Repository navigation
fix(dtensor): merge LoRA into refit weights under checkpoint wrappers - #4259
Closed
zhiyuanma-agents wants to merge 2 commits into
Closed
zhiyuanma-agents wants to merge 2 commits into
zhiyuanma-agents wants to merge 2 commits into
Conversation
`dtensor_params_generator` resolves each `state_dict()` key back to its owning module through `dict(model.named_modules())` so that `LinearLoRA` adapters can be merged into the base weight before the tensor is streamed to the inference engine. Those two spellings disagree as soon as a module sits behind a wrapper that `state_dict()` does not name: the activation checkpoint `CheckpointWrapper` (`layers.0._checkpoint_wrapped_module.mlp` vs `layers.0.mlp.weight`) and `torch.compile`'s `OptimizedModule` (`_orig_mod.`). The lookup then misses, `_maybe_merge_lora_weight` is never reached, and the unmerged base weight is refit every step. With `policy.dtensor_cfg.activation_checkpointing: true` and LoRA this silently freezes the sampler at the initial policy for the entire run: training becomes off-policy against a stale generator, the generation KL error grows monotonically, and validation stays flat while the trainer reports normal losses. Observed on Nemotron 3.5 Super (MoE) GRPO/GSPO LoRA runs where every layer is checkpoint-wrapped, so 0 of 1867 refit tensors carried the adapter. Fix: build the module map keyed by the state-dict spelling as well as the raw `named_modules()` name, stripping the known transparent wrapper prefixes, and use it in `dtensor_params_generator`. Tests: `TestLoRAMergeUnderStateDictTransparentWrappers` builds a tiny LoRA-patched linear behind `checkpoint_wrapper` and asserts (a) the two namespaces disagree, (b) the map resolves the state-dict key to the `LinearLoRA`, (c) the generator streams the merged weight. (b) and (c) fail on main and pass with this change. Signed-off-by: Zhiyuan Ma <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Zhiyuan Ma <[email protected]>
`_maybe_merge_lora_weight` cast `lora_A`/`lora_B` to the base weight's dtype and computed `W + (B @ A) * scale` there. With a bf16 policy that rounds twice (the delta, then the sum), so the tensor handed to the generation engine differs from an offline merge (`W.float() + (B.float() @ A.float()) * scale`, then one cast) by up to one bf16 ulp per element. The engine then samples from weights that are not quite the checkpoint that will be evaluated and served. Promote the base weight and both adapters to fp32, merge, and cast once to the base dtype. Transient cost is one fp32 copy of a single weight at a time. Test: `test_bf16_merge_matches_fp32_offline_merge_exactly` builds a 64x64 bf16 LoRA layer behind `checkpoint_wrapper` and requires the refit tensor to equal the offline fp32 merge bit for bit; it fails on the previous commit (double rounding) and passes with this change. Signed-off-by: Zhiyuan Ma <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Zhiyuan Ma <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What does this PR do ?
Fix
dtensor_params_generatorso LoRA adapters are merged into refit weights when the owning module sits behind an activation-checkpoint (CheckpointWrapper) ortorch.compile(_orig_mod) wrapper; today the lookup misses and the inference engine keeps sampling from the base policy.Symptom
With
policy.dtensor_cfg.activation_checkpointing: true+ LoRA (DTensor policy worker v2), every refit streams the unmerged base weight. The generator is silently frozen at the initial policy for the whole run:merge_loras_to_hf.py-style) do moveObserved on Nemotron 3.5 Super (120B-A12B MoE) GRPO/GSPO LoRA runs where every decoder layer is checkpoint-wrapped: 0 of 1867 refit tensors carried the adapter, across five runs, until we patched the worker.
Root cause
dtensor_params_generatorresolves eachstate_dict()key to its owning module viadict(model.named_modules()), then calls_maybe_merge_lora_weightif that module is aLinearLoRA. The two namespaces disagree under wrappers thatstate_dict()does not spell out:named_modules()layers.0._checkpoint_wrapped_module.mlpstate_dict()layers.0.mlp.weightSo
module_map.get("layers.0.mlp")returnsNone, the LoRA branch is skipped, and the base weight is yielded as-is. Same story fortorch.compile'sOptimizedModule(_orig_mod.).Fix
_STATE_DICT_TRANSPARENT_PREFIXES = ("_checkpoint_wrapped_module.", "_orig_mod.")_state_dict_module_name(name)strips thembuild_state_dict_module_map(model)keys every module by both the state-dict spelling and the rawnamed_modules()name (setdefault, so an unwrapped module is never shadowed)dtensor_params_generatoruses that map instead ofdict(model.named_modules())No behaviour change when no wrapper is present (the raw names are still in the map).
Issues
None filed yet; happy to open one if maintainers prefer an issue to track this.
Usage
No user-facing API change. Any LoRA config with activation checkpointing on now refits the merged weight:
Before your PR is "Ready for review"
Pre checks:
Additional Information
Tests —
tests/unit/models/policy/test_dtensor_worker_v2.py::TestLoRAMergeUnderStateDictTransparentWrappersbuilds a tiny LoRA-patchednn.Linear(patch_linear_module, randomlora_A/lora_Bso the merge is not a no-op) behindcheckpoint_wrapperand asserts:named_modules()andstate_dict()disagree on the name (documents the trigger)build_state_dict_module_mapresolves the state-dict key to theLinearLoRAdtensor_params_generatorstreams the merged weight (W + scale · B @ A)(2) and (3) fail on
main, all three pass with this change. Run inside the NeMo RL training image against the DTensor worker venv;ruff check/ruff formatclean.Evidence from a real run — with this change applied to the worker inside our training image (Nemotron 3.5 Super, LoRA r=32 on the attention/latent/shared-expert projections, activation checkpointing on), the refit now reports
streaming 272 of 1867 tensorscarrying a LoRA delta on all 8 ranks; the same run without the change reported0 of 1867on every step. Resuming that run from its step-20 checkpoint with the fix (same seed weights, same config): at the first step the trainer-vs-generator "Generation KL Error" is 0.0049 versus 0.0096 for the same step without the fix (where it kept climbing to 1.0 by step 35), the weight transfer takes 1.99 s instead of 0.21 s (adapters now move), and the average rollout reward is .753 versus .727 because the engine finally samples from the trained policy instead of the initial one. Over the next two steps the KL error stays at .0049 / .0051 (transfer 2.1 / 2.5 s), i.e. trainer and generation engine agree after every refit; without the fix the same quantity had climbed monotonically to .03 by step 25 and 1.0 by step 35.Second commit — merge in fp32, round once. The merge computed
W + (B @ A) * scalein the base dtype (bf16), rounding twice, so the refit tensor could differ from an offline fp32 merge of the same checkpoint by one bf16 ulp per element. It now promotes to fp32 and casts once;test_bf16_merge_matches_fp32_offline_merge_exactlyrequires bit-equality with the offline merge (fails on the first commit alone, passes with the second). Happy to drop this commit if maintainers prefer to keep the PR to the module-map fix.Scope note — Automodel's
nemo_automodel.shared.parameter_names.canonical_parameter_fqndoes the same prefix stripping on its side; this PR keeps the fix local to the worker so it does not depend on the Automodel version pinned by NeMo RL. Happy to switch to that helper if maintainers prefer.Opened as a draft for maintainer feedback.
🤖 Generated with Claude Code