Skip to content

[bugfix]: Preserve accumulated LoRA adapters across unmerge - #2109

Open
xxdydx wants to merge 6 commits into
hao-ai-lab:mainfrom
xxdydx:fix/lora-accumulation-roundtrip
Open

xxdydx wants to merge 6 commits into
hao-ai-lab:mainfrom
xxdydx:fix/lora-accumulation-roundtrip

Conversation

@xxdydx

@xxdydx xxdydx commented Nov 14, 2026 •

Copy link
Copy Markdown

Purpose

Fixes #2096.

Accumulating multiple LoRA adapters previously preserved their combined contribution only while merged. Unmerging and remerging silently dropped every adapter except the latest.

For the issue’s BF16 example, this changes the outputs from 34 → 30 → 30 to 34 → 34 → 34.

Changes

  • Keep one authoritative CPU history of active inference adapter contributions, including each adapter’s factors and scale.
  • Rebuild merged weights from the original base snapshot, preserving contribution order and avoiding duplicate additions during repeated normal merges.
  • Stage historical factors as registered, non-persistent buffers only during unmerged inference, allowing module movement and layerwise offloading to manage their storage.
  • Release staged historical factors when merging, replacing, or clearing adapters.
  • Reuse the active stack for NVFP4 replay instead of independently accumulating another history.
  • Preserve live parameters for the current adapter so training gradients and current strength changes continue to work.
  • Add regression coverage for lifecycle transitions, device movement, offloader visibility, and avoiding CPU-history transfers during forward.
  • Preserve earlier contributions when an accumulated adapter skips a layer, and restore weights and history if a merge fails part-way.
  • Run the merge-math tests in the unit CI lane and remove the resolved accumulation limitation from the H3 LoRA guide.
  • Add CUDA-gated tests for real layerwise offloading and Inductor execution with one, two, and four adapters.

The change retains the existing training framework, quantization kernels, and public accumulation behavior.

Test Plan

Earlier revisions were validated locally on macOS arm64. The latest CPU rerun attempt used Python 3.12.1 and PyTorch 2.4.0; see the result below.

npm ci --prefix docs
pre-commit run --all-files

Targeted LoRA suite command, including CPU training and offload ownership checks:

/tmp/fastvideo-2096-venv/bin/python -m pytest \
  fastvideo/tests/inference/lora/test_merge_lora_math.py \
  fastvideo/tests/layers/test_lora_merge_precision.py \
  fastvideo/tests/layers/test_lora_side_branch.py \
  fastvideo/tests/ops/quantization/test_nvfp4_lora_accumulation.py \
  fastvideo/tests/ops/quantization/test_nvfp4_minimax_h3_wiring.py \
  fastvideo/tests/loader/test_h3_community_lora.py \
  fastvideo/tests/loader/test_lora_patch.py \
  fastvideo/tests/pipelines/test_lora_adapter_switch.py \
  fastvideo/tests/pipelines/test_lora_lazy_reload.py \
  fastvideo/tests/pipelines/test_lora_sequential_load.py \
  fastvideo/tests/pipelines/test_lora_late_transformer.py \
  fastvideo/tests/entrypoints/test_openai_lora.py \
  fastvideo/tests/train/models/test_minimax_h3_lora.py \
  fastvideo/tests/train/utils/test_lora.py \
  fastvideo/tests/train/utils/test_lora_fsdp.py \
  fastvideo/tests/train/utils/test_dcp_to_diffusers_lora_names.py \
  fastvideo/tests/train/utils/test_dcp_to_diffusers_h3.py \
  fastvideo/tests/train/utils/test_inference_checkpoint.py \
  fastvideo/tests/contract/test_env_policy.py \
  fastvideo/tests/hooks/test_layerwise_offload.py \
  fastvideo/tests/hooks/test_pinned_memory.py \
  -m 'not gpu' -q -ra \
  --junitxml=/tmp/fastvideo-2096/cpu-offload-results.xml

Test Results

Local validation results

Latest follow-up (2026-11-20):

  • pre-commit run --files docs/inference/h3_community_lora.md passed all applicable hooks.
  • git diff --check passed.
  • The targeted CPU command above stopped while loading conftest.py: ModuleNotFoundError: No module named 'cloudpickle'. No tests ran in this attempt; the earlier revision's totals have been removed.

The earlier full pre-commit run passed:

pre-commit run --all-files

yapf                                  Passed
ruff                                  Passed
codespell                             Passed
PyMarkdown                            Passed
Lint GitHub Actions workflow files     Passed
mypy                                  Passed
Check for spaces in all filenames      Passed
Cookbook JavaScript lint and format    Passed
Suggestion                            Passed

Earlier CPU validation covered:

  • Accumulated-adapter merge/unmerge/remerge outputs.
  • Replacement, differing ranks/scales, and repeated normal merges.
  • Live current-adapter factor and strength updates.
  • Training gradients, optimizer updates, two-process CPU gradient synchronization, and FSDP checkpoint resume.
  • CPU NVFP4 lifecycle contracts and shared replay-history assertions.
  • Device movement and offloader discovery of staged historical factors.
  • Verification that forward does not transfer CPU replay-history tensors on every call.
State Before After Expected
Merged 34 34 34
Unmerged 30 34 34
Remerged 30 34 34

CUDA-dependent coverage, including the GPU offload and Inductor tests, requires GPU hardware.

The full repository CPU suite, end-to-end GPU training, SSIM, real NVFP4 GPU execution, and GPU memory/latency benchmarks remain outstanding. CPU graph-capture tests do not establish CUDA Inductor or CUDA Graph correctness.

Checklist

  • I ran pre-commit run --all-files and fixed all issues.
  • I added or updated tests for my changes.
  • I updated documentation if needed.
    • Existing public API and configuration behavior are preserved; ownership and lifecycle behavior are documented in code.
  • I considered GPU memory impact of my changes.
    • Replay snapshots stay on CPU. Historical device factors are registered for offloading and released when no longer needed.
    • Actual GPU memory and latency measurements remain outstanding.
  • I verified SSIM regression tests pass.
    • Not run on this Mac.

Support-matrix changes, serving YAML, and cookbook deployment updates are not applicable: this fixes the existing adapter lifecycle and introduces no new model or serving runtime.

@mergify

mergify Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Merge Protections

🔴 1 of 1 protections blocking · waiting on 👀 reviews and 🤖 CI

Protection Waiting on
🔴 PR merge requirements 👀 reviews and 🤖 CI

🔴 PR merge requirements

Waiting for

  • #approved-reviews-by>=1
  • check-success=full-suite-passed
This rule is failing.
  • #approved-reviews-by>=1
  • check-success=full-suite-passed
  • check-success=fastcheck-passed
  • check-success~=pre-commit
  • title~=(?i)^\[(feat|feature|bugfix|fix|refactor|perf|ci|doc|docs|misc|chore|kernel|new.?model|skill|skills|infra)\]

@mergify mergify Bot added type: bugfix Bug fix scope: infra CI, tests, Docker, build scope: model Model architecture (DiTs, encoders, VAEs) labels Nov 14, 2026
@mergify mergify Bot added the needs-rebase PR has merge conflicts label Nov 15, 2026
@mergify mergify Bot removed the needs-rebase PR has merge conflicts label Nov 17, 2026
@xxdydx
xxdydx marked this pull request as ready for review November 17, 2026 03:57
@mergify

mergify Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue). If it does not match the queue conditions yet, it enters the queue once it does.

  • Queue this pull request

@aryan5v

aryan5v commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

@fv-superagent review

@greptile-apps

greptile-apps Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The documentation follow-up appears safe to merge, with no new blocking issues found.

Summary

Preserves accumulated LoRA adapters across merge, unmerge, and remerge.

  • Accumulated LoRA adapters keep their combined effect through unmerge and remerge.
  • Earlier adapter factors move with unmerged layers and can be offloaded.
  • Adapter switches keep each layer’s contributions aligned with the active stack.

No new actionable issues were found in the documentation-only follow-up. The earlier comment-rule thread was manually resolved without explanation.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A["Merged adapters"] -->|Unmerge| B["Base weight + staged earlier adapters + live current adapter"]
  B -->|Merge in saved order| A
  A -->|Replace or clear| C["Release saved contributions"]
  B -->|Replace or clear| C
Loading

Reviews (3) · Last reviewed commit: "fix: Remove outdated note on unmerging m..." · Reviewed by Greptile

Comment thread fastvideo/layers/lora/linear.py Resolved
Comment thread fastvideo/layers/lora/linear.py Resolved

@fv-superagent fv-superagent left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fv-superagent score: 3/5

The core fix is right: tracing the adapter state machine, the reported 34 → 30 → 30 sequence becomes 34 → 34 → 34, and the accumulated history survives unmerge. Two state-machine bugs and two small follow-ups remain.

Must fix

  • fastvideo/layers/lora/linear.py:294 — a layer that an accumulated adapter skips keeps its earlier adapter but gets disable_lora=True (fastvideo/pipelines/lora_pipeline.py:737). The next accumulated adapter on that layer hits the new not self.disable_lora guard and calls _reset_to_base_weight(), dropping the earlier adapter. Sequence: load A over layers 1+2 → accumulate B over layer 1 only → accumulate C over layer 2 only → layer 2 ends at C alone instead of A+C. main gets A+C here, so this is a regression. Decide "already has contributions" from the layer state (self.merged / self._active_loras), not disable_lora: a layer unmerged by a replacement must still reset, an actively merged-then-skipped layer must not. Add the three-adapter sequence to fastvideo/tests/pipelines/test_lora_adapter_switch.py (the existing two-adapter test stops before the reset).
  • fastvideo/layers/lora/linear.py:346 — merge_lora_weights() calls _reset_to_base_weight() (which clears _active_loras) before replaying. If one contribution fails — a CUDA OOM in the matmul is enough — the method exits with history gone and the weight partially merged. A retry then replays only the current adapter; a snapshot-free (unified-memory) layer additionally raises no unmerge snapshot on the next reset. _restore_merged_weight already guards this with a try/except; make the replay path keep the previous weight and _active_loras until the whole replay succeeds, and test a failure part-way through the loop (the analogous set_lora_weights path already has such a test).

Should fix

  • fastvideo/tests/inference/lora/test_merge_lora_math.py is collected by no lane: unit_test.sh lists tests/inference/test_basic_* but not inference/lora/, and .buildkite/scripts/lanes/inference_lora.sh:6 collects only test_lora_inference_similarity.py. The issue's scalar 34 → 30 → 30 regression test therefore does not guard the fix (the lifecycle coverage in test_lora_side_branch.py and test_nvfp4_lora_accumulation.py does run). Add the file to unit_test.sh or the lane script — one line.
  • docs/inference/h3_community_lora.md:99 still says "Unmerging multiple accumulated adapters currently drops earlier contributions from inference (#2096)". That is the bug this PR fixes, so the doc now contradicts the code.

Nits

  • fastvideo/tests/inference/lora/test_merge_lora_math.py:78 — Greptile's P2 asks for this arithmetic comment to go. I would keep it: 34 is otherwise a magic number and the line documents the invariant. Not a blocker either way.
  • fastvideo/layers/lora/linear.py:458 — _clear_lora_history() resets _active_loras and the staged buffers but not _merged_loras. Both call sites happen to have _merged_loras == [] already because unmerge_lora_weights() ran first, so this is latent; resetting them together would be safer.
  • PR body: the staged historical factors are described as "registered, frozen parameters"; the code uses non-persistent buffers (OffloadableBufferList), which the tests assert stay out of state_dict/named_parameters.

CI is green at 91a3f21 (fastcheck build 2451), and the CUDA-gated offload and Inductor tests did run in microscope-unit-tests and pass, so those paths are covered.

— fv-superagent · The first adapter would like it on the record that it was here. · run by aryan5v

@fv-superagent fv-superagent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fv-superagent score: 4/5 (was 3/5)

Both round-1 P1s are fixed; the code reads correctly now.

  • set_lora_weights decides from self._active_loras (fastvideo/layers/lora/linear.py:293), and the pipeline keeps disable_lora=False while a skipped layer still holds contributions (fastvideo/pipelines/lora_pipeline.py:739), so an earlier adapter survives a skipping accumulation. The new three-adapter tests in test_lora_adapter_switch.py cover skipped-then-covered, skipped-then-replaced, and replace-after-skip.
  • merge_lora_weights now replays through _replay_lora_contributions (linear.py:353), which restores the base layer, weight tensor and history on any failure; test_failed_merge_part_way_keeps_previous_weight_and_history covers snapshot and snapshot-free, merged and unmerged.
  • Also addressed: test_merge_lora_math.py is wired into unit_test.sh, the flagged test comments are gone, and _clear_lora_history re-points _merged_loras.

One item left, docs-only:

  • docs/inference/h3_community_lora.md:100 still says "Unmerging multiple accumulated adapters currently drops earlier contributions from inference (#2096)". That is exactly the behavior this PR fixes, so the sentence is now false. Please update or remove it — that sentence is the only reason this is still changes-requested.

Nit: the PR body still calls the staged factors "registered, frozen parameters" (they are non-persistent buffers) and still quotes the round-1 307 passed numbers.

CI: build, pre-commit and buildkite/pr-fastcheck were still running at 5e28593 when this was written; I will confirm the result separately. Greptile's re-review had not finished either.

— fv-superagent · The adapters are back together. The docs haven't heard the news. · run by aryan5v

@mergify mergify Bot added the scope: docs Documentation label Nov 20, 2026
@xxdydx

xxdydx commented Nov 20, 2026

Copy link
Copy Markdown
Author

@aryan5v hey i would like to request a review!

@fv-superagent
fv-superagent dismissed stale reviews from themself November 22, 2026 07:14

Addressed in 79c490d.

@fv-superagent fv-superagent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fv-superagent score: 5/5 (was 4/5)

79c490d removes the stale #2096 note from docs/inference/h3_community_lora.md, so every item from my earlier reviews is addressed. I have dismissed those two change requests.

  • Both state-machine P1s are fixed and covered by tests (test_lora_adapter_switch.py, test_lora_side_branch.py).
  • test_merge_lora_math.py is wired into unit_test.sh.
  • Greptile's round-2 review marked both P1s fixed; its one remaining P2 points at a comment that no longer exists — the only comment left in that file is the # Issue #2096 link, which is on its keep-list.

CI on 79c490d: build and pre-commit are green. buildkite/pr-fastcheck has been stuck scheduled since 2026-11-20 (build 2467), and recent fastcheck builds on other PRs (2457, 2460, 2465, 2468) are stalled the same way — the lane is down repo-wide, not on this change. The code is reviewed and the author's local suite passed, but the lane still has to run before this merges.

— fv-superagent · Buildkite has been "scheduled" for two days. I'm starting to think it's a lifestyle. · run by aryan5v

@aryan5v
aryan5v self-requested a review November 22, 2026 09:15

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

scope: docs Documentation scope: infra CI, tests, Docker, build scope: model Model architecture (DiTs, encoders, VAEs) type: bugfix Bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Unmerging accumulated LoRA adapters drops earlier adapters from inference

3 participants