-
Notifications
You must be signed in to change notification settings - Fork 382
Quantize lm_head + embedding for Nemotron-H, add NVFP4 W4A16 recipe #1327
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 2 commits
43c3454
490b6b2
a115c88
8fa0d4c
e63965e
78f4c42
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -107,6 +107,7 @@ def _set_kv_cache_constant_amax(quant_cfg: list) -> None: | |
| "int4_awq": mtq.INT4_AWQ_CFG, | ||
| "w4a8_awq": mtq.W4A8_AWQ_BETA_CFG, | ||
| "nvfp4": mtq.NVFP4_DEFAULT_CFG, | ||
| "nvfp4_w4a16": mtq.NVFP4_W4A16_CFG, | ||
| "nvfp4_awq": mtq.NVFP4_AWQ_LITE_CFG, | ||
| "nvfp4_mse": mtq.NVFP4_W4A4_WEIGHT_MSE_FP8_SWEEP_CFG, | ||
| "fp8_pb_wo": mtq.FP8_2D_BLOCKWISE_WEIGHT_ONLY_CFG, | ||
|
|
@@ -593,6 +594,59 @@ def sparsity_main( | |
| mts.export(full_model) | ||
|
|
||
|
|
||
| def _enable_lm_head_and_embedding_quantization( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can we define this in the modelop_recipe if everything modelopt_recipes/models can be captured with our yaml recipe system? |
||
| quant_cfg: dict[str, Any], | ||
| weight_quantizer_cfg: dict[str, Any], | ||
| ) -> None: | ||
| """Re-enable quantization of ``lm_head`` and the input embedding table. | ||
|
|
||
| ModelOpt's default PTQ recipes exclude ``*lm_head*`` and never touch ``nn.Embedding`` | ||
| because most LLM deployment runtimes keep those layers at full precision. For Nemotron-H | ||
| (and similar SSM+Attention hybrids) the embedding and lm_head are a large fraction of the | ||
| total parameters — quantizing them recovers most of the promised memory savings. This | ||
| helper appends two entries to the cfg list that override earlier ``*lm_head*`` disables | ||
| and explicitly target the embedding weight quantizer. | ||
|
|
||
| Args: | ||
| quant_cfg: the primary quant_cfg dict (``{"quant_cfg": [...], "algorithm": ...}``). | ||
| weight_quantizer_cfg: the weight-quantizer attribute dict to apply (e.g. ``_nvfp4_cfg``). | ||
| """ | ||
| # Ordering matters: these entries must come AFTER the _default_disabled_quantizer_cfg | ||
| # entries (which set *lm_head* → disabled) so they take effect. | ||
| quant_cfg["quant_cfg"].append( | ||
| {"quantizer_name": "*lm_head*weight_quantizer", "cfg": copy.deepcopy(weight_quantizer_cfg)} | ||
| ) | ||
| # nn.Embedding quantizers only exist once `quant_embedding.py` registers the class. | ||
| # Nemotron-H's backbone attribute name differs between the remote-code ("backbone.embeddings") | ||
| # and transformers built-in ("model.embeddings") paths; both are weight-only vocab | ||
| # embeddings here. The broad "*embeddings*" wildcard covers both and does not match | ||
| # any other layer in a Nemotron-H model (no positional/rotary embeddings exist). | ||
| quant_cfg["quant_cfg"].append( | ||
| { | ||
| "quantizer_name": "*embeddings*weight_quantizer", | ||
| "cfg": copy.deepcopy(weight_quantizer_cfg), | ||
| } | ||
| ) | ||
| # Also keep the standard HF "embed_tokens" naming in case future Nemotron-H variants | ||
| # rename the attribute. | ||
| quant_cfg["quant_cfg"].append( | ||
| { | ||
| "quantizer_name": "*embed_tokens*weight_quantizer", | ||
| "cfg": copy.deepcopy(weight_quantizer_cfg), | ||
| } | ||
| ) | ||
|
coderabbitai[bot] marked this conversation as resolved.
Outdated
|
||
|
|
||
|
|
||
| def _extract_weight_quantizer_cfg(quant_cfg: dict[str, Any]) -> dict[str, Any] | None: | ||
| """Return the first ``*weight_quantizer`` cfg dict from an ordered quant_cfg list.""" | ||
| for entry in quant_cfg.get("quant_cfg", []): | ||
| if entry.get("quantizer_name") == "*weight_quantizer" and isinstance( | ||
| entry.get("cfg"), dict | ||
| ): | ||
| return entry["cfg"] | ||
| return None | ||
|
|
||
|
|
||
| def mono_quantize( | ||
| args: argparse.Namespace, | ||
| quant_cfg: dict[str, Any], | ||
|
|
@@ -629,6 +683,24 @@ def mono_quantize( | |
| ) # Nemotron-Parse specific | ||
| print("Quantization will only be applied to the decoder (text generation) component") | ||
|
|
||
| # For Nemotron-H (Mamba-2 + MLP + Attention hybrid, e.g. NVIDIA-Nemotron-3-Nano-4B), | ||
| # extend quantization coverage to the lm_head and the input token embedding. On this | ||
| # architecture those two 131072x3136 tables account for ~21% of parameters, so leaving | ||
| # them at bf16 wastes most of the NVFP4 memory benefit. | ||
| if model_type == "nemotron_h": | ||
| weight_quantizer_cfg = _extract_weight_quantizer_cfg(quant_cfg) | ||
| if weight_quantizer_cfg is not None: | ||
| print( | ||
| "Nemotron-H detected: extending quantization to lm_head and input embedding " | ||
| "(backbone.embeddings)." | ||
| ) | ||
| _enable_lm_head_and_embedding_quantization(quant_cfg, weight_quantizer_cfg) | ||
|
coderabbitai[bot] marked this conversation as resolved.
Outdated
|
||
| else: | ||
| warnings.warn( | ||
| "Nemotron-H detected but quant_cfg has no wildcard '*weight_quantizer' entry; " | ||
| "skipping lm_head/embedding extension (model-specific or non-standard recipe)." | ||
| ) | ||
|
|
||
| if not model_is_already_quantized or calibration_only: | ||
| # quantize the model | ||
|
|
||
|
|
@@ -781,6 +853,12 @@ def export_quantized( | |
| extra_state_dict=mtp_state_dict, | ||
| ) | ||
|
|
||
| if args.qformat == "nvfp4_w4a16": | ||
| warnings.warn( | ||
| "TensorRT-LLM and SGLang do not support this format. " | ||
| "To serve on vLLM, convert the NVFP4 W4A16 checkpoint to compressed-tensors format." | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. hi @ajrasane , should we point the users to how they can convert? do we have a helper in ModelOpt we should point them to?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @hychiang-git, are you planning to merge your conversion script to modelopt? |
||
| ) | ||
|
|
||
| # Restore default padding and export the tokenizer as well. | ||
| if tokenizer is not None: | ||
| tokenizer.padding_side = default_padding_side | ||
|
|
@@ -1106,6 +1184,18 @@ def quantize_main( | |
| quant_cfg["quant_cfg"].append({"quantizer_name": pattern, "enable": False}) | ||
| print(f"Excluding MTP layer from quantization: {pattern}") | ||
|
|
||
| # Apply user-requested per-module exclusions (--exclude_modules). | ||
| if args.exclude_modules: | ||
| quant_cfg = copy.deepcopy(quant_cfg) | ||
| for mod in args.exclude_modules: | ||
| quant_cfg["quant_cfg"].append( | ||
| {"quantizer_name": f"*{mod}*.weight_quantizer", "enable": False} | ||
| ) | ||
| quant_cfg["quant_cfg"].append( | ||
| {"quantizer_name": f"*{mod}*.input_quantizer", "enable": False} | ||
| ) | ||
| print(f"Excluding module from quantization: {mod}") | ||
|
|
||
| # Use constant amax for KV quantizers when a cast format is selected. | ||
| if args.kv_cache_qformat in _KV_CAST_FORMATS: | ||
| quant_cfg = copy.deepcopy(quant_cfg) | ||
|
|
@@ -1304,6 +1394,17 @@ def parse_args() -> argparse.Namespace: | |
| default=False, | ||
| action="store_true", | ||
| ) | ||
| parser.add_argument( | ||
| "--exclude_modules", | ||
| nargs="+", | ||
| default=[], | ||
| metavar="MODULE", | ||
| help=( | ||
| "Module name patterns to exclude from quantization " | ||
| "(e.g. lm_head backbone.layers.0.mixer). " | ||
| "Appends a disable rule for each pattern's weight and input quantizers." | ||
| ), | ||
| ) | ||
| parser.add_argument( | ||
| "--low_memory_mode", | ||
| help=( | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
Repository: NVIDIA/Model-Optimizer
Length of output: 186
🏁 Script executed:
Repository: NVIDIA/Model-Optimizer
Length of output: 2298
🏁 Script executed:
Repository: NVIDIA/Model-Optimizer
Length of output: 84
🏁 Script executed:
Repository: NVIDIA/Model-Optimizer
Length of output: 430
🏁 Script executed:
Repository: NVIDIA/Model-Optimizer
Length of output: 1010
🏁 Script executed:
Repository: NVIDIA/Model-Optimizer
Length of output: 1060
🏁 Script executed:
Repository: NVIDIA/Model-Optimizer
Length of output: 1080
🏁 Script executed:
Repository: NVIDIA/Model-Optimizer
Length of output: 1721
🏁 Script executed:
Repository: NVIDIA/Model-Optimizer
Length of output: 465
🏁 Script executed:
Repository: NVIDIA/Model-Optimizer
Length of output: 645
🏁 Script executed:
Repository: NVIDIA/Model-Optimizer
Length of output: 816
🏁 Script executed:
Repository: NVIDIA/Model-Optimizer
Length of output: 653
🏁 Script executed:
Repository: NVIDIA/Model-Optimizer
Length of output: 689
🏁 Script executed:
Repository: NVIDIA/Model-Optimizer
Length of output: 1892
🏁 Script executed:
Repository: NVIDIA/Model-Optimizer
Length of output: 1108
🏁 Script executed:
Repository: NVIDIA/Model-Optimizer
Length of output: 2331
🏁 Script executed:
Repository: NVIDIA/Model-Optimizer
Length of output: 1472
Don't mutate the live
generation_configinget_model().The mutation persists on the returned model object, and both the before-PTQ and after-PTQ preview calls (
full_model.generate()at lines 922 and 980 in hf_ptq.py) use that same model instance. For checkpoints with sampling hyperparameters, this makes the previews non-deterministic instead of deterministic, undermining PTQ smoke test comparisons. Normalize a copy during export instead.🤖 Prompt for AI Agents