linting-and-formatting
Skill976 starsChanged 22 days agoApache-2.0View on GitHub
Code style and quality rules for Megatron Bridge — ruff configuration, naming conventions, type hints, mypy rules, docstrings, copyright headers, logging, and the code review checklist.
We split this skill into the rules it gives an agent
11 rules. About 0 are common, 6 are distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 21
Run before every commit:
- Distinctive: line 71
Avoid shadowing variables from an outer scope.
- Very specific: line 88
Use T | None instead of Optional[T]
- Very specific: line 90
Use built-in generics (list, dict, tuple) instead of typing equivalents
- Distinctive: line 103
Run on changed files before submitting:
- Very specific: line 121
When a function has multiple parameters of the same type that could be swapped by mistake, use * to force keyword-only arguments.
- Very specific: line 164
Use logging.getLogger(__name__) for module-level loggers.
- Distinctive: line 178
Use specific exceptions. Keep try bodies minimal.
- Very specific: line 204
Use dataclasses or NamedTuple for configuration objects.
- Distinctive: line 205
Do not add arbitrary defaults — be explicit about required vs optional fields.
- Distinctive: line 209
Add to all new Python files and shell scripts (not test files).
≈ “Common” is an estimate: at least 1 in 5 of the 308,232 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Linting and Formatting
Single source of truth for code style in Megatron Bridge. Read this before writing new code or reviewing PRs.
Style Guides
- Python: Google Python Style Guide
- Shell: Google Shell Style Guide
Target Python 3.10+.
Formatting and Linting
Run before every commit:
uv run ruff check --fix .
uv run ruff format .Pre-commit hooks run these automatically. If hooks auto-fix files, re-stage and re-run until clean:
git add -u
pre-commit run
# if it auto-fixed files:
git add -u
pre-commit runRuff Rules (from ruff.toml)
| Rule | ID | Description |
| Line length | — | 119 characters (formatter) |
| Quote style | — | Double quotes |
| f-string without placeholders | F541 | Error |
| Unused local variable | F841 | Auto-removed by --fix |
| Unused import | F401 | Auto-removed by --fix (ignored in __init__.py) |
| Ambiguous variable name | E741 | Error (e.g., l, O, I) |
| Undefined name | F821 | Error |
| Block comment format | E266 | Error (too many #) |
| Import sorting | I | isort-compatible, auto-fixed |
| Public class docstring | D101 | Warning (ignored in test files) |
| Public function docstring | D103 | Warning (ignored in test files) |
Per-file overrides:
__init__.py: F401 and F403 ignored (re-exports expected).test_*.py,*_test.py,tests/*.py: D101 and D103 ignored.
Naming Conventions
| Kind | Convention | Example |
| Files | snake_case | model_bridge.py |
| Classes | PascalCase | MegatronModelBridge |
| Functions/methods | snake_case | load_weights_hf_to_megatron |
| Local variables | snake_case | megatron_weights |
| Variables starting with digit | prefix k | k_99th_percentile |
| Global variables | UPPER_SNAKE + prefix G | G_LOGGER |
| Constants | UPPER_SNAKE | DEFAULT_HIDDEN_SIZE |
- Avoid shadowing variables from an outer scope.
- Initialize all externally visible class members in the constructor.
Import Order
__future__imports- Standard library
- Third-party (
megatron.core,torch,transformers, etc.) - First-party (
megatron.bridge.*) - Local folder imports
Separate groups with blank lines. ruff auto-fixes via the I rule.
Type Hints
Required on all public API functions and methods.
- Use
T | Noneinstead ofOptional[T] - Use
X | Yinstead ofUnion[X, Y] - Use built-in generics (
list,dict,tuple) instead oftypingequivalents
def get_module_by_name(
model: torch.nn.Module,
name: str,
default: torch.nn.Module | None = None,
) -> torch.nn.Module | None:
...Mypy
Run on changed files before submitting:
uv run mypy --strict path/to/file.pyKey rules:
- No
Anyleaks — useobjectfor unknown types or aTypeVarfor generics. - No untyped defs — every function must have parameter and return annotations.
- No implicit
Optional— writex: int | None = None, neverx: int = None. - Explicit casts — use
typing.cast()only when inference fails; add a comment. - Typed dictionaries — prefer
TypedDictoverdict[str, Any]for structured dicts. - Callable signatures — use
Callable[[ArgType], ReturnType]orProtocol. - Ignore sparingly —
# type: ignore[code]must include the error code and justification.
Keyword-Only Arguments for Ambiguous Parameters
When a function has multiple parameters of the same type that could be swapped
by mistake, use * to force keyword-only arguments.
# Don't
def scatter_weights(tensor: Tensor, tp_group: ProcessGroup, ep_group: ProcessGroup): ...
# Do
def scatter_weights(tensor: Tensor, *, tp_group: ProcessGroup, ep_group: ProcessGroup): ...Docstrings
Google-style for public classes and functions:
def convert_weights(
source_model: torch.nn.Module,
target_model: torch.nn.Module,
mapping: MegatronParamMapping,
) -> dict[str, torch.Tensor]:
"""Convert weights from source to target model format.
Args:
source_model: The source model containing weights to convert.
target_model: The target model that will receive converted weights.
mapping: Parameter mapping defining the conversion rules.
Returns:
Dictionary mapping parameter names to converted weight tensors.
Raises:
ValueError: If source and target models have incompatible shapes.
"""Comments
- Commented-out code must have a comment explaining why. Otherwise remove it.
- Comments explain non-obvious intent, trade-offs, or constraints — not what the code does.
Logging
Use logging.getLogger(__name__) for module-level loggers. Use print_rank_0
/ warn_rank_0 for user-facing messages in distributed contexts.
# Don't
print(f"Loading weights for {model_name}")
# Do
logger = logging.getLogger(__name__)
logger.info("Loading weights for %s", model_name)Error Handling
Use specific exceptions. Keep try bodies minimal.
try:
state_dict = torch.load(path)
except FileNotFoundError:
raise ValueError(f"Checkpoint not found at {path}") from None
else:
result = convert(state_dict)Avoid Reflection
# Don't
def make_config(*args):
x, y = args
return dict(**locals())
# Do
def make_config(x, y):
return {"x": x, "y": y}Configuration and Dataclasses
- Use
dataclassesorNamedTuplefor configuration objects. - Do not add arbitrary defaults — be explicit about required vs optional fields.
NVIDIA Copyright Header
Add to all new Python files and shell scripts (not test files). Use the current year.
# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.Code Review Checklist
- Copyright header present on new Python files (not test files)
- Type hints on public functions and methods
- Docstrings on public classes and functions (Google style)
- Specific exceptions in try-except blocks
- No bare
print()— useloggerorprint_rank_0 - No hidden defaults in config function parameters
- Keyword-only args for ambiguous same-type parameters
- Double quotes for strings
- Import order follows the 5-group convention
- No commented-out code without explanation
- Mypy clean — no untyped defs, no
Anyin public APIs, no bare# type: ignore
Other versions2 projects use a version of this.
Word for word · 0
None found.
Edited · 1
- NVIDIA-NeMo/Automodel★ 1.1k26% same
Wrote their own version · 1
- NVIDIA-NeMo/RL★ 2.1ksame name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository35 other files it gives its agents.
- AGENTS.mdAGENTS.md
- adding-model-supportSkill
- build-and-dependencySkill
- bump-dependencySkill
- cicdSkill
- create-model-verification-cardSkill
- nemo-mbridge-memory-snapshot-analysisSkill
- nemo-mbridge-mlm-bridge-trainingSkill
- nemo-mbridge-multi-node-slurmSkill
- nemo-mbridge-perf-activation-recomputeSkill
- nemo-mbridge-perf-cpu-offloadingSkill
- nemo-mbridge-perf-cuda-graphsSkill
- nemo-mbridge-perf-expert-parallel-overlapSkill
- nemo-mbridge-perf-hierarchical-context-parallelSkill
- nemo-mbridge-perf-megatron-fsdpSkill
- nemo-mbridge-perf-memory-tuningSkill
- nemo-mbridge-perf-moe-comm-overlapSkill
- nemo-mbridge-perf-moe-dispatcher-selectionSkill
- nemo-mbridge-perf-moe-hardware-configsSkill
- nemo-mbridge-perf-moe-long-contextSkill
- nemo-mbridge-perf-moe-optimization-workflowSkill
- nemo-mbridge-perf-moe-vlm-trainingSkill
- nemo-mbridge-perf-nsys-analysisSkill
- nemo-mbridge-perf-parallelism-strategiesSkill
- nemo-mbridge-perf-sequence-packingSkill
- nemo-mbridge-perf-tp-dp-comm-overlapSkill
- nemo-mbridge-perf-vision-dp-over-cpSkill
- nemo-mbridge-recipe-recommenderSkill
- nemo-mbridge-resiliencySkill
- nemo-rl-e2e-testingSkill
- parity-testingSkill
- pr-reviewSkill
- review-prSkill
- testingSkill
- verl-e2e-testingSkill
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

