Skip to content

Fix attention quantizer leakage in diffusers HF exports - #2904

Merged
Zhehao-Hu merged 1 commit into
mainfrom
fix/nvbug-6927340-qwen-attention-export
Oct 22, 2026
Merged

Zhehao-Hu merged 1 commit into
mainfrom
fix/nvbug-6927340-qwen-attention-export

Conversation

@Zhehao-Hu

@Zhehao-Hu Zhehao-Hu commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Type of change: ? Bug fix

Exporting Qwen-Image FP8 with --quantize-mha leaves internal {q,k,v}_bmm_quantizer._amax buffers in the HF checkpoint, including buffers from disabled quantizers. TRT-LLM rejects these unexpected keys.

Hide attention quantizers during HF export by default, except for FLUX.1, which retains enabled Q/K/V quantizers for compatibility with the static FP8 attention path in NVIDIA/TensorRT-LLM#18396. An explicit option overrides this default. Disabled attention quantizers are always omitted, and quantizers are restored on the live model after saving.

Infer KV-cache metadata only for Transformers components. Diffusion components, including the native LTX-2 transformer, no longer emit KV-cache quantization metadata.

Usage

Default exports omit attention quantizer state for Qwen-Image and other diffusion components, while FLUX.1 retains enabled Q/K/V quantizers without an additional flag:

export_hf_checkpoint(pipe, export_dir="./hf_ckpt")

Explicitly retain enabled Q/K/V quantizers for a compatible runtime:

export_hf_checkpoint(
    pipe,
    export_dir="./hf_ckpt",
    export_attention_quantizers=True,
)

Set export_attention_quantizers=False to omit attention quantizers, including for FLUX.1.

Equivalent diffusers CLI option:

--extra-param export_attention_quantizers=true
# Or explicitly omit them:
--extra-param export_attention_quantizers=false

Testing

  • 93 focused export and quantization-config tests passed.
  • Regression cases run real FP8 calibration and sharded safetensors export with tiny Qwen-Image and FLUX models. They verify clean Qwen exports, FLUX’s default retention of enabled Q/K/V scales, explicit overrides, omission of disabled buffers, and restoration of live quantizers.
  • Additional coverage verifies that the native diffusion save path used by LTX-2 omits KV-cache metadata while a real Transformers model retains it. This exercises the native export interface, not a full LTX-2 model.
  • Regression tests reproduce the original buffer leak. The FLUX-default and native-diffusion metadata checks also fail against the implementation before the review fixes.
  • Pre-commit checks passed.
  • One optional ONNX example suite was skipped during earlier validation because onnx_graphsurgeon was absent.
  • Full B100/TRT-LLM generation and full LTX-2 deployment were not run; the test host has no usable GPU.

Before your PR is "Ready for review"

Make sure you read and follow Contributor guidelines and your commits are signed (git commit -s -S).

Make sure you read and follow the Security Best Practices (e.g. avoiding hardcoded trust_remote_code=True, torch.load(..., weights_only=False), pickle, etc.).

  • Is this change backward compatible?: ❌ - Consumers of legacy attention _amax
    keys must enable export_attention_quantizers=True.
  • If you copied code from any other sources or added a new PIP dependency, did you follow guidance in CONTRIBUTING.md: N/A
  • Did you write any new necessary tests?: ✅
  • Did you update Changelog?: ✅
  • Did you get Claude approval on this PR?: N/A - Not yet run

Additional Information

Fixes NVBug 6927340.

Summary by CodeRabbit

  • Breaking Changes

    • Hugging Face diffusion exports omit attention quantizer data by default.
    • FLUX.1 exports retain enabled Q/K/V quantizer values for runtime compatibility.
    • KV-cache metadata is excluded from native diffusion exports.
  • New Features

    • Added the export_attention_quantizers option to retain or omit attention quantizers.
    • Disabled quantizers remain excluded regardless of this option.
    • Transformers exports continue to include KV-cache metadata.
  • Documentation

    • Added guidance on attention quantizer and KV-cache export behavior.

@copy-pr-bot

copy-pr-bot Bot commented Oct 20, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@coderabbitai

coderabbitai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: NVIDIA/Model-Optimizer/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Enterprise
  • Run ID: c6f30c2d-fef7-4762-880c-3da069b9289c
📥 Commits

Reviewing files that changed from the base of the PR and between d97efd9 and 819bb98.

📒 Files selected for processing: 3
  • CHANGELOG.rst
  • modelopt/torch/export/unified_export_hf.py
  • tests/unit/torch/export/test_export_diffusers.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 10 remain after this review.

📝 Walkthrough

Diffusion Hugging Face exports now omit attention quantizer state by default, except for FLUX.1. The export_attention_quantizers option controls retention. KV-cache metadata is generated for Transformers components, not native diffusion components.

Changes: Diffusers Hugging Face export quantizer handling

Layer / File(s) Summary
Component-specific KV-cache metadata
modelopt/torch/export/quant_utils.py, modelopt/torch/export/unified_export_hf.py, tests/unit/torch/export/test_export_diffusers.py
get_quant_config gains the include_kv_cache option. The export path collects KV-cache metadata for recognized Transformers components and omits it for native diffusion components. Tests cover both component types.
Attention quantizer retention and export
examples/diffusers/quantization/quantize.py, modelopt/torch/export/unified_export_hf.py, modelopt/torch/export/diffusers_utils.py, tests/unit/torch/export/test_export_diffusers.py, examples/diffusers/README.md, CHANGELOG.rst
export_attention_quantizers is forwarded to the export path. Enabled Q/K/V BMM quantizers are retained when requested; the default retains them for FLUX.1. Tests check default and explicit settings, exported tensors, and disabled quantizers. The README and changelog describe the behavior.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant ExtraParams as model_config.extra_params
  participant export_hf_ckpt
  participant export_hf_checkpoint
  participant hide_quantizers_from_state_dict
  participant Checkpoint
  ExtraParams->>export_hf_ckpt: provide export_attention_quantizers
  export_hf_ckpt->>export_hf_checkpoint: forward the validated option
  export_hf_checkpoint->>hide_quantizers_from_state_dict: apply the retention setting
  hide_quantizers_from_state_dict-->>export_hf_checkpoint: provide the temporary state-dict view
  export_hf_checkpoint->>Checkpoint: write the Hugging Face checkpoint
Loading

Suggested reviewers: kevalmorabia97

Merge Risk: ⚪ Minimal · up to 819bb

The documented Transformers exception preserves the calibration tensors required by its KV-cache configuration. No identified issue blocks merging after normal checks.

Pre-merge checks: Passed 5 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 53.85% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 13 functions across 5 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 5 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: preventing attention quantizer leakage in Diffusers Hugging Face exports.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Security Anti-Patterns Passed PASS. The pull request changes only export logic and CLI option handling in the reviewed Python files. Added lines contain no torch.load(..., weights_only=False), `numpy.load(..., allow_pickle=True)…
Full details: Security Anti-Patterns

Explanation

PASS. The pull request changes only export logic and CLI option handling in the reviewed Python files. Added lines contain no torch.load(..., weights_only=False), numpy.load(..., allow_pickle=True), hardcoded trust_remote_code=True, external-input eval()/exec(), or # nosec. No pyproject.toml or requirements.txt dependency files changed.

Full details: Docstring Coverage

Explanation

Docstring coverage is 53.85% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 13 functions across 5 files. (1 skipped: 1 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@cjluo-nv cjluo-nv 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.

Bot review (bedrock-claude-opus-5-5) — DM the bot to share feedback.

The fix is small, correct and well tested, but it changes the default export in a backward-breaking way, so an owner should confirm the new default before merge.

Needs action:

  • Confirm with the TRT-LLM diffusion owners that the static FP8 FLUX path (TensorRT-LLM#18396) is fine requiring export_attention_quantizers=True. Otherwise, keep the old default for FLUX and hide the quantizers only where they break loading (Qwen-Image).
  • Confirm it's intended that non-diffusers components (the LTX-2 transformer) still infer KV-cache metadata. include_kv_cache=not is_diffusers_object(component) in unified_export_hf.py leaves that path unchanged.

No action needed:

  • Design: this extends the existing hide_quantizers_from_state_dict and get_quant_config with one flag each, with no new subsystem. Making it opt-in through **kwargs and the existing --extra-param keys fits the current conventions.
  • The flag reaches _export_diffusers_checkpoint as a named parameter, so it doesn't leak into _postprocess_safetensors kwargs.
  • The new parametrized test runs real FP8 calibration on tiny Qwen-Image and FLUX models with sharded export. It covers:
    • clean default exports;
    • only enabled Q/K/V scales kept when opted in;
    • no KV-cache metadata;
    • quantizers restored on the live model.
  • No existing tests were modified. I read the tests but didn't run them.

@github-actions

github-actions Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1
Preview removed because the pull request was closed.
2026-10-22 03:24 UTC

@codecov

codecov Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 78.94%. Comparing base (d055c23) to head (819bb98).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2904      +/-   ##
==========================================
+ Coverage   70.16%   78.94%   +8.77%     
==========================================
  Files         659      659              
  Lines       74081    74088       +7     
==========================================
+ Hits        51978    58486    +6508     
+ Misses      22103    15602    -6501     
Flag Coverage Δ
examples-diffusers 20.05% <84.61%> (+<0.01%) ⬆️
examples-gpt-oss 13.52% <30.76%> (+<0.01%) ⬆️
examples-hf_ptq 23.19% <38.46%> (-0.04%) ⬇️
examples-llm_distill 13.59% <30.76%> (-0.01%) ⬇️
examples-llm_eval 17.24% <38.46%> (+<0.01%) ⬆️
examples-llm_qat 17.48% <38.46%> (-0.01%) ⬇️
examples-llm_sparsity 16.84% <38.46%> (+1.07%) ⬆️
examples-megatron_bridge 26.43% <30.76%> (-0.13%) ⬇️
examples-specdec_bench 13.30% <30.76%> (+<0.01%) ⬆️
examples-speculative_decoding 17.47% <38.46%> (-0.01%) ⬇️
examples-torch_onnx 21.38% <30.76%> (-0.03%) ⬇️
examples-torch_trt 15.24% <30.76%> (-0.01%) ⬇️
examples-vllm_serve 15.09% <30.76%> (-0.01%) ⬇️
gpu 59.13% <84.61%> (+37.00%) ⬆️
regression 15.10% <30.76%> (-0.01%) ⬇️
unit 60.71% <100.00%> (+0.12%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Zhehao-Hu
Zhehao-Hu force-pushed the fix/nvbug-6927340-qwen-attention-export branch from eb84515 to d97efd9 Compare October 20, 2026 23:59

@cjluo-nv cjluo-nv 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.

Bot review (bedrock-claude-opus-5-5) — DM the bot to share feedback.

Approving: both concerns from my last review are fixed in this diff, and each fix has a test that would fail without it.

No action needed.

No action needed:

  • ✔️ Resolved since the last review:
    • FLUX.1 keeps its legacy default. When export_attention_quantizers is unset, isinstance(component, diffusers.FluxTransformer2DModel) keeps enabled Q/K/V _amax keys, so the static FP8 path in TRT-LLM#18396 is unchanged.
    • Native components like LTX-2 no longer emit KV-cache metadata. include_kv_cache is now set only for PreTrainedModel instances, so text encoders still get it.
  • Design: the PR adds a flag to the existing hide_quantizers_from_state_dict and get_quant_config. It adds no new subsystem; the gate fired only because the change touches 5 directories.
  • softmax_quantizer and bmm2_output_quantizer are now always hidden, even when the flag is True. That's right, since the opt-in only promises to keep Q/K/V.
  • The only callers of hide_quantizers_from_state_dict are the diffusers export path and its tests, so the new default doesn't affect other callers.
  • The diffusers.FluxTransformer2DModel reference is safe: you can only reach that code when HAS_DIFFUSERS is set.
  • No existing tests were changed. The new tests cover Qwen with the default, and FLUX with the default plus explicit True and False. They also check KV metadata for a native component and for a Transformers component. I read the tests but didn't run them.

Complex PR: spans 5 directories (≥ 5); 1 existing test file modified or removed. Looping in a human for approval.

@Zhehao-Hu
Zhehao-Hu marked this pull request as ready for review October 21, 2026 00:05
@Zhehao-Hu
Zhehao-Hu requested review from a team as code owners October 21, 2026 00:05
# - for non-diffusers modules (e.g., LTX-2 transformer), fall back to torch.save
if hasattr(component, "save_pretrained"):
with hide_quantizers_from_state_dict(component):
with hide_quantizers_from_state_dict(component, keep_attention_quantizers):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Preserve KV-cache scales for Transformers components

When a Transformers component has calibrated K/V quantizers, include_kv_cache=True above retains its static kv_cache_scheme, but keep_attention_quantizers defaults to false because the component is not a FluxTransformer2DModel. This context then removes both K/V quantizers before saving. This export path does not run postprocess_state_dict, so no replacement k_scale/v_scale tensors are written either.

I reproduced this with the tiny Llama setup from test_export_diffusion_component_kv_metadata[True]: using the previous hiding implementation preserves layers.0.self_attn.{k,v}_bmm_quantizer._amax; the new implementation exports no K/V calibration tensors while keeping {"dynamic": false, "num_bits": 8, "type": "float"} in kv_cache_scheme. The checkpoint therefore loses the calibration required by its declared static KV-cache configuration.

Please preserve or convert those scales for Transformers components independently of the diffusion-attention option, and extend the existing test to check the saved tensors as well as the metadata.

@Edwardf0t1 Edwardf0t1 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM, left 1 comment by the agent

Hide attention quantizer buffers by default and avoid treating diffusion
attention quantization as KV-cache quantization.

Add export_attention_quantizers=True to preserve enabled Q/K/V quantizers
for runtimes consuming legacy _amax keys. Disabled quantizers remain
excluded.

Add Qwen-Image and FLUX regression coverage for sharded exports.

Signed-off-by: Zhehao Hu <zhehaoh@nvidia.com>
@Zhehao-Hu
Zhehao-Hu force-pushed the fix/nvbug-6927340-qwen-attention-export branch from d97efd9 to 819bb98 Compare October 21, 2026 21:49
@Zhehao-Hu
Zhehao-Hu merged commit 9714044 into main Oct 22, 2026
72 of 83 checks passed
@Zhehao-Hu
Zhehao-Hu deleted the fix/nvbug-6927340-qwen-attention-export branch October 22, 2026 03:24
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.

3 participants