Skip to content

fix(dtensor): merge LoRA into refit weights under checkpoint wrappers - #4259

Closed
zhiyuanma-agents wants to merge 2 commits into
NVIDIA-NeMo:mainfrom
zhiyuanma-agents:fix/lora-refit-module-map-wrappers
Closed

zhiyuanma-agents wants to merge 2 commits into
NVIDIA-NeMo:mainfrom
zhiyuanma-agents:fix/lora-refit-module-map-wrappers

Conversation

@zhiyuanma-agents

@zhiyuanma-agents zhiyuanma-agents commented Sep 24, 2026 •

Copy link
Copy Markdown

What does this PR do ?

Fix dtensor_params_generator so LoRA adapters are merged into refit weights when the owning module sits behind an activation-checkpoint (CheckpointWrapper) or torch.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:

  • trainer losses look normal, but the sampler never moves → training is off-policy against a stale generator
  • "Generation KL Error" grows monotonically step over step
  • in-job validation stays flat (or drifts) while checkpoints merged offline (merge_loras_to_hf.py-style) do move

Observed 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_generator resolves each state_dict() key to its owning module via dict(model.named_modules()), then calls _maybe_merge_lora_weight if that module is a LinearLoRA. The two namespaces disagree under wrappers that state_dict() does not spell out:

source name
named_modules() layers.0._checkpoint_wrapped_module.mlp
state_dict() layers.0.mlp.weight

So module_map.get("layers.0.mlp") returns None, the LoRA branch is skipped, and the base weight is yielded as-is. Same story for torch.compile's OptimizedModule (_orig_mod.).

Fix

  • _STATE_DICT_TRANSPARENT_PREFIXES = ("_checkpoint_wrapped_module.", "_orig_mod.")
  • _state_dict_module_name(name) strips them
  • build_state_dict_module_map(model) keys every module by both the state-dict spelling and the raw named_modules() name (setdefault, so an unwrapped module is never shadowed)
  • dtensor_params_generator uses that map instead of dict(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:

policy:
  dtensor_cfg:
    activation_checkpointing: true
  peft:
    enabled: true

Before your PR is "Ready for review"

Pre checks:

  • Make sure you read and followed Contributor guidelines
  • Did you write any new necessary tests?
  • Did you run the unit tests and functional tests locally? Visit our Testing Guide for how to run tests
  • Did you add or update any necessary documentation? (none needed; internal fix)

Additional Information

Tests — tests/unit/models/policy/test_dtensor_worker_v2.py::TestLoRAMergeUnderStateDictTransparentWrappers builds a tiny LoRA-patched nn.Linear (patch_linear_module, random lora_A/lora_B so the merge is not a no-op) behind checkpoint_wrapper and asserts:

  1. named_modules() and state_dict() disagree on the name (documents the trigger)
  2. build_state_dict_module_map resolves the state-dict key to the LinearLoRA
  3. dtensor_params_generator streams 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 format clean.

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 tensors carrying a LoRA delta on all 8 ranks; the same run without the change reported 0 of 1867 on 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) * scale in 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_exactly requires 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_fqn does 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

`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]>
@copy-pr-bot

copy-pr-bot Bot commented Sep 24, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

`_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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant