Add sound type annotations: distributed execution and cuda graphs
Parent: NVIDIA-NeMo/Automodel#4607 / GitHub #4607.
Scope: Distributed execution and CUDA graphs
distributed/: Distributed configs, mesh/process-group contracts, and parallelizer inputs/returns. Coordinate with AM-997; do not fold the MeshContext migration into an annotation PR.cuda_graphs/: Partial graph capture/replay interfaces, callable signatures, buffers, and lifecycle state; preserve capture behavior.
Suggested first contribution
Pick one module below, inspect its actual callers, and propose a few missing/imprecise signatures or one boundary contract. Already-correct code needs no cosmetic rewrite. Claim the slice in this issue before starting; keep the group open until its remaining scope is covered.
Required annotation-policy branch
Until draft PR #4653 is merged, base annotation work on akoumpa/ci/annotation-policy from akoumpa/Automodel. This branch adds the annotation-policy checker alongside ty; it is not yet part of upstream main. Current policy commit: ef93d5e70.
From a clean checkout, create your contribution branch with:
git fetch https://github.com/akoumpa/Automodel.git akoumpa/ci/annotation-policy
git switch -c my-annotation-slice FETCH_HEAD
For an existing contribution branch, fetch the same policy branch and merge FETCH_HEAD into your branch instead of creating a new one. Link #4653 as a dependency in your PR; after it merges, update your branch onto upstream main.
Run the shared entry point from the repository root in the configured development environment:
uv run --group linting python tools/check_types.py
ty.toml owns type-checker settings and the existing opt-in module list. tools/annotation_policy.toml owns exact annotation-slot exceptions and the legacy inventory. New object annotations fail unless a maintainer reviews a specific exception with a reason for genuinely opaque values. Do not add to or increase the legacy inventory; remove/reduce entries when fixing their annotations. Runtime object() sentinels and Literal/Annotated metadata are unaffected.
The policy scans nemo_automodel and examples, but ty still checks only its configured opt-in modules through this entry point. Also run a targeted uv run --group linting ty check <affected-path> for your slice when it falls outside that scope, and report any exclusions or missing dependencies. A passing policy check does not establish type soundness: it does not infer types or resolve cross-module aliases, and all requirements below still apply.
Annotation requirements (applies to every sub-issue)
Read CODING_GUIDELINES.md and AGENTS.md. This campaign requires real contracts, not annotation-count improvements alone.
- Trace actual callers and implementations before choosing types. Annotate parameters, returns, and relevant stored attributes; include
-> Nonefor constructors and methods that return nothing. Preserve supported inputs, defaults, return forms, and subclass compatibility. - Use concrete types and parameterized containers. Prefer
Sequence[T],Mapping[K, V],Iterable[T], and precisely typed callbacks when those are the operations the consumer needs. UseT | Noneonly whenNonereally is supported, and narrow it before use. - Reuse existing typed configs and interfaces. Use small consumer-owned
Protocols for genuine structural contracts,TypedDictfor fixed-key records, and dataclasses for owned configuration/state. Use generics and overloads only for relationships demonstrated by real callers. Do not introduce cross-component imports or move types intosharedmerely to evade import boundaries. - No
Any, including nestedAny, aliases to it,**kwargs: Any, or newly propagated implicit Any from untyped containers/callbacks/decorators/dependencies. No baredict,list,Callable, orCallable[..., ...]used to erase a known signature. Parameterize generic bases as well. - No escape hatches: do not add
typing.cast,# type: ignore,# ty: ignore,# pyright: ignore,@no_type_check, blanketnoqa, checker exclusions, disabled diagnostics, or fake stubs/protocols that merely assert an unverified interface. Existing suppressions are not precedent; remove them in the completed slice where feasible and explicitly track anything that remains. objectis valid for a genuinely opaque value or an unvalidated boundary input, not as a replacement forAnyor a bag that hides a known schema. Validate external data at its boundary; do not add reflection, speculativegetattr/hasattr, runtime-checkable Protocol probes, or assertions solely to convince the checker. Retain real validation and supported compatibility behavior.- For untyped third-party APIs, first use available upstream types; otherwise provide a narrow, truthful boundary adapter/stub whose contract is verified against the supported dependency. Do not spread dependency uncertainty through component interfaces. Report a blocked boundary instead of masking it.
torch.Tensordoes not encode shape, dtype, device, or distributed placement. Document relevant tensor and semantic contracts, including axis order, optional fields, aliasing, token/label alignment, and storage versus compute dtype where applicable.- Preserve runtime behavior, public APIs, optional-dependency import safety, and tensor math. Use deferred annotations /
TYPE_CHECKINGimports where appropriate without making runtime annotation consumers fail. No new import-time GPU/dependency requirements. Keep behavioral fixes and broad refactors separate.
Validation and completion
- Claim a small slice (one module or a few related functions) in the sub-issue before implementation. Inspect current main: already-correct code needs no cosmetic rewrite. Larger components require multiple small PRs; one starter PR does not complete the component.
- Record before/after missing or imprecise signatures and remaining
Any/suppression sites for that slice. Use the repository's annotation coverage reporter / Python annotation coverage CI as supporting evidence, not proof of type soundness. - Run
uv run --group linting python tools/check_types.pyfrom the annotation-policy branch, plus targetedtychecking and Ruff on the affected files, and appropriate existing tests. Record exact commands, dependency versions, results, and any pre-existing diagnostics. Confirm the changed files were actually checked;ty.tomlcurrently excludes checkpoint_backportsand relaxes some diagnostics. Do not weaken configuration. If a slice is excluded, supply a targeted check that includes it and report the limitation. - Audit actual callers and concrete implementations against the declared contracts; a green checker with untyped dependencies is insufficient. Run import checks for optional-dependency/type-only import changes. If runtime tensor/distributed behavior changes, require the corresponding real forward/backward or multi-process validation rather than mocks alone.
- A completed slice has fully specified, truthful contracts with no new escape hatches and no new diagnostics. Keep the group issue open until remaining public APIs/config contracts and required internal helpers are covered, or explicitly document an audited no-change result. Keep the parent table current when group work is complete.
Hello, I'd like to take the capture_owner and target type fixes in cuda_graphs/partial.py.
Issue
A few values in partial.py have the wrong type or are typed Any:
capture_owneris typed as a plainnn.Module, but it is always an FSDP module.- The adapter's
targetis set throughself.__dict__, which the type checker can't see. - Some values with known types are typed
Any, and three__init__s are missing-> None.
Why it's a problem
- The type checker reports 4 errors. CI doesn't check this folder, so nobody saw them.
- Because of the wrong types, the checker can't properly check the FSDP capture code or the replay check.
Suggested fix
- Type
capture_ownerasFSDPModule | None. The code that creates it already makes sure it's an FSDP module. - Declare
targeton the class. - Replace the
Anys with the real types and add-> None.
How the fix solves it
- The types now match what the code actually uses, so the 4 errors go away (23 → 19 on this file).
- Only type hints change, so the code runs exactly the same.
Tests
- The existing
test_partial.pytests pass before and after. They run on CPU, no GPU needed. - An import check confirms nothing new loads at runtime.
- Type check and lint results before and after go in the PR: 4 errors removed, none added.
Not in this PR
The other 19 type-checker issues. Most need a design decision about how from_model_parts reads backend.cuda_graph.modules: should the recipe pass the module names in, or should the manager define a small protocol? Happy to take that next.
Hello, I'd like to take the distributed/config.py slice — specifically tightening the imprecise signatures there (e.g. normalize_activation_checkpointing_scope(value: Any), the bare Dict/List usages in the ActivationCheckpointingScope alias and remaining unparameterized annotations), based on the annotation-policy branch per the instructions.
Hi @akoumpa, I'd like to take the distributed/tensor_utils.py and distributed/grad_utils.py slice in this group.
Plan:
- Add missing parameter and return annotations in ensor_utils.py ( o_cpu, PEP 604 unions).
- Narrow parameters to Iterable[torch.Tensor | DTensor] | torch.Tensor | DTensor and add -> None return type to clip_grad_by_total_norm_ in grad_utils.py.
- Clean up tensor accumulation in get_grad_norm, removing the unused # type: ignore suppressions.
- Add both files to y.toml overrides and verify clean ools/check_types.py and unit tests.
Hi @akoumpa, I'd like to take the \distributed/init_utils.py\ and \distributed/utils.py\ slice in this group.
Plan:
- Type \initialize_distributed\ and \destroy_global_state\ in \init_utils.py, pass typed arguments to \init_process_group, and ensure \DistInfo.device\ is consistently a \ orch.device.
- Type \FirstRankPerNode.enter/_exit_, \get_sync_ctx, and \dp_eval_sample_shard\ in \utils.py, import \ orch.distributed.fsdp\ explicitly, and remove unused \Any.
- Add unit tests for \initialize_distributed\ and \dp_eval_sample_shard.
- Add both files to \ y.toml\ overrides, verify \ ools/check_types.py, and run the unit tests.
Thank you @taran-dev4u taking a look now;
For anyone else interested in contributing, please, announce here to claim the work (& duplicate) and go ahead with opening a PR.
Thank you all
Hi @akoumpa, I'd like to take the \distributed/thd_utils.py\ and \distributed/tp_replicas.py\ slice in this group.
Plan:
- Type \process_input_for_thd\ and \split_batch_into_thd_chunks\ return dictionaries as \dict[str, torch.Tensor | bool]\ in \ hd_utils.py, type \pad_and_stack, and remove bare \dict\ annotations.
- Register both \ hd_utils.py\ and \ p_replicas.py\ in \ y.toml\ overrides.
- Add unit tests for \ p_replicas.py\ helpers and \ hd_utils.py\ return structure.
- Verify clean \ ools/check_types.py, \ uff check, and full test suite.