mirror of
https://github.com/NVIDIA/Model-Optimizer.git
synced 2026-12-06 04:57:17 +08:00
Keep #3662's export_mcore_gpt_to_hf DeprecationWarning, docstring migration guidance and CHANGELOG Deprecations entry alongside this PR's refusal and its CHANGELOG line. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Keval Morabia <28916987+kevalmorabia97@users.noreply.github.com>
This commit is contained in:
+11
-1
@@ -40,9 +40,11 @@ Changelog
|
||||
|
||||
*Speculative Decoding*
|
||||
|
||||
- Offline training of the plain DFlash draft now supports context parallelism (``training.cp_size > 1``); other DFlash-family setups with ``cp_size > 1`` now raise an error.
|
||||
|
||||
*Megatron Framework (M-LM / M-Bridge)*
|
||||
|
||||
- ``examples/megatron_bridge/export_quantized_megatron_to_hf.py`` now exports through Megatron-Bridge (``AutoBridge.save_hf_pretrained_modelopt``) at any tensor, expert or pipeline parallelism when the installed Megatron-Bridge provides it and can export every enabled quantizer, writing the quantization config inline in ``config.json`` only (no ``hf_quant_config.json``). Otherwise, e.g. for KV-cache quantizers before Megatron-Bridge #7057, GGML / IQ formats, ``--export_extra_modules`` or a VLM's language-model-only QAD checkpoint, ModelOpt's Megatron exporter writes it at ``--tp_size 1`` (GGML / IQ also at ``--pp_size 1``); ``--modelopt_megatron_exporter`` selects it explicitly.
|
||||
- ``examples/megatron_bridge/export_quantized_megatron_to_hf.py`` now exports through Megatron-Bridge (``AutoBridge.save_hf_pretrained_modelopt``) at any tensor, expert or pipeline parallelism when the installed Megatron-Bridge provides it and can export every enabled quantizer, writing the quantization config inline in ``config.json`` only (no ``hf_quant_config.json``). Otherwise, e.g. for KV-cache quantizers before Megatron-Bridge #7057, GGML / IQ formats, ``--export_extra_modules`` or a model whose bridge post-processes exported weights (e.g. Nemotron 3.5 Super VL), ModelOpt's Megatron exporter writes it at ``--tp_size 1`` (GGML / IQ also at ``--pp_size 1``); ``--modelopt_megatron_exporter`` selects it explicitly. A VLM's language-model-only QAD checkpoint is loaded over the source's Hugging Face weights, so Megatron-Bridge's export carries the source's vision tower.
|
||||
|
||||
*Misc*
|
||||
|
||||
@@ -53,8 +55,12 @@ Changelog
|
||||
|
||||
**Backward Breaking Changes**
|
||||
|
||||
- A distributed ``mtq.auto_quantize`` weight search now resumes only when every rank holds its own file from the same run, world size, distribution plan, parallel groups and DTensor weight placements. Pipeline-parallel searches, tensor- or expert-parallel runs given a file written before this release, and one process given a file that several ranks wrote with this release no longer resume: start over with a new checkpoint path, or re-solve the saved scores with ``mtq.get_auto_quantize_config(search_state, constraints)``.
|
||||
|
||||
**Deprecations**
|
||||
|
||||
- ``modelopt.torch.export.export_mcore_gpt_to_hf`` is deprecated and planned for removal in 0.51.0; it now emits a ``DeprecationWarning``. Where it supports the checkpoint, export with Megatron-Bridge's ``AutoBridge.save_hf_pretrained_modelopt`` instead, as ``examples/megatron_bridge/export_quantized_megatron_to_hf.py`` does (set up as in `examples/megatron_bridge/README.md <https://github.com/NVIDIA/Model-Optimizer/tree/main/examples/megatron_bridge#pre-requisites>`_); the function's docstring lists what Megatron-Bridge doesn't export yet.
|
||||
|
||||
**Bug Fixes**
|
||||
|
||||
*Quantization*
|
||||
@@ -67,6 +73,7 @@ Changelog
|
||||
- For dense Qwen3.5 checkpoints with an LM-head size mismatch in TensorRT-LLM 1.3.0, use ``model_type/qwen3_5/auto_quantize/w4a8_awq_beta_fp8_at_6p0bits-decoder_only`` to keep the output head unquantized and outside the 6-bit decoder budget. Rerun from the original weights and omit ``--auto_quantize_checkpoint`` or give it a fresh path.
|
||||
- Fix Hugging Face exports of a model downloaded with ``huggingface_hub`` 1.32 or later into the configured Hugging Face cache (``HF_HUB_CACHE``) missing ``tokenizer.json`` and other files the Hub stores with Git LFS (e.g. ``tokenizer.model``), and the Kimi-K3 and DeepSeek-V4 NVFP4 converters failing on such a model. Copy the missing files from the source checkpoint into affected exports (or re-export them) and rerun failed conversions.
|
||||
- Calibration of a model spread over several GPUs no longer fails with an illegal memory access under ``PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True``: clearing the CUDA cache now waits for every GPU's queued work first.
|
||||
- AutoQuantize now counts the ``up_proj`` of non-gated fused MoE experts in its cost, which counted only half of each such expert and so exceeded ``effective_bits``. A search resumed from an older checkpoint solves with recomputed costs; re-solving such a checkpoint without the model with ``get_auto_quantize_config`` warns that its costs may be stale.
|
||||
|
||||
*ONNX*
|
||||
|
||||
@@ -81,7 +88,10 @@ Changelog
|
||||
*Megatron Framework (M-LM / M-Bridge)*
|
||||
|
||||
- Preserve model-specific hybrid stacks when selecting MoE expert layouts in Megatron-Bridge, and reject grouped GEMM when a custom factory returns sequential experts. Custom built stack ``ModuleSpec`` values are now rejected; assign a named factory function instead.
|
||||
- Fix restoring a Megatron checkpoint of non-gated grouped MoE experts (e.g. squared ReLU) with per-channel weight quantizers (e.g. ``INT8_DEFAULT_CFG``, ``FP8_PER_CHANNEL_PER_TOKEN_CFG``) at another tensor-parallel size, which failed with a CUDA device-side assert or a checkpoint shape mismatch. Gated (SwiGLU) experts' per-channel state must still load at the expert tensor-parallel size it was saved at: ``restore_sharded_modelopt_state`` into an unquantized model now raises at another size, but a load into an already quantized model does not check it.
|
||||
- Fix a sparse gated (SwiGLU) MLP's ``linear_fc1`` weight mask loading on the wrong rows when a Megatron checkpoint is restored at another tensor-parallel size. Checkpoints saved by earlier versions (and re-saves of them) keep the old layout and load only through ``restore_sharded_modelopt_state`` into a model that isn't sparsified yet, at their saved tensor-parallel size (at another size their masks load on the wrong rows, with no error); any other load fails with a missing key, so load such a checkpoint without ModelOpt state (weights only) with an earlier version.
|
||||
- ``export_mcore_gpt_to_hf`` and Megatron-Bridge's quantized export now refuse AWQ (including weight-only ``INT4_AWQ_CFG``) and SmoothQuant models instead of writing weights still scaled by the AWQ / SmoothQuant ``pre_quant_scale``. Quantize and export such models from Hugging Face with ``examples/hf_ptq/hf_ptq.py``, and re-export affected checkpoints.
|
||||
- Fix calibration with context parallelism failing on newer Megatron-Core with ``get_batch_on_this_cp_rank() missing 1 required positional argument: 'dynamic_cp'``.
|
||||
- ``export_mcore_gpt_to_hf`` now refuses quantization formats it writes no valid quantization config for (e.g. INT4, MXFP8, MXFP4) instead of exporting weights the checkpoint does not describe, and refuses an export whose config-writing rank (the last pipeline stage's first rank) holds no quantized layer while other ranks do. Quantize and export the Hugging Face model instead, or use Megatron-Bridge's ``AutoBridge.save_hf_pretrained_modelopt`` for the formats it supports.
|
||||
|
||||
*Misc*
|
||||
|
||||
+2046
File diff suppressed because it is too large
Load Diff
|
After Width: | Height: | Size: 59 KiB |
+2886
File diff suppressed because it is too large
Load Diff
|
After Width: | Height: | Size: 87 KiB |
+2237
File diff suppressed because it is too large
Load Diff
|
After Width: | Height: | Size: 65 KiB |
+302
@@ -0,0 +1,302 @@
|
||||
:orphan:
|
||||
|
||||
Evaluating Models Efficiently During Optimization Experiments
|
||||
#############################################################
|
||||
|
||||
:Author: `Daniel Korzekwa <https://github.com/danielkorzekwa>`__,
|
||||
`Rohan Joshi <https://github.com/rohansjoshi>`__,
|
||||
`Chad Voegele <https://github.com/chadvoegele>`__,
|
||||
`Chenjie Luo <https://github.com/cjluo-nv>`__
|
||||
:Date: November 18, 2026
|
||||
:Tags: evaluation, docs, quantization, qad, fast-experimentation
|
||||
|
||||
Introduction
|
||||
------------
|
||||
|
||||
When you optimize a reasoning model with NVIDIA Model Optimizer, how do you verify improvements
|
||||
without overlooking regressions? Average accuracy can hide doomed reasoning loops (repetitive
|
||||
reasoning that continues until the output-token limit is reached), missing answers, inappropriate
|
||||
guessing, or excessive output length.
|
||||
|
||||
Because model generation is stochastic, we repeat evaluations to measure how scores vary between runs.
|
||||
You may assume that reliable evaluation requires many repetitions. But could repeating by default
|
||||
waste time? How many questions and repetitions do you need to measure improvements and rule out
|
||||
regressions?
|
||||
|
||||
This article helps you evaluate models quickly and reliably during optimization experiments.
|
||||
We use SciCode to compare two NVFP4 Qwen3.6-35B-A3B checkpoints and test whether
|
||||
Kahneman–Tversky Optimization (KTO) reduces reasoning loops while preserving accuracy.
|
||||
See how we apply these guidelines in practice across a broader set of benchmarks in the
|
||||
`KTO tutorial
|
||||
<https://github.com/NVIDIA/Model-Optimizer/blob/main/examples/megatron_bridge/tutorials/Qwen3.6-35B-A3B/kto/README.md>`__.
|
||||
|
||||
For standardized evaluation and acceptance checks before releasing optimized models, follow the
|
||||
`ModelOpt evaluation
|
||||
skill <https://github.com/NVIDIA/Model-Optimizer/blob/main/skills/modelopt-evaluation/SKILL.md>`__
|
||||
and `ModelOpt results-comparison
|
||||
skill <https://github.com/NVIDIA/Model-Optimizer/blob/main/skills/modelopt-compare-results/SKILL.md>`__.
|
||||
For benchmark commands, see the `LLM evaluation
|
||||
examples <https://github.com/NVIDIA/Model-Optimizer/blob/main/examples/llm_eval/README.md>`__.
|
||||
|
||||
**What should you measure, and how?**
|
||||
|
||||
- **Show where the model improves or worsens:** use paired statistical tests to distinguish model
|
||||
differences from evaluation noise.
|
||||
- **Check for regressions:** use confidence intervals and non-inferiority tests to rule out
|
||||
unacceptable regression, even if the baseline does not have a higher average score.
|
||||
- **Assess model reliability:** measure doomed reasoning loops, missing answers, and whether the
|
||||
model abstains appropriately.
|
||||
- **Measure verbosity:** compare output length, including reasoning tokens.
|
||||
|
||||
**How can you evaluate faster?**
|
||||
|
||||
- **Choose between question-level and repetition-level analysis:** match the approach to your goal
|
||||
and evaluation budget.
|
||||
- **Collect as much evaluation data as you need:** use pilot results to choose enough questions or
|
||||
repetitions to assess regression.
|
||||
- **Test known weaknesses on a focused subset:** failure-prone questions can reveal targeted
|
||||
improvements with fewer responses; check broader performance separately.
|
||||
|
||||
What should you measure, and how?
|
||||
---------------------------------
|
||||
|
||||
Choose a primary improvement metric before inspecting results. Prefer Candidate
|
||||
if it improves that metric and meets your non-inferiority criteria for the others. Regressions
|
||||
highlight areas to improve.
|
||||
|
||||
Show where the model improves or worsens
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Our primary question is whether Candidate is better than Baseline. We use paired question-level
|
||||
tests here to compare models across the domain represented by the benchmark. Pairing can reduce
|
||||
variation caused by question difficulty. For standardized reporting on a fixed benchmark, ModelOpt
|
||||
uses unpaired Welch t-tests on independent, complete-run scores to estimate uncertainty from
|
||||
variation between runs of those exact questions.
|
||||
|
||||
We use a paired 95% bootstrap confidence interval to show the uncertainty in the mean accuracy
|
||||
difference and a one-sided paired permutation test to assess evidence of improvement. A one-sided
|
||||
paired test can detect improvement with less data than a two-sided test for any difference.
|
||||
The bootstrap and permutation test account for correlations among subtasks from the same SciCode
|
||||
parent problem and assume independence across parent problems. See the
|
||||
:ref:`SciCode accuracy calculation <evaluation-statistical-methods>` in the Reproducibility Notes.
|
||||
|
||||
The SciCode table reports the Candidate − Baseline accuracy difference in percentage points (pp)
|
||||
and shows reverse-direction p-values for context. We use p < 0.05 for each test. “No evidence”
|
||||
means higher Candidate accuracy was not established at that threshold.
|
||||
|
||||
+----------------+----------+-----------+------------------+------------------+------------------+
|
||||
| Benchmark | Baseline | Candidate | Difference [95% | Candidate | Baseline higher, |
|
||||
| | | | CI], pp | higher, p-value | p-value |
|
||||
| | | | | | (context) |
|
||||
+================+==========+===========+==================+==================+==================+
|
||||
| SciCode | 42.81% | 44.39% | +1.57 [−0.48, | 0.080 — no | 0.931 |
|
||||
| | | | +3.67] | evidence | |
|
||||
+----------------+----------+-----------+------------------+------------------+------------------+
|
||||
|
||||
Check for regressions
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
One-sided tests for improvement do not tell us about possible regression.
|
||||
Choose an acceptable accuracy-loss margin for your use case before inspecting results, then
|
||||
use a non-inferiority test to assess whether the loss is smaller. See the
|
||||
:ref:`non-inferiority calculation <evaluation-statistical-methods>` in the Reproducibility Notes.
|
||||
|
||||
The table illustrates two possible margins on SciCode.
|
||||
“Yes” means the stated accuracy loss is ruled out (p < 0.05).
|
||||
|
||||
============================ ===================
|
||||
Rule out an accuracy loss of SciCode p-value
|
||||
============================ ===================
|
||||
1.0 pp 0.009 — yes
|
||||
0.5 pp 0.028 — yes
|
||||
============================ ===================
|
||||
|
||||
Assess model reliability
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Average accuracy alone does not show whether a model behaves reliably: also measure doomed reasoning
|
||||
loops, missing answers, and whether it abstains when appropriate.
|
||||
|
||||
+------------------------+----------------------------------------------------------------------------+
|
||||
| Measure | Recommendation |
|
||||
+========================+============================================================================+
|
||||
| Doomed reasoning loops | Use cap-hit rates to screen for potential loops, then inspect the text to |
|
||||
| | confirm repetition. A cap hit reaches the configured response-token limit |
|
||||
| | (131,072 here). |
|
||||
+------------------------+----------------------------------------------------------------------------+
|
||||
| Missing final answers | Report how often responses contain no final answer. |
|
||||
+------------------------+----------------------------------------------------------------------------+
|
||||
| Abstention ratio | Count an abstention when the final response is non-empty and the judge |
|
||||
| | grades it ``NOT_ATTEMPTED`` using AA-Omniscience’s rubric. |
|
||||
| | Report abstentions / (all responses − correct responses) alongside |
|
||||
| | accuracy. The denominator includes abstentions, incorrect and partial |
|
||||
| | answers, and missing answers. |
|
||||
| | `AA-Omniscience <https://artificialanalysis.ai/evaluations/omniscience>`__ |
|
||||
| | is an example benchmark. |
|
||||
+------------------------+----------------------------------------------------------------------------+
|
||||
|
||||
The doomed reasoning loops example below shows how to report rare failures using cap-hit rates.
|
||||
Rare failures can make t-based approximations unreliable, so we use paired-bootstrap 95% confidence
|
||||
intervals and one-sided paired permutation tests for the rates below. As in the accuracy
|
||||
analysis, both methods account for correlations among subtasks from the same SciCode parent
|
||||
problem.
|
||||
The confidence intervals and p-values come from different procedures and need not lead to the
|
||||
same conclusion. See the :ref:`cap-hit rate calculation <evaluation-statistical-methods>` in the
|
||||
Reproducibility Notes.
|
||||
|
||||
The candidate has fewer cap hits on SciCode (p < 0.001).
|
||||
“Yes” means evidence of a lower Candidate cap-hit rate (p < 0.05).
|
||||
|
||||
+----------------+---------------+---------------+---------------+---------------+---------------+
|
||||
| Benchmark | Baseline cap | Candidate cap | Difference | Candidate | Candidate |
|
||||
| | rate | rate | [95% CI], pp | lower, | higher, |
|
||||
| | | | | p-value | p-value |
|
||||
| | | | | | (context) |
|
||||
+================+===============+===============+===============+===============+===============+
|
||||
| SciCode | 1.53% | 0.00% | −1.53 [−2.03, | <0.001 — yes | 1.000 |
|
||||
| | (36/2,352) | (0/2,352) | −1.04] | | |
|
||||
+----------------+---------------+---------------+---------------+---------------+---------------+
|
||||
|
||||
.. tip::
|
||||
|
||||
For exploratory evaluations on vLLM, enable its repetition detector to stop looping
|
||||
responses early and save GPU time. Use the same settings for both checkpoints. Save the
|
||||
stop reason so you can inspect the stopped responses and compare how often the detector
|
||||
triggers for each checkpoint. To measure how often responses would reach the token cap
|
||||
without early stopping, run with the detector off. See the
|
||||
`ModelOpt instructions for stopping repeated reasoning
|
||||
<https://github.com/NVIDIA/Model-Optimizer/blob/main/skills/modelopt-evaluation/references/doom_loops.md>`__.
|
||||
|
||||
Measure verbosity
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
||||
Compare mean and median completion tokens, including reasoning, to assess how much generation each
|
||||
answer requires. A paired 95% confidence interval shows how precisely we estimate the difference in mean
|
||||
completion length. The one-sided p-value helps assess whether Candidate produces shorter
|
||||
completions on average. The table marks p < 0.05 as “yes.” See the
|
||||
:ref:`verbosity calculation <evaluation-statistical-methods>` in the Reproducibility Notes.
|
||||
|
||||
+----------------+-------------+-------------+-------------+-------------+-------------+-------------+
|
||||
| Benchmark | Baseline: | Candidate: | Change: | Mean change | Candidate | Candidate |
|
||||
| | mean / | mean / | mean / | [95% CI], | shorter, | longer, |
|
||||
| | median | median | median, % | tokens | p-value | p-value |
|
||||
| | | | | | | (context) |
|
||||
+================+=============+=============+=============+=============+=============+=============+
|
||||
| SciCode | 6,512 / | 3,063 / | −53.0% / | −3,450 | <0.001 — | 1.000 |
|
||||
| | 2,993 | 1,803 | −39.8% | [−4,236, | yes | |
|
||||
| | | | | −2,664] | | |
|
||||
+----------------+-------------+-------------+-------------+-------------+-------------+-------------+
|
||||
|
||||
How can you evaluate faster?
|
||||
----------------------------
|
||||
|
||||
.. _evaluation-prioritize-question-coverage:
|
||||
.. _evaluation-choose-questions-and-repetitions:
|
||||
|
||||
Choose between question-level and repetition-level analysis
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Both approaches are valid. Choose based on your goal and the balance between precision and
|
||||
evaluation speed:
|
||||
|
||||
- **Repetition-level: estimate accuracy on a fixed benchmark.** Treat its question set as a black box:
|
||||
compute one average score per complete run, then estimate uncertainty across independent runs.
|
||||
Multiple complete passes can be expensive. If scores vary widely across runs, you need more
|
||||
repetitions to reach the same precision.
|
||||
- **Question-level: get accurate results quickly for the domain represented by a benchmark.**
|
||||
Use representative questions: compute an average score per question across repetitions, then
|
||||
estimate uncertainty across questions. With sufficiently independent questions, this approach can support faster experimentation.
|
||||
|
||||
In both approaches, we produce the same aggregate mean score by averaging across all questions
|
||||
and repetitions. Using question-level versus repetition-level analysis only changes how we
|
||||
calculate confidence intervals and p-values. What you can compare later depends on the results
|
||||
you use:
|
||||
|
||||
- **Within an experiment**, use paired analysis when both checkpoints answer the same questions.
|
||||
- **Across experiments**, report an aggregate score per checkpoint. Keep per-question results for
|
||||
paired analysis when you can match the question IDs.
|
||||
|
||||
Is question-level analysis reliable on real benchmarks compared with repetition-level analysis?
|
||||
We compare the two approaches by spending the same response budget on more questions or
|
||||
more repetitions per question, then measuring how much the resulting scores vary.
|
||||
For SciCode, we sample with replacement from the 294 eligible subtasks and select distinct runs
|
||||
from the eight saved runs. Each simulated evaluation uses 280 saved scores per model, from
|
||||
280 subtask draws with one repetition to 35 subtask draws with eight repetitions. Candidate
|
||||
accuracy had a lower standard deviation (SD) when we drew more subtasks with fewer repetitions.
|
||||
The choice of analysis level may depend on the benchmark and metric. See the
|
||||
:ref:`fixed-budget analysis <evaluation-fixed-response-budgets>` in the Reproducibility Notes.
|
||||
|
||||
.. figure:: images/budget-allocation-scicode-accuracy.svg
|
||||
:alt: Mean Candidate accuracy on SciCode with shading showing one standard deviation above and below the mean across random draws. At 280 sampled scores per model, the spread is smaller with more subtask draws and fewer repetitions.
|
||||
:width: 640px
|
||||
|
||||
.. _evaluation-collect-data:
|
||||
|
||||
Collect as much evaluation data as you need
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
You may not need the full evaluation budget to detect an improvement or rule out an unacceptable
|
||||
regression. The data needed depends on the model pair, metric, acceptable regression margin, and
|
||||
statistical target.
|
||||
|
||||
**How many responses show fewer cap hits on SciCode?**
|
||||
|
||||
After completing all eight repetitions, we analyzed subsets of the saved responses. We first
|
||||
increased coverage from 10 to 294 subtasks with one repetition, then added repetitions on all
|
||||
294 subtasks. In this retrospective comparison, the p-value first fell below 0.05 at 250
|
||||
responses per model and below 0.001 at 882.
|
||||
See the :ref:`cap-hit p-value calculation <evaluation-scicode-cap-hit-p-values>` in the Reproducibility Notes.
|
||||
|
||||
A large drop in cap-hit rate from Baseline to Candidate may be detectable with only a few
|
||||
repetitions. Use a small pilot to estimate the size of the difference for your checkpoints
|
||||
and plan how many subtasks and repetitions to run.
|
||||
|
||||
In a staged evaluation, analyze all responses collected so far at each stage, including the
|
||||
pilot. During experimentation, stopping at the first p < 0.05 can speed up decisions at the
|
||||
cost of a higher risk of a false positive. For final evaluation results, set the response count
|
||||
after the staged preliminary evaluation and before the final run. Use only responses from that
|
||||
run for the final test.
|
||||
|
||||
.. image:: images/scicode-cap-data-volume.svg
|
||||
:alt: SciCode cap-hit rate evidence excluding the 44 recovery-training subtasks: blue points increase coverage from ten to 294 subtasks with one repetition; green points add repetitions on all 294 subtasks, reaching 2,352 responses per model. The ten-subtask subset has no observed cap hits and no informative bootstrap interval. The lower panel shows permutation p-values.
|
||||
:width: 640px
|
||||
|
||||
Test known weaknesses on a focused subset
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Freeze a subset from earlier baseline failures to screen for targeted improvements. Use multiple
|
||||
Baseline runs to see which questions show the target failure most often. Use a histogram to
|
||||
choose a cutoff for the subset, then compare both models on fresh runs.
|
||||
|
||||
On SciCode, we selected all 55 subtasks where Baseline hit the completion cap at least once
|
||||
across eight earlier runs, used 44 for training, and held out 11 for validation.
|
||||
|
||||
.. figure:: images/scicode-cap-hit-histogram.svg
|
||||
:alt: Across eight SciCode baseline runs, 283 subtasks had no cap hits, 30 had one, 15 had two, five had three, four had four, and one had five.
|
||||
:width: 640px
|
||||
|
||||
The focused evaluation used those 11 subtasks × 8 repetitions (88 responses per
|
||||
model), compared with 294 subtasks × 8 repetitions (2,352 responses per model) in the broader
|
||||
evaluation. As intended, Baseline’s cap-hit rate was higher on the focused subset
|
||||
(10.23%, compared with 1.53% in the broader evaluation).
|
||||
Use it for a quick check of known weaknesses, then evaluate broader accuracy and reliability
|
||||
separately.
|
||||
|
||||
“Yes” means evidence of a lower Candidate cap-hit rate (p < 0.05).
|
||||
|
||||
+----------------+---------------+---------------+---------------+---------------+---------------+
|
||||
| Benchmark | Baseline cap | Candidate cap | Difference | Candidate | Candidate |
|
||||
| | rate | rate | [95% CI], pp | lower, | higher, |
|
||||
| | | | | p-value | p-value |
|
||||
| | | | | | (context) |
|
||||
+================+===============+===============+===============+===============+===============+
|
||||
| Focused subset | 10.23% | 0.00% (0/88) | −10.23 | 0.004 — yes | 1.000 |
|
||||
| | (9/88) | | [−14.77, | | |
|
||||
| | | | −5.68] | | |
|
||||
+----------------+---------------+---------------+---------------+---------------+---------------+
|
||||
|
||||
.. toctree::
|
||||
:hidden:
|
||||
:maxdepth: 1
|
||||
|
||||
Reproducibility notes <reproducibility/index>
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
repetitions,subtask_draws,responses_per_model,draws,mean_accuracy_percent,accuracy_sd_pp
|
||||
1,280,280,50000,44.37022142857143,3.4779158888869754
|
||||
2,140,280,50000,44.377921428571426,4.087446916276032
|
||||
4,70,280,50000,44.36131428571429,5.347851895453355
|
||||
8,35,280,50000,44.35445714285714,7.383874636503734
|
||||
|
+117
@@ -0,0 +1,117 @@
|
||||
Reproducibility notes
|
||||
=====================
|
||||
|
||||
We use evaluation data from the `KTO tutorial <https://github.com/NVIDIA/Model-Optimizer/blob/main/examples/megatron_bridge/tutorials/Qwen3.6-35B-A3B/kto/README.md#experiments-and-results>`__
|
||||
for the examples in the :doc:`evaluation article <../index>`.
|
||||
See its
|
||||
`reproducibility instructions <https://github.com/NVIDIA/Model-Optimizer/blob/main/examples/megatron_bridge/tutorials/Qwen3.6-35B-A3B/kto/reproducibility/README.md>`__
|
||||
for the checkpoints, subtask split, and evaluation settings.
|
||||
|
||||
.. _evaluation-statistical-methods:
|
||||
|
||||
Statistical methods
|
||||
-------------------
|
||||
|
||||
- **SciCode accuracy:** to estimate the mean accuracy difference, first average each model’s
|
||||
correctness across repetitions within each subtask, then compute **Candidate − Baseline** for
|
||||
that subtask. Average those differences across subtasks.
|
||||
For the confidence interval and p-values, group all scored subtasks and their repetitions by
|
||||
parent problem. For the 95% interval, draw 50,000 resamples of paired parent problems with
|
||||
replacement and take the 2.5th and 97.5th percentiles of the resulting mean differences.
|
||||
For the one-sided `paired permutation p-values
|
||||
<https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.permutation_test.html>`__,
|
||||
swap model labels for whole parent problems and count permuted mean differences at least as
|
||||
extreme as the observed difference in the tested direction. Use 50,000 random swap patterns
|
||||
and calculate the p-value as ``(extreme swaps + 1) / (total swaps + 1)``.
|
||||
|
||||
When question-level differences are independent and a t approximation is suitable, a paired
|
||||
t-based confidence interval and a one-sided paired t-test are alternatives.
|
||||
|
||||
- **Non-inferiority:** use a one-sided t-test to assess whether Candidate's accuracy loss is
|
||||
smaller than an acceptable margin. Use the same mean paired accuracy difference as above and
|
||||
estimate its standard error by grouping subtasks by parent problem. With all three quantities
|
||||
in pp, the t statistic is ``(mean_difference + margin) / standard_error``. Calculate the p-value
|
||||
from the upper tail of the t distribution with degrees of freedom equal to the number of parent
|
||||
problems minus one.
|
||||
|
||||
- **Cap-hit rates:** for each model, divide the number of responses that hit the completion cap
|
||||
by the total number of responses across all subtasks and repetitions.
|
||||
|
||||
Calculate a two-sided 95% paired-bootstrap confidence interval for the rate difference using
|
||||
50,000 resamples of whole SciCode parent problems with replacement. Keep all repetitions and
|
||||
both models together within each sampled group. The interval endpoints are the 2.5th and 97.5th
|
||||
percentiles.
|
||||
If neither model has an observed failure, bootstrapping gives a [0, 0] interval. This does not
|
||||
establish that failures cannot occur or that the models have equal failure rates.
|
||||
|
||||
- .. _evaluation-scicode-cap-hit-p-values:
|
||||
|
||||
**SciCode cap-hit p-values**
|
||||
|
||||
For the one-sided `paired permutation p-values
|
||||
<https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.permutation_test.html>`__,
|
||||
swap model labels for whole parent problems and count permuted cap-hit rate differences at least
|
||||
as extreme as the observed difference in the tested direction. For an exact p-value, divide
|
||||
this count by the total number of possible swap patterns.
|
||||
To estimate the p-value from random swaps, sample 50,000 swap patterns and use the same
|
||||
formula as for accuracy.
|
||||
Cap hits are rare, so most subtask differences are zero. The permutation test avoids relying
|
||||
on a t-distribution approximation for these sparse differences.
|
||||
|
||||
The outcomes are binary, but a simple binomial test on pooled responses would ignore question
|
||||
pairing and repetitions within each question. With one response per model and question and
|
||||
independent question pairs, an
|
||||
`exact McNemar test
|
||||
<https://www.statsmodels.org/stable/generated/statsmodels.stats.contingency_tables.mcnemar.html>`__
|
||||
is another paired option.
|
||||
|
||||
- **Verbosity:** to compare mean completion lengths, average each model’s response lengths across
|
||||
repetitions within each question, then subtract Baseline’s average from Candidate’s. Use these
|
||||
paired differences to calculate a two-sided t-based 95% confidence interval and run one-sided
|
||||
paired t-tests for the stated direction. Degrees of freedom equal the number of questions minus
|
||||
one.
|
||||
Compute each model's median completion length across all its responses. The verbosity tests
|
||||
compare mean lengths.
|
||||
|
||||
.. _evaluation-fixed-response-budgets:
|
||||
|
||||
Resampling at fixed response budgets
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
For each allocation, we simulate 50,000 evaluations using 294 eligible SciCode subtasks
|
||||
and eight saved runs. For R = 1, 2, 4, or 8 repetitions, draw 280/R subtask IDs with replacement
|
||||
and independently select R run IDs without replacement. This gives 280 sampled scores per model.
|
||||
Use the same selected runs for all subtasks in a simulated evaluation. If a subtask is drawn
|
||||
twice, its saved scores count twice. At eight repetitions, each evaluation uses all eight runs
|
||||
and the sampled subtasks still vary.
|
||||
|
||||
We use NumPy's random generator with seed ``20261201``. We compute Candidate accuracy for each
|
||||
simulated evaluation and report the mean in percent and the sample standard deviation in
|
||||
percentage points.
|
||||
|
||||
Subtask order for the cap-hit plot
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
For the cap-hit plot, shuffle the sorted IDs of the 294 eligible subtasks with seed
|
||||
``20261124`` and select prefixes of that order.
|
||||
|
||||
Saved metrics
|
||||
-------------
|
||||
|
||||
We save the means, standard deviations, confidence intervals, and p-values as CSV
|
||||
summaries:
|
||||
|
||||
- **SciCode: candidate accuracy at fixed response budgets** — data used in the
|
||||
:ref:`Choose between question-level and repetition-level analysis <evaluation-choose-questions-and-repetitions>`
|
||||
example.
|
||||
CSV file: :download:`budget-allocation-accuracy.csv <budget-allocation-accuracy.csv>`.
|
||||
- **SciCode: cap-hit rates** — data used in the
|
||||
:ref:`Collect as much evaluation data as you need <evaluation-collect-data>` example.
|
||||
CSV file: :download:`scicode-cap-data-volume.csv <scicode-cap-data-volume.csv>`.
|
||||
|
||||
Reproducibility limits
|
||||
----------------------
|
||||
|
||||
The checkpoints and paired measurements are stored outside the public ModelOpt repository.
|
||||
To keep the repository lightweight, we include summary results here rather than question-level
|
||||
data, generated responses, or a full experiment environment.
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
allocation,subtasks,repetitions,responses_per_model,baseline_count,candidate_count,baseline_pct,candidate_pct,difference_pp,ci_low_pp,ci_high_pp,ci_width_pp,ci_informative,candidate_less_p,candidate_greater_p
|
||||
more_subtasks,10,1,10,0,0,0.0,0.0,0.0,,,,False,1.0,1.0
|
||||
more_subtasks,50,1,50,1,0,2.0,0.0,-2.0,-6.122448979591836,0.0,6.122448979591836,True,0.5,1.0
|
||||
more_subtasks,100,1,100,1,0,1.0,0.0,-1.0,-3.061224489795918,0.0,3.061224489795918,True,0.5,1.0
|
||||
more_subtasks,150,1,150,2,0,1.3333333333333333,0.0,-1.3333333333333333,-3.2679738562091507,0.0,3.2679738562091507,True,0.25,1.0
|
||||
more_subtasks,200,1,200,4,0,2.0,0.0,-2.0,-3.9647577092511015,-0.4830917874396135,3.481665921811488,True,0.0625,1.0
|
||||
more_subtasks,250,1,250,5,0,2.0,0.0,-2.0,-3.75,-0.4329004329004329,3.317099567099567,True,0.03125,1.0
|
||||
more_subtasks,294,1,294,6,0,2.0408163265306123,0.0,-2.0408163265306123,-3.691300980898297,-0.6688963210702341,3.0224046598280627,True,0.015625,1.0
|
||||
more_repetitions,294,1,294,6,0,2.0408163265306123,0.0,-2.0408163265306123,-3.691300980898297,-0.6688963210702341,3.0224046598280627,True,0.015625,1.0
|
||||
more_repetitions,294,2,588,9,0,1.530612244897959,0.0,-1.530612244897959,-2.464788732394366,-0.6830484529737586,1.7817402794206074,True,0.001953125,1.0
|
||||
more_repetitions,294,3,882,12,0,1.3605442176870748,0.0,-1.3605442176870748,-2.1080368906455855,-0.6734006734006733,1.434636217244912,True,0.00048828125,1.0
|
||||
more_repetitions,294,4,1176,17,0,1.445578231292517,0.0,-1.445578231292517,-2.181818181818182,-0.78125,1.400568181818182,True,6.103515625e-05,1.0
|
||||
more_repetitions,294,5,1470,25,0,1.7006802721088434,0.0,-1.7006802721088434,-2.323943661971832,-1.107011070110701,1.216932591861131,True,4.76837158203125e-07,1.0
|
||||
more_repetitions,294,6,1764,28,0,1.5873015873015872,0.0,-1.5873015873015872,-2.192982456140351,-0.997652582159624,1.195329873980727,True,4.76837158203125e-07,1.0
|
||||
more_repetitions,294,7,2058,31,0,1.5063168124392614,0.0,-1.5063168124392614,-2.034498009730208,-0.9777294948397608,1.056768514890447,True,2.384185791015625e-07,1.0
|
||||
more_repetitions,294,8,2352,36,0,1.530612244897959,0.0,-1.530612244897959,-2.027027027027027,-1.0375494071146245,0.9894776199124027,True,2.9802322387695312e-08,1.0
|
||||
|
@@ -0,0 +1,21 @@
|
||||
Evaluation
|
||||
==========
|
||||
|
||||
* ModelOpt skills: for standardized evaluation and acceptance checks before
|
||||
releasing optimized models, follow the
|
||||
`ModelOpt evaluation skill <https://github.com/NVIDIA/Model-Optimizer/blob/main/skills/modelopt-evaluation/SKILL.md>`__
|
||||
and
|
||||
`ModelOpt results-comparison skill <https://github.com/NVIDIA/Model-Optimizer/blob/main/skills/modelopt-compare-results/SKILL.md>`__.
|
||||
|
||||
* `LLM evaluation examples <https://github.com/NVIDIA/Model-Optimizer/blob/main/examples/llm_eval/README.md>`__:
|
||||
benchmark frameworks, setup, and evaluation commands.
|
||||
|
||||
* :doc:`Evaluating Models Efficiently During Optimization Experiments <../../announcements/evaluating_models_efficiently_during_optimization_experiments/index>`:
|
||||
evaluate models quickly and reliably during optimization experiments, with worked examples
|
||||
of metrics, regression and reliability checks, and evaluation budgets.
|
||||
|
||||
.. toctree::
|
||||
:hidden:
|
||||
:maxdepth: 1
|
||||
|
||||
Evaluating Models Efficiently During Optimization Experiments <../../announcements/evaluating_models_efficiently_during_optimization_experiments/index>
|
||||
@@ -11,6 +11,8 @@ Release notes, technical updates, examples, and deployment stories from the Mode
|
||||
<input id="announcement-search" class="announcement-search" type="search" placeholder="Search announcements" autocomplete="off" />
|
||||
<div class="announcement-tags" aria-label="Announcement tags">
|
||||
<button class="announcement-tag is-active" type="button" data-tag="all" aria-pressed="true">All</button>
|
||||
<button class="announcement-tag" type="button" data-tag="evaluation" aria-pressed="false">Evaluation</button>
|
||||
<button class="announcement-tag" type="button" data-tag="fast-experimentation" aria-pressed="false">Fast experimentation</button>
|
||||
<button class="announcement-tag" type="button" data-tag="release" aria-pressed="false">Release</button>
|
||||
<button class="announcement-tag" type="button" data-tag="autoquantize" aria-pressed="false">AutoQuantize</button>
|
||||
<button class="announcement-tag" type="button" data-tag="kv-cache" aria-pressed="false">KV cache</button>
|
||||
@@ -31,6 +33,17 @@ Release notes, technical updates, examples, and deployment stories from the Mode
|
||||
</div>
|
||||
|
||||
<div class="announcement-grid" id="announcement-grid">
|
||||
<article class="announcement-card" data-date="2026-11-18" data-title="Evaluating Models Efficiently During Optimization Experiments" data-summary="Compare checkpoints during optimization experiments: choose metrics, check regressions and reliability, and balance question coverage with repeated runs." data-tags="evaluation docs quantization qad fast-experimentation">
|
||||
<div class="announcement-card-meta">November 18, 2026 ·
|
||||
<a href="https://github.com/danielkorzekwa">Daniel Korzekwa</a>,
|
||||
<a href="https://github.com/rohansjoshi">Rohan Joshi</a>,
|
||||
<a href="https://github.com/chadvoegele">Chad Voegele</a>,
|
||||
<a href="https://github.com/cjluo-nv">Chenjie Luo</a>
|
||||
</div>
|
||||
<h2><a href="announcements/evaluating_models_efficiently_during_optimization_experiments/index.html">Evaluating Models Efficiently During Optimization Experiments</a></h2>
|
||||
<p>Compare checkpoints during optimization experiments: choose metrics, check regressions and reliability, and balance question coverage with repeated runs.</p>
|
||||
<div class="announcement-card-tags"><span>evaluation</span><span>docs</span><span>quantization</span><span>qad</span><span>fast-experimentation</span></div>
|
||||
</article>
|
||||
<article class="announcement-card" data-date="2026-11-17" data-title="Training Standalone Speculative Decoding Drafts for Fast Inference on Groq 3 LPX" data-summary="Three ModelOpt-trained standalone drafts for Qwen3.8-27B, intended for Groq 3 LPX deployment. At unbounded draft length, offline scoring gives the 4B and 0.8B drafts 59% and 6% higher acceptance lengths than the live MTP baseline." data-tags="speculative-decoding external-draft groq-lpx qwen3.8 distillation">
|
||||
<div class="announcement-card-meta">November 17, 2026 · Peter Hicks et al.</div>
|
||||
<h2><a href="announcements/20261117-qwen38-27b-external-drafts-lpx.html">Training Standalone Speculative Decoding Drafts for Fast Inference on Groq 3 LPX</a></h2>
|
||||
@@ -139,6 +152,7 @@ Release notes, technical updates, examples, and deployment stories from the Mode
|
||||
guides/0_support_matrix
|
||||
guides/1_quantization
|
||||
guides/quantization_aware_training_and_distillation
|
||||
guides/evaluation/index
|
||||
guides/2_save_load
|
||||
guides/3_pruning
|
||||
guides/4_distillation
|
||||
|
||||
@@ -621,6 +621,16 @@ Changing only `effective_bits` finalizes the same scores at another budget; the
|
||||
cost model come from the checkpoint, so change those with a new one. From Python,
|
||||
`mtq.get_auto_quantize_config(search_state, constraints, algorithm=...)` returns the finalized config.
|
||||
|
||||
A search that resumes on the model solves with its candidates' costs recomputed from the model
|
||||
(keeping the scores); the cost refresh itself does not write the checkpoint, though a search may still
|
||||
save it (to finish calibration or scoring, or after solving with `aumann_shapley` or the `kv_cache` cost
|
||||
model). A checkpoint saved before ModelOpt 0.50 may
|
||||
count non-gated fused experts at half size, and the finalize rerun, which re-solves it without the
|
||||
model, warns about it; to finalize with corrected costs, rerun the search with a new
|
||||
`--auto_quantize_checkpoint` (format shards included: rescore each shard, then merge). Counting the experts in full shifts the smallest `constraints.effective_bits` the search can meet
|
||||
(up or down, depending on how cheap the experts' cheapest format is); if a value that fit before is now
|
||||
refused as infeasible, raise it to a feasible value.
|
||||
|
||||
Gradient and `kl_div` searches can also score their formats in parallel processes, at most one
|
||||
*format shard* per searched format. Give every shard the same explicit `--batch_size` and its own
|
||||
checkpoint, then merge them into a new checkpoint. The merge run solves and exports like the
|
||||
|
||||
@@ -4,6 +4,8 @@ This folder includes popular 3rd-party LLM benchmarks for LLM accuracy evaluatio
|
||||
|
||||
The following instructions show how to evaluate the Model Optimizer quantized LLM with the benchmarks, including the TensorRT-LLM deployment.
|
||||
|
||||
For guidance on evaluation design, metrics, data budgets, and interpreting model comparisons, see [Evaluation documentation](https://nvidia.github.io/Model-Optimizer/guides/evaluation/index.html). For AI-assisted workflows, see the skills for [running evaluations](https://github.com/NVIDIA/Model-Optimizer/blob/main/skills/modelopt-evaluation/SKILL.md) and [comparing results](https://github.com/NVIDIA/Model-Optimizer/blob/main/skills/modelopt-compare-results/SKILL.md).
|
||||
|
||||
## NeMo Evaluator
|
||||
|
||||
[NeMo Evaluator](https://docs.nvidia.com/nemo/evaluator/latest/get-started/quickstart/index.html#self-hosted-options) is the recommended way to evaluate a large choice of benchmarks on quantized checkpoints generated from [hf_ptq](../hf_ptq). Quantized checkpoints can be served with [TensorRT-LLM](https://github.com/NVIDIA/TensorRT-LLM), [vLLM](https://github.com/vllm-project/vllm), or [SGLang](https://github.com/sgl-project/sglang) and then evaluated using NeMo Evaluator.
|
||||
|
||||
@@ -136,7 +136,7 @@ torchrun --nproc_per_node 2 export_quantized_megatron_to_hf.py \
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> Megatron-Bridge writes the export at any `--tp_size` / `--ep_size` / `--pp_size`, with the quantization config inline in `config.json`, when it provides `AutoBridge.save_hf_pretrained_modelopt` (newer than the one in `nemo:26.10`) and can export every enabled quantizer: KV-cache quantizers (e.g. `--kv_cache_quant fp8` or a `*-kv_fp8*` recipe) need a Megatron-Bridge with #7057. Otherwise, and for GGML / IQ formats, `--export_extra_modules` or a VLM's language-model-only QAD checkpoint, ModelOpt's Megatron exporter writes it and `--tp_size` above 1 raises: use `--pp_size` (or `--ep_size`) to shard a large model across GPUs instead, except for GGML / IQ formats, which export at `--tp_size 1 --pp_size 1` only.
|
||||
> Megatron-Bridge writes the export at any `--tp_size` / `--ep_size` / `--pp_size`, with the quantization config inline in `config.json`, when it provides `AutoBridge.save_hf_pretrained_modelopt` (newer than the one in `nemo:26.10`) and can export every enabled quantizer: KV-cache quantizers (e.g. `--kv_cache_quant fp8` or a `*-kv_fp8*` recipe) need a Megatron-Bridge with #7057. A VLM's language-model-only QAD checkpoint is loaded over the HF weights, so the export carries the HF vision tower. Otherwise, and for GGML / IQ formats, `--export_extra_modules` or a model whose bridge post-processes exported weights (e.g. Nemotron 3.5 Super VL), ModelOpt's Megatron exporter writes it and `--tp_size` above 1 raises: use `--pp_size` (or `--ep_size`) to shard a large model across GPUs instead, except for GGML / IQ formats, which export at `--tp_size 1 --pp_size 1` only.
|
||||
|
||||
> [!TIP]
|
||||
> To recover the accuracy lost during quantization, fine-tune the quantized Megatron checkpoint (from step 1) with [Quantization Aware Distillation (QAD)](#quantization-aware-distillation-qad) before running the step 2 export.
|
||||
|
||||
@@ -21,9 +21,10 @@ The process is as follows:
|
||||
3. Export the model to a HuggingFace (unified) checkpoint. Megatron-Bridge writes it at any
|
||||
TP / EP / PP when it provides ``AutoBridge.save_hf_pretrained_modelopt`` and can export every
|
||||
enabled quantizer (e.g. the KV-cache ones only since Megatron-Bridge #7057). Otherwise, and for
|
||||
what it doesn't cover (GGML / IQ formats, --export_extra_modules, a VLM's language-model-only
|
||||
QAD checkpoint), ModelOpt's Megatron exporter writes it at tensor_model_parallel_size=1: use
|
||||
--pp_size and/or --ep_size to shard a large model, except GGML / IQ formats (TP=1 and PP=1).
|
||||
what it doesn't cover (GGML / IQ formats, --export_extra_modules), ModelOpt's Megatron
|
||||
exporter writes it at tensor_model_parallel_size=1: use --pp_size and/or --ep_size to shard a
|
||||
large model, except GGML / IQ formats (TP=1 and PP=1). A VLM's language-model-only (QAD)
|
||||
checkpoint is loaded over the HF weights, so its export carries the HF vision tower.
|
||||
|
||||
Example usage to export an FP8 checkpoint produced by quantize.py:
|
||||
|
||||
@@ -52,6 +53,7 @@ See `README.md` in this directory for more details.
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
@@ -85,6 +87,7 @@ from modelopt.torch.utils.plugins.mbridge import (
|
||||
is_vlm_config,
|
||||
load_mbridge_model_from_hf,
|
||||
load_modelopt_megatron_checkpoint,
|
||||
resolve_modelopt_megatron_checkpoint,
|
||||
use_moe_grouped_gemm,
|
||||
)
|
||||
|
||||
@@ -147,8 +150,8 @@ def get_args() -> argparse.Namespace:
|
||||
"--export_extra_modules",
|
||||
action="store_true",
|
||||
help=(
|
||||
"Export extra modules such as Medusa heads, EAGLE, or MTP (ModelOpt's Megatron "
|
||||
"exporter only, at --tp_size 1)."
|
||||
"Write the EAGLE draft module as a separate draft checkpoint instead of the model "
|
||||
"(ModelOpt's Megatron exporter only, at --tp_size 1)."
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
@@ -271,18 +274,16 @@ def bridge_rejected_by_quantized_export(bridge) -> str | None:
|
||||
|
||||
|
||||
def bridge_export_unsupported(
|
||||
bridge, model: list, args: argparse.Namespace, language_model_only: bool
|
||||
bridge, model: list, args: argparse.Namespace
|
||||
) -> tuple[str | None, bool]:
|
||||
"""Why Megatron-Bridge's quantized export can't write this checkpoint, alike on every rank.
|
||||
|
||||
Returns the reason (None if it can) and whether the checkpoint has GGML / IQ formats, which
|
||||
ModelOpt's Megatron exporter writes at TP=1 and PP=1 only. Megatron-Bridge's export needs
|
||||
``AutoBridge.save_hf_pretrained_modelopt`` and doesn't cover GGML / IQ formats, extra modules
|
||||
(EAGLE / Medusa / MTP), or a VLM's language-model-only checkpoint (it saves the in-memory
|
||||
vision tower, which that checkpoint doesn't hold; ModelOpt's exporter copies it from the HF
|
||||
source), or models whose bridge it rejects (see :func:`bridge_rejected_by_quantized_export`), and
|
||||
packs fewer weight formats (see :func:`unexportable_weight`). Older Megatron-Bridge versions
|
||||
also reject some quantizers (e.g. KV-cache ones).
|
||||
(EAGLE), or models whose bridge it rejects (see :func:`bridge_rejected_by_quantized_export`),
|
||||
and packs fewer weight formats (see :func:`unexportable_weight`). Older Megatron-Bridge
|
||||
versions also reject some quantizers (e.g. KV-cache ones).
|
||||
"""
|
||||
try:
|
||||
from megatron.bridge.models.conversion.modelopt_utils import check_exportable_quantizers
|
||||
@@ -296,7 +297,6 @@ def bridge_export_unsupported(
|
||||
check_exportable_quantizers is None
|
||||
or not hasattr(bridge, "save_hf_pretrained_modelopt")
|
||||
),
|
||||
int(language_model_only),
|
||||
int(any(uses_iq_quantization(unwrap_model(chunk)) for chunk in model)),
|
||||
# Not scanned when ModelOpt's exporter is forced.
|
||||
int(
|
||||
@@ -312,15 +312,13 @@ def bridge_export_unsupported(
|
||||
)
|
||||
if torch.distributed.is_initialized():
|
||||
torch.distributed.all_reduce(flags, op=torch.distributed.ReduceOp.MAX)
|
||||
no_writer, language_model_only, ggml, unexportable = (bool(flag) for flag in flags.tolist())
|
||||
no_writer, ggml, unexportable = (bool(flag) for flag in flags.tolist())
|
||||
if args.modelopt_megatron_exporter:
|
||||
return "--modelopt_megatron_exporter", ggml
|
||||
if no_writer:
|
||||
return "this Megatron-Bridge has no save_hf_pretrained_modelopt", ggml
|
||||
if args.export_extra_modules:
|
||||
return "--export_extra_modules", ggml
|
||||
if language_model_only:
|
||||
return "a VLM's language-model-only checkpoint (e.g. from QAD)", ggml
|
||||
# The same model bridge on every rank.
|
||||
if (rejected := bridge_rejected_by_quantized_export(bridge)) is not None:
|
||||
return f"Megatron-Bridge's quantized export rejects {rejected}", ggml
|
||||
@@ -337,15 +335,13 @@ def bridge_export_unsupported(
|
||||
return None, False
|
||||
|
||||
|
||||
def use_bridge_export(
|
||||
bridge, model: list, args: argparse.Namespace, language_model_only: bool
|
||||
) -> bool:
|
||||
def use_bridge_export(bridge, model: list, args: argparse.Namespace) -> bool:
|
||||
"""Whether Megatron-Bridge writes the unified export, else ModelOpt's Megatron exporter.
|
||||
|
||||
Decided alike on every rank, which all raise if the exporter it falls to can't run at this
|
||||
parallelism (also when --modelopt_megatron_exporter or --export_extra_modules selects it).
|
||||
"""
|
||||
unsupported, ggml = bridge_export_unsupported(bridge, model, args, language_model_only)
|
||||
unsupported, ggml = bridge_export_unsupported(bridge, model, args)
|
||||
if unsupported is None:
|
||||
return True
|
||||
if ggml and (args.tp_size != 1 or args.pp_size != 1):
|
||||
@@ -364,6 +360,26 @@ def use_bridge_export(
|
||||
return False
|
||||
|
||||
|
||||
def load_quantized_checkpoint(bridge, model: list, args: argparse.Namespace) -> None:
|
||||
"""Load the quantized Megatron checkpoint into ``model``.
|
||||
|
||||
Megatron-Bridge saves the whole in-memory model, and a VLM's QAD checkpoint holds only the
|
||||
language model: for its Megatron-Bridge export, the HF weights (with the vision tower) load
|
||||
first and the checkpoint over them. The checkpoint iteration is resolved once for both steps.
|
||||
"""
|
||||
checkpoint_path, language_model_only = resolve_modelopt_megatron_checkpoint(
|
||||
model, args.megatron_path
|
||||
)
|
||||
# The vLLM fake-quant export loaded the HF weights already, and ModelOpt's exporter, when
|
||||
# selected up front, copies the vision tower from the HF source itself.
|
||||
if language_model_only and not (
|
||||
args.vllm_fakequant_export or args.modelopt_megatron_exporter or args.export_extra_modules
|
||||
):
|
||||
bridge.load_hf_weights(model, args.local_checkpoint_path)
|
||||
print_rank_0(f"Loading quantized Megatron checkpoint from {checkpoint_path}...")
|
||||
load_modelopt_megatron_checkpoint(model, checkpoint_path)
|
||||
|
||||
|
||||
def export_bridge_hf(bridge, model: list, args: argparse.Namespace) -> None:
|
||||
"""Export the quantized model to a unified HF checkpoint with Megatron-Bridge (any TP/EP/PP)."""
|
||||
print_rank_0(
|
||||
@@ -399,14 +415,20 @@ def export_unified_hf(unwrapped_model, args: argparse.Namespace, trust_remote_co
|
||||
f"Exporting to HuggingFace (unified) checkpoint at {args.export_unified_hf_path}..."
|
||||
)
|
||||
# TODO: Gemma3-VL is not in export_mcore_gpt_to_hf's per-arch mappings yet.
|
||||
export_mcore_gpt_to_hf(
|
||||
unwrapped_model,
|
||||
args.local_checkpoint_path,
|
||||
export_extra_modules=export_extra_modules,
|
||||
dtype=torch.bfloat16,
|
||||
export_dir=args.export_unified_hf_path,
|
||||
trust_remote_code=trust_remote_code,
|
||||
)
|
||||
# This script falls back to this exporter only where Megatron-Bridge's can't export (or when
|
||||
# --modelopt_megatron_exporter asks for it), so it doesn't pass the deprecation warning on.
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings(
|
||||
"ignore", "export_mcore_gpt_to_hf is deprecated", DeprecationWarning
|
||||
)
|
||||
export_mcore_gpt_to_hf(
|
||||
unwrapped_model,
|
||||
args.local_checkpoint_path,
|
||||
export_extra_modules=export_extra_modules,
|
||||
dtype=torch.bfloat16,
|
||||
export_dir=args.export_unified_hf_path,
|
||||
trust_remote_code=trust_remote_code,
|
||||
)
|
||||
|
||||
|
||||
def main(args: argparse.Namespace):
|
||||
@@ -452,20 +474,16 @@ def main(args: argparse.Namespace):
|
||||
load_weights=args.vllm_fakequant_export
|
||||
and is_vlm_config(args.local_checkpoint_path, trust_remote_code=trust_remote_code),
|
||||
)
|
||||
|
||||
# Load the quantized checkpoint (with the correct layer spec) rather than reconstructing it from the checkpoint
|
||||
# config, which avoids the non-serializable layer-spec issue for MoE / Mamba models.
|
||||
print_rank_0(f"Loading quantized Megatron checkpoint from {args.megatron_path}...")
|
||||
loaded = load_modelopt_megatron_checkpoint(model, args.megatron_path)
|
||||
# Only a VLM's language-model-only checkpoint loads into other modules (``.language_model``).
|
||||
language_model_only = loaded is not model
|
||||
load_quantized_checkpoint(bridge, model, args)
|
||||
unwrapped_model = unwrap_model(model[0])
|
||||
mtq.merge_quant_lora(unwrapped_model)
|
||||
|
||||
if args.vllm_fakequant_export:
|
||||
print_rank_0(f"Exporting vLLM fake-quant checkpoint to {args.export_unified_hf_path}...")
|
||||
export_vllm_fakequant(bridge, model, args.export_unified_hf_path)
|
||||
elif use_bridge_export(bridge, model, args, language_model_only):
|
||||
elif use_bridge_export(bridge, model, args):
|
||||
export_bridge_hf(bridge, model, args)
|
||||
else:
|
||||
export_unified_hf(unwrapped_model, args, trust_remote_code)
|
||||
|
||||
@@ -95,6 +95,8 @@ Megatron EAGLE supports the same mode: set `eagle_mix_hidden_states=True` and
|
||||
`eagle_mix_hidden_states_mode="uniform_layer_sample"` in the `EagleConfig` passed to `mtsp.convert`.
|
||||
|
||||
To enable context parallelism for long-context training, add `training.cp_size=<N>`.
|
||||
DFlash supports it only for the plain DFlash draft trained offline (`data.offline_data_path`),
|
||||
without `dflash_use_torch_compile`; `training_seq_len` must be divisible by `cp_size`.
|
||||
The saved modelopt checkpoint is similar in architecture to HF models. It can be further optimized through **ModelOpt**, e.g., PTQ and QAT.
|
||||
|
||||
## Training Draft Model with Offline Base Model
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import contextlib
|
||||
import inspect
|
||||
import random
|
||||
from collections.abc import Callable
|
||||
@@ -340,6 +341,17 @@ class EagleTrainerWithAccLog(Trainer):
|
||||
finally:
|
||||
self.accelerator.gradient_accumulation_steps = accumulation_steps
|
||||
|
||||
def _prepare_context_parallel_inputs(self, model, inputs):
|
||||
"""Let a DFlash draft shard its own context, without torch's ring attention.
|
||||
|
||||
Ring attention covers causal self-attention only, and shards the token inputs that
|
||||
every DFlash rank needs whole.
|
||||
"""
|
||||
if getattr(self.model, "context_parallel_enabled", False):
|
||||
self.model.shard_context(inputs["base_model_outputs"])
|
||||
return contextlib.nullcontext, inputs
|
||||
return super()._prepare_context_parallel_inputs(model, inputs)
|
||||
|
||||
def compute_loss(self, *args, **kwargs):
|
||||
"""Override compute_loss to save train accs and per-component losses in trainer state."""
|
||||
if not hasattr(self.state, "training_accs"):
|
||||
|
||||
@@ -164,6 +164,21 @@ def init_distributed_env(training_args: transformers.TrainingArguments) -> None:
|
||||
)
|
||||
|
||||
|
||||
def check_dflash_context_parallel(model, recipe, training_args) -> None:
|
||||
"""Refuse a DFlash run whose ``cp_size > 1`` setup is not supported."""
|
||||
if recipe.data.mode != "offline":
|
||||
raise ValueError(
|
||||
"DFlash context parallelism (cp_size > 1) needs data.offline_data_path; "
|
||||
f"data.mode={recipe.data.mode!r} is not supported."
|
||||
)
|
||||
if training_args.training_seq_len % training_args.cp_size:
|
||||
raise ValueError(
|
||||
f"training_seq_len ({training_args.training_seq_len}) must be divisible by "
|
||||
f"cp_size ({training_args.cp_size})."
|
||||
)
|
||||
model.check_context_parallel_support()
|
||||
|
||||
|
||||
def _is_hf_format_checkpoint(checkpoint: str | None) -> bool:
|
||||
"""True if the checkpoint dir holds consolidated HF weights (from_pretrained-loadable).
|
||||
|
||||
@@ -492,8 +507,11 @@ def train():
|
||||
)
|
||||
return
|
||||
|
||||
print_rank_0("Loading dataset...")
|
||||
is_dflash = isinstance(recipe, ModelOptDFlashRecipe)
|
||||
if is_dflash and training_args.cp_size > 1:
|
||||
check_dflash_context_parallel(model, recipe, training_args)
|
||||
|
||||
print_rank_0("Loading dataset...")
|
||||
if recipe.data.mode == "sparse" and not isinstance(recipe, ModelOptExternalDraftRecipe):
|
||||
# Only the external draft reads a sparse policy. Any other mode would build the
|
||||
# dataset, hand the collator's teacher_topk_* to a forward that ignores them, and
|
||||
@@ -573,6 +591,9 @@ def train():
|
||||
if os.environ.get("PATCH_FSDP2_BUFFERS_TF457") == "1":
|
||||
fsdp2_buffer_patch.patch_accelerator(trainer.accelerator)
|
||||
|
||||
if is_dflash and training_args.cp_size > 1:
|
||||
model.enable_context_parallel(trainer.accelerator.torch_device_mesh["cp"].get_group())
|
||||
|
||||
# DFlash: export the draft submodule after each checkpoint save — but only under FSDP2
|
||||
# SHARDED_STATE_DICT, where checkpoints are distributed shards the post-training
|
||||
# export_hf_checkpoint.py pass can't read. Gate by reading the live FSDP state dict
|
||||
|
||||
@@ -45,7 +45,9 @@ from modelopt.torch.quantization.utils import get_quantizer_state_dict
|
||||
from modelopt.torch.quantization.utils.core_utils import (
|
||||
ModuleNames,
|
||||
enable_weight_access_and_writeback,
|
||||
has_accelerate_offload,
|
||||
module_name_maps,
|
||||
requires_weight_materialization,
|
||||
)
|
||||
from modelopt.torch.quantization.utils.layerwise_calib import LayerActivationCollector
|
||||
from modelopt.torch.utils import get_unwrapped_name, safe_save
|
||||
@@ -54,6 +56,7 @@ from modelopt.torch.utils.plugins.hf_checkpoint_utils import copy_off_index_safe
|
||||
from ..layer_utils import get_experts_list
|
||||
from ..quant_utils import get_quantization_format
|
||||
from ..unified_export_hf import (
|
||||
_check_export_offload,
|
||||
_copy_non_model_files_from_source,
|
||||
_source_checkpoint,
|
||||
collect_shared_input_modules,
|
||||
@@ -396,7 +399,8 @@ def _enable_writeback_for_group(
|
||||
"""
|
||||
with ExitStack() as stack:
|
||||
for m in group:
|
||||
stack.enter_context(enable_weight_access_and_writeback(m, root_model, names))
|
||||
if has_accelerate_offload(m) or requires_weight_materialization(m, root_model, names):
|
||||
stack.enter_context(enable_weight_access_and_writeback(m, root_model, names))
|
||||
yield
|
||||
|
||||
|
||||
@@ -656,6 +660,7 @@ def export_hf_vllm_fq_checkpoint(
|
||||
dict materialization. This is destructive — model weights are permanently
|
||||
modified and weight quantizers are not re-enabled after export.
|
||||
"""
|
||||
_check_export_offload(model)
|
||||
export_dir = Path(export_dir)
|
||||
export_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -701,6 +706,8 @@ def export_hf_vllm_fq_checkpoint(
|
||||
# Default path: fakequant into the resmoothed state_dict copy (do not refresh
|
||||
# from model.state_dict() or resmooth is lost).
|
||||
for module_name, module in model.named_modules():
|
||||
if not isinstance(module, QuantModule):
|
||||
continue
|
||||
with enable_weight_access_and_writeback(module, model):
|
||||
_fakequant_module_weights(
|
||||
module,
|
||||
|
||||
@@ -111,6 +111,7 @@ from modelopt.torch.utils.distributed import (
|
||||
broadcast_from,
|
||||
distribution_plan,
|
||||
is_fsdp2_model,
|
||||
recorded_distribution_plan,
|
||||
)
|
||||
from modelopt.torch.utils.fsdp2_utils import fsdp2_root_unsharded
|
||||
from modelopt.torch.utils.perf import maybe_clear_cuda_cache
|
||||
@@ -1081,12 +1082,36 @@ def _convert_custom_backends(model: nn.Module) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _check_export_offload(model, *, whole_state=False):
|
||||
"""Agree before dispatching an FSDP2 export, and keep whole-state export off offloaded models."""
|
||||
plan = recorded_distribution_plan(model) if isinstance(model, nn.Module) else None
|
||||
if bool(plan is not None and plan.is_fsdp_dense) or (
|
||||
isinstance(model, nn.Module) and is_fsdp2_model(model)
|
||||
):
|
||||
if all_reduce(
|
||||
"accelerate offload",
|
||||
lambda: has_accelerate_offload(model, include_suspended=True),
|
||||
any,
|
||||
):
|
||||
raise NotImplementedError(
|
||||
"Reload the FSDP2 model without Accelerate CPU/disk offload before export. "
|
||||
"Closing a weight-access window leaves the offload hooks installed."
|
||||
)
|
||||
elif whole_state and has_accelerate_offload(model):
|
||||
raise NotImplementedError(
|
||||
"_export_transformers_checkpoint does not support disk/CPU-offloaded models. "
|
||||
"Use export_hf_checkpoint() which dispatches to _export_transformers_checkpoint_streaming."
|
||||
)
|
||||
|
||||
|
||||
def _prepare_model_for_export(model, dtype, is_modelopt_qlora):
|
||||
"""Run the shared export setup. Packing the weights is a separate step.
|
||||
|
||||
Both export paths call this so they cannot drift. Returns the dtype, the tied-weight map and
|
||||
the quant config.
|
||||
"""
|
||||
_check_export_offload(model, whole_state=True)
|
||||
|
||||
_convert_custom_backends(model)
|
||||
dtype = _resolve_export_dtype(model, dtype)
|
||||
# One tied-weight map for the whole export (amax sync + final dedup in postprocess_state_dict).
|
||||
@@ -1098,14 +1123,6 @@ def _prepare_model_for_export(model, dtype, is_modelopt_qlora):
|
||||
# TODO: Handle mixed precision
|
||||
requantize_resmooth_fused_llm_layers(model)
|
||||
|
||||
# Offloaded models need their weights materialized layer-by-layer, which this
|
||||
# whole-state-dict path cannot do; export_hf_checkpoint() streams them instead.
|
||||
if has_accelerate_offload(model):
|
||||
raise NotImplementedError(
|
||||
"_export_transformers_checkpoint does not support disk/CPU-offloaded models. "
|
||||
"Use export_hf_checkpoint() which dispatches to _export_transformers_checkpoint_streaming."
|
||||
)
|
||||
|
||||
# Remove all hooks from the model
|
||||
try:
|
||||
from accelerate.hooks import remove_hook_from_module
|
||||
@@ -2289,6 +2306,7 @@ def export_hf_checkpoint(
|
||||
)
|
||||
# Each rank holds only its own experts' quantizers, so they are agreed on before any folds.
|
||||
_agree_on_fused_expert_quantization(model)
|
||||
_check_export_offload(model)
|
||||
# Either form of sharding, including the hybrid where both hold: a model can be FSDP2-dense AND
|
||||
# expert-parallel, so these are tracked separately rather than as an either/or.
|
||||
_sharded_export = _ep_sharded or _fsdp2_sharded
|
||||
|
||||
@@ -157,8 +157,8 @@ class GPTModelExporter:
|
||||
are copied into the export from a local directory only; for a model ID they are
|
||||
skipped with a warning. Get a local copy first with
|
||||
`modelopt.torch.export.ensure_local_checkpoint` to include them.
|
||||
export_extra_modules: If True, export extra modules like medusa_heads or
|
||||
eagle_module. Otherwise, only export the base model.
|
||||
export_extra_modules: If True, export extra modules like eagle_module. Otherwise,
|
||||
only export the base model.
|
||||
dtype: The weights data type to export the unquantized layers.
|
||||
trust_remote_code: Whether to trust remote code in the HuggingFace pretrained model.
|
||||
moe_router_dtype: Storage dtype override for the exported MoE router weight, "fp32",
|
||||
@@ -2711,12 +2711,68 @@ def export_mcore_gpt_to_hf(
|
||||
are copied into the export from a local directory only; for a model ID they are
|
||||
skipped with a warning. Get a local copy first with
|
||||
`modelopt.torch.export.ensure_local_checkpoint` to include them.
|
||||
export_extra_modules: If True, export extra modules like medusa_heads or
|
||||
eagle_module. Otherwise, only export the base model.
|
||||
export_extra_modules: If True, export extra modules like eagle_module. Otherwise,
|
||||
only export the base model.
|
||||
dtype: The weights data type to export the unquantized layers.
|
||||
export_dir: The target export path.
|
||||
clamp_kv_cache_scales: Whether to clamp FP8 KV cache scaling factors to at least 1.0.
|
||||
|
||||
.. deprecated:: 0.50.0
|
||||
Planned for removal in 0.51.0. Where it supports the checkpoint, export with
|
||||
Megatron-Bridge's ``AutoBridge.save_hf_pretrained_modelopt`` instead.
|
||||
``examples/megatron_bridge/export_quantized_megatron_to_hf.py`` does this and copies the
|
||||
source's non-model files. It checks only what Megatron-Bridge can export: otherwise it
|
||||
falls back to this function, which exports the checkpoint only within its own limits (see
|
||||
below). ``save_hf_pretrained_modelopt`` needs a Megatron-Bridge newer than the one in
|
||||
``nemo:26.10``; ModelOpt tests it at the commit ``examples/megatron_bridge/README.md``
|
||||
names. To call it directly, from the quantized model chunks and the local HF source
|
||||
checkpoint:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
bridge = AutoBridge.from_hf_pretrained(hf_path)
|
||||
bridge.save_hf_pretrained_modelopt(model_chunks, export_dir, source_path=hf_path)
|
||||
# Megatron-Bridge saves only the config, tokenizer and remote code; carry over the
|
||||
# source's other non-model files (chat templates, assets) as this function does.
|
||||
if torch.distributed.get_rank() == 0:
|
||||
copy_non_model_files(hf_path, export_dir)
|
||||
|
||||
Megatron-Bridge writes the model as it is in memory, so ``model_chunks`` must hold the
|
||||
whole loaded model. For a VLM checkpoint that holds only the language model, load the HF
|
||||
weights first (``bridge.load_hf_weights(model_chunks, hf_path)``) and the checkpoint over
|
||||
them, as the example does; unlike this function, Megatron-Bridge doesn't copy the vision
|
||||
tower from ``source_path``.
|
||||
|
||||
Megatron-Bridge doesn't export these yet:
|
||||
|
||||
* GGML / IQ formats;
|
||||
* EAGLE modules (``export_extra_modules=True``);
|
||||
* models whose Megatron-Bridge bridge post-processes the exported weights (e.g.
|
||||
Nemotron 3.5 Super VL);
|
||||
* KV-cache quantizers, with a Megatron-Bridge older than NVIDIA-NeMo/Megatron-Bridge#7057
|
||||
(including the commit the README names).
|
||||
|
||||
This function covers them only for the architectures in its rule tables
|
||||
(``modelopt/torch/export/plugins/mcore_*.py``) and at TP=1 (GGML / IQ formats also at
|
||||
PP=1). A quantized base model also needs a weight format it records in the quantization
|
||||
metadata; the separate EAGLE draft export doesn't. For example, it has no rules for
|
||||
Gemma3-VL, and writes no quantization metadata when only KV-cache quantizers are enabled.
|
||||
|
||||
Neither path exports these:
|
||||
|
||||
* Medusa heads: Megatron-Bridge won't add them, and this function fails for a Medusa model
|
||||
with ``export_extra_modules=True``.
|
||||
* Uniform INT8 weight-only checkpoints: Megatron-Bridge can't pack INT8 weight-only
|
||||
layers, and this function writes no quantization metadata for such a checkpoint.
|
||||
"""
|
||||
warnings.warn(
|
||||
"export_mcore_gpt_to_hf is deprecated as of 0.50.0 and planned for removal in 0.51.0. "
|
||||
"Where it supports the checkpoint, export with Megatron-Bridge's "
|
||||
"AutoBridge.save_hf_pretrained_modelopt instead; see this function's docstring for what "
|
||||
"it doesn't export (e.g. GGML / IQ formats, EAGLE and Medusa modules).",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
exporter = GPTModelExporter(
|
||||
model,
|
||||
pretrained_model_name_or_path,
|
||||
|
||||
@@ -307,7 +307,7 @@ def _attn_fwd(
|
||||
DENSE_SINK_TOKENS: tl.constexpr = 0, # Leading KV tokens kept dense (attention sinks)
|
||||
DENSE_RECENT_TOKENS: tl.constexpr = 64, # Recent KV tokens kept dense (BLOCK_N-independent)
|
||||
APPLY_SKIP_SOFTMAX: tl.constexpr = False, # Skip KV tiles with negligible scores
|
||||
SKIP_THRESHOLD_LOG2: tl.constexpr = 0.0, # log2(lambda) in the kernel's scaled log2 score space
|
||||
skip_threshold_log2=0.0, # log2(lambda), runtime scalar so per-call thresholds reuse one binary
|
||||
P_QDQ: tl.constexpr = 0, # Fake quant-dequant of softmax P: 0=off, 1=FP8 E4M3, 2=NVFP4
|
||||
p_qdq_scale=1.0, # Per-tensor scale for softmax qdq (runtime scalar; amax/448 or amax/(6*448))
|
||||
V_QDQ: tl.constexpr = 0, # Fake quant-dequant of V: 0=off, 2=NVFP4
|
||||
@@ -441,7 +441,7 @@ def _attn_fwd(
|
||||
row_max,
|
||||
q_pos,
|
||||
seq_len_q,
|
||||
SKIP_THRESHOLD_LOG2,
|
||||
skip_threshold_log2,
|
||||
Sparsity_total,
|
||||
Sparsity_skipped,
|
||||
MEASURE_SPARSITY,
|
||||
@@ -630,7 +630,7 @@ def _attn_bwd_dq(
|
||||
DENSE_SINK_TOKENS: tl.constexpr = 0,
|
||||
DENSE_RECENT_TOKENS: tl.constexpr = 64,
|
||||
APPLY_SKIP_SOFTMAX: tl.constexpr = False,
|
||||
SKIP_THRESHOLD_LOG2: tl.constexpr = 0.0,
|
||||
skip_threshold_log2=0.0,
|
||||
):
|
||||
"""Phase 3 of backward: compute dQ for one Q tile, looping over KV tiles.
|
||||
|
||||
@@ -728,7 +728,7 @@ def _attn_bwd_dq(
|
||||
# max, so this conservatively zeros out at least what forward skipped.
|
||||
if APPLY_SKIP_SOFTMAX:
|
||||
tile_row_max = tl.max(scores, 1)
|
||||
can_skip = tile_row_max < (lse + SKIP_THRESHOLD_LOG2)
|
||||
can_skip = tile_row_max < (lse + skip_threshold_log2)
|
||||
p = tl.where(can_skip[:, None], 0.0, p)
|
||||
|
||||
# dP = dO @ V^T, dS = P * (dP - delta), dQ += dS @ K
|
||||
@@ -783,7 +783,7 @@ def _attn_bwd_dkdv(
|
||||
DENSE_SINK_TOKENS: tl.constexpr = 0,
|
||||
DENSE_RECENT_TOKENS: tl.constexpr = 64,
|
||||
APPLY_SKIP_SOFTMAX: tl.constexpr = False,
|
||||
SKIP_THRESHOLD_LOG2: tl.constexpr = 0.0,
|
||||
skip_threshold_log2=0.0,
|
||||
):
|
||||
"""Phase 2 of backward: compute dK, dV for one KV tile.
|
||||
|
||||
@@ -884,7 +884,7 @@ def _attn_bwd_dkdv(
|
||||
# max, so this conservatively zeros out at least what forward skipped.
|
||||
if APPLY_SKIP_SOFTMAX:
|
||||
tile_row_max = tl.max(scores, 1)
|
||||
can_skip = tile_row_max < (lse + SKIP_THRESHOLD_LOG2)
|
||||
can_skip = tile_row_max < (lse + skip_threshold_log2)
|
||||
p = tl.where(can_skip[:, None], 0.0, p)
|
||||
|
||||
# dV += P^T @ dO
|
||||
@@ -1041,7 +1041,7 @@ class _Attention(torch.autograd.Function):
|
||||
"DENSE_SINK_TOKENS": dense_sink_tokens,
|
||||
"DENSE_RECENT_TOKENS": dense_recent_tokens,
|
||||
"APPLY_SKIP_SOFTMAX": apply_skip,
|
||||
"SKIP_THRESHOLD_LOG2": skip_threshold_log2,
|
||||
"skip_threshold_log2": skip_threshold_log2,
|
||||
"P_QDQ": p_qdq_mode,
|
||||
"p_qdq_scale": p_qdq_scale,
|
||||
"V_QDQ": v_qdq_mode,
|
||||
@@ -1229,7 +1229,7 @@ class _Attention(torch.autograd.Function):
|
||||
DENSE_SINK_TOKENS=ctx.dense_sink_tokens,
|
||||
DENSE_RECENT_TOKENS=ctx.dense_recent_tokens,
|
||||
APPLY_SKIP_SOFTMAX=ctx.apply_skip,
|
||||
SKIP_THRESHOLD_LOG2=ctx.skip_threshold_log2,
|
||||
skip_threshold_log2=ctx.skip_threshold_log2,
|
||||
num_warps=num_warps,
|
||||
num_stages=1,
|
||||
)
|
||||
@@ -1255,7 +1255,7 @@ class _Attention(torch.autograd.Function):
|
||||
DENSE_SINK_TOKENS=ctx.dense_sink_tokens,
|
||||
DENSE_RECENT_TOKENS=ctx.dense_recent_tokens,
|
||||
APPLY_SKIP_SOFTMAX=ctx.apply_skip,
|
||||
SKIP_THRESHOLD_LOG2=ctx.skip_threshold_log2,
|
||||
skip_threshold_log2=ctx.skip_threshold_log2,
|
||||
num_warps=num_warps,
|
||||
num_stages=1,
|
||||
)
|
||||
|
||||
@@ -144,7 +144,7 @@ def _skip_softmax_decision(
|
||||
row_max,
|
||||
q_pos,
|
||||
seq_len_q,
|
||||
SKIP_THRESHOLD_LOG2: tl.constexpr,
|
||||
skip_threshold_log2,
|
||||
Sparsity_total,
|
||||
Sparsity_skipped,
|
||||
MEASURE_SPARSITY: tl.constexpr,
|
||||
@@ -178,7 +178,7 @@ def _skip_softmax_decision(
|
||||
tile_row_max = tl.max(scores, 1) # [BLOCK_M] — ~m_i^(j) (scaled)
|
||||
# Per-row: True if the row's tile max is negligible vs running max, OR the
|
||||
# row is padding (q_pos >= seq_len_q) so it must not veto the tile decision.
|
||||
can_skip = (tile_row_max < (row_max + SKIP_THRESHOLD_LOG2)) | (q_pos >= seq_len_q)
|
||||
can_skip = (tile_row_max < (row_max + skip_threshold_log2)) | (q_pos >= seq_len_q)
|
||||
# Per-tile: skip entire tile only if ALL valid rows are negligible
|
||||
skip_tile = tl.min(can_skip.to(tl.int32)) == 1
|
||||
|
||||
|
||||
@@ -93,8 +93,8 @@ def is_routed_moe_module_name(name: str) -> bool:
|
||||
return "shared_expert" not in name and _ROUTED_MOE_EXPERT_NAME_RE.search(name) is not None
|
||||
|
||||
|
||||
def _get_module_weight_numel(module: nn.Module) -> int:
|
||||
"""Return the parameter count for a module's quantizable weights.
|
||||
def _get_module_weights(module: nn.Module) -> list[nn.Parameter]:
|
||||
"""Return a module's quantizable weights, the tensors AutoQuantize's cost counts.
|
||||
|
||||
Standard quantized linear modules have a single ``weight`` parameter. Fused
|
||||
MoE expert containers expose projection tensors directly instead, so both
|
||||
@@ -102,15 +102,16 @@ def _get_module_weight_numel(module: nn.Module) -> int:
|
||||
"""
|
||||
weight = getattr(module, "weight", None)
|
||||
if weight is not None:
|
||||
return weight.numel()
|
||||
return [weight]
|
||||
|
||||
# Fused MoE expert containers expose projection tensors directly instead of
|
||||
# a single ``weight`` parameter.
|
||||
return sum(
|
||||
param.numel()
|
||||
for attr in ("gate_up_proj", "down_proj")
|
||||
# a single ``weight`` parameter. Non-gated experts name the
|
||||
# first projection ``up_proj``; leaving it out counts only half the experts.
|
||||
return [
|
||||
param
|
||||
for attr in ("gate_up_proj", "up_proj", "down_proj")
|
||||
if (param := getattr(module, attr, None)) is not None
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
class AutoQuantizeCostModel:
|
||||
|
||||
@@ -444,10 +444,12 @@ class AutoQuantizeAumannShapleySearcher(_AutoQuantizeBackwardScoringSearcher):
|
||||
)
|
||||
return config
|
||||
|
||||
def validate_search_input(self, constraints, config) -> None:
|
||||
def validate_search_input(
|
||||
self, constraints, config, model: torch.nn.Module | None = None
|
||||
) -> None:
|
||||
"""Reject ambiguous target combinations (runs before any model mutation)."""
|
||||
self._check_targets(constraints, config)
|
||||
super().validate_search_input(constraints, config)
|
||||
super().validate_search_input(constraints, config, model)
|
||||
|
||||
@staticmethod
|
||||
def _check_targets(constraints, config) -> None:
|
||||
|
||||
@@ -19,7 +19,12 @@ import copy
|
||||
import fnmatch
|
||||
import functools
|
||||
import gc
|
||||
import hashlib
|
||||
import numbers
|
||||
import os
|
||||
import stat
|
||||
import types
|
||||
import uuid
|
||||
import warnings
|
||||
from abc import ABC, abstractmethod
|
||||
from collections import defaultdict
|
||||
@@ -38,15 +43,23 @@ from modelopt.torch.opt.conversion import ModeloptStateManager
|
||||
from modelopt.torch.opt.hparam import CustomHPType, Hparam, HPType
|
||||
from modelopt.torch.opt.searcher import LPS, BaseSearcher, SearchConfig, SearchStateDict
|
||||
from modelopt.torch.opt.utils import get_hparam, named_hparams
|
||||
from modelopt.torch.utils import create_param_grad_clear_hook, print_rank_0, report_memory
|
||||
from modelopt.torch.utils import (
|
||||
create_param_grad_clear_hook,
|
||||
print_rank_0,
|
||||
report_memory,
|
||||
safe_save,
|
||||
)
|
||||
from modelopt.torch.utils.distributed import (
|
||||
DistributedProcessGroup,
|
||||
ParallelState,
|
||||
all_reduce,
|
||||
broadcast_from,
|
||||
fail_together,
|
||||
is_distributed_run,
|
||||
is_fsdp2_model,
|
||||
is_master,
|
||||
rank,
|
||||
recorded_distribution_plan,
|
||||
)
|
||||
|
||||
from . import config as mtq_config
|
||||
@@ -56,7 +69,7 @@ from ._auto_quantize_cost import (
|
||||
AUTO_QUANTIZE_CONSTRAINT_KEYS,
|
||||
COST_MODEL_ACTIVE_MOE,
|
||||
COST_MODEL_WEIGHT,
|
||||
_get_module_weight_numel,
|
||||
_get_module_weights,
|
||||
get_auto_quantize_cost_model,
|
||||
normalize_auto_quantize_constraints,
|
||||
)
|
||||
@@ -66,6 +79,7 @@ from .ggml import GGML_FORMAT_REGISTRY
|
||||
from .ggml.common import PIN_OVERRIDES_WEIGHT, drop_search_scales
|
||||
from .nn import QuantLinearConvBase, QuantModule, SequentialQuantizer, TensorQuantizer
|
||||
from .utils import is_quantized_linear
|
||||
from .utils.core_utils import _fsdp2_sharded_alone, _group_ranks
|
||||
|
||||
|
||||
def _is_hf_quant_fused_experts_module(module: nn.Module) -> bool:
|
||||
@@ -873,6 +887,120 @@ def _quantization_formats_signature(quant_recipes) -> tuple[str, ...]:
|
||||
return tuple(sorted(recipe.checkpoint_signature for recipe in quant_recipes))
|
||||
|
||||
|
||||
def _comparable(value: Any) -> Any:
|
||||
"""``value`` as lists, strings and integers, a dict as its ordered items and a float as its text.
|
||||
|
||||
So the digest of its ``repr`` that ranks compare on resume covers every value they restored,
|
||||
order included, where a tensor's own ``repr`` would elide most of them.
|
||||
"""
|
||||
if isinstance(value, torch.Tensor):
|
||||
value = value.tolist()
|
||||
if isinstance(value, QuantRecipe):
|
||||
return value.checkpoint_signature
|
||||
if isinstance(value, dict):
|
||||
return [[_comparable(key), _comparable(item)] for key, item in value.items()]
|
||||
if isinstance(value, (list, tuple)):
|
||||
return [_comparable(item) for item in value]
|
||||
if isinstance(value, (set, frozenset)):
|
||||
return sorted((_comparable(item) for item in value), key=repr)
|
||||
if value is None or isinstance(value, (bool, str)):
|
||||
return value
|
||||
if isinstance(value, numbers.Integral):
|
||||
return int(value)
|
||||
if isinstance(value, numbers.Real):
|
||||
return repr(float(value))
|
||||
return repr(value)
|
||||
|
||||
|
||||
def _parallel_groups(parallel_state: ParallelState) -> dict[str, DistributedProcessGroup]:
|
||||
return {
|
||||
"tp": parallel_state.tensor_parallel_group,
|
||||
"ep": parallel_state.expert_model_parallel_group,
|
||||
"dp": parallel_state.data_parallel_group,
|
||||
}
|
||||
|
||||
|
||||
def _parallel_layout(
|
||||
hparams: Sequence["QuantRecipeHparam"], module_names: dict[int, str], fsdp2_alone: set[int]
|
||||
) -> tuple:
|
||||
"""Each searched module's tensor-, expert- and data-parallel groups, by their ranks in order.
|
||||
|
||||
Also the mesh and placements of each counted weight that is a DTensor tensor or expert
|
||||
parallelism shards, as the same groups can shard a weight along another dim. FSDP2 calibrates
|
||||
the weights it alone shards, by id in ``fsdp2_alone``, whole, so their placements are left out.
|
||||
With the rank that wrote it, a file's layout tells which shard of each module's weights its
|
||||
calibration is of. A group or mesh of one rank shards nothing and is left out, so a search in
|
||||
one process under a one-rank process group, as a single-GPU FSDP2 load runs, matches one
|
||||
without. Sorted by module name, so a model that registers the same modules in another order,
|
||||
such as ``k_proj`` before ``q_proj``, matches too.
|
||||
"""
|
||||
layout = []
|
||||
for hparam in hparams:
|
||||
for module in hparam.quant_modules:
|
||||
state = getattr(module, "parallel_state", None)
|
||||
groups = tuple(
|
||||
(kind, tuple(_group_ranks(group)))
|
||||
for kind, group in (_parallel_groups(state).items() if state is not None else ())
|
||||
if group.is_initialized() and group.world_size() > 1
|
||||
)
|
||||
weights = tuple(
|
||||
(
|
||||
tuple(weight.device_mesh.mesh.shape),
|
||||
tuple(weight.device_mesh.mesh.flatten().tolist()),
|
||||
tuple(map(repr, weight.placements)),
|
||||
)
|
||||
if isinstance(weight, DTensor)
|
||||
and weight.device_mesh.size() > 1
|
||||
and id(weight) not in fsdp2_alone
|
||||
else None
|
||||
for weight in (
|
||||
_get_module_weights(module)
|
||||
if _AutoQuantizeBaseSearcher._is_auto_quantize_module(module)
|
||||
else []
|
||||
)
|
||||
)
|
||||
name = module_names.get(id(module))
|
||||
# The weights' entries only where one has a placement to record.
|
||||
layout.append((name, groups, weights) if any(weights) else (name, groups))
|
||||
return tuple(sorted(layout, key=lambda entry: str(entry[0])))
|
||||
|
||||
|
||||
def _save_together(searcher: BaseSearcher, verbose: bool, label: str) -> None:
|
||||
"""Save each rank's checkpoint file; a write failing on any rank leaves every rank's old one.
|
||||
|
||||
Each rank writes beside its file in one collective, and renames it over the file in another
|
||||
once every rank has written: a write failing on one rank, e.g. on a full disk, would otherwise
|
||||
leave the others' files a save ahead of its own. A rename failing on one rank, or a job stopped
|
||||
between the renames, can still leave the files a save apart; every rank then refuses to resume
|
||||
them (``_resume_together``).
|
||||
"""
|
||||
path = searcher._get_checkpoint_path()
|
||||
if path is None: # on every rank alike: every rank checkpoints or none does
|
||||
return
|
||||
staged = f"{path}.{uuid.uuid4().hex}.saving"
|
||||
created = False
|
||||
try:
|
||||
with fail_together(label):
|
||||
if verbose:
|
||||
print(f"Saving searcher state to {path}...")
|
||||
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
||||
# A new file of its own: a name another user could have linked elsewhere would write
|
||||
# through the link. The rename then replaces any link at the path, never follows it.
|
||||
with open(staged, "xb") as f:
|
||||
created = True
|
||||
# A re-save keeps its mode.
|
||||
if os.path.isfile(path) and not os.path.islink(path):
|
||||
os.chmod(staged, stat.S_IMODE(os.stat(path).st_mode))
|
||||
safe_save(searcher.state_dict(), f)
|
||||
with fail_together(f"{label} (rename)"):
|
||||
os.replace(staged, path)
|
||||
except BaseException:
|
||||
# Only the file this save created: a name the exclusive open found taken is another's.
|
||||
if created and os.path.exists(staged):
|
||||
os.remove(staged)
|
||||
raise
|
||||
|
||||
|
||||
_NO_BATCH = object()
|
||||
|
||||
|
||||
@@ -913,6 +1041,59 @@ def _lockstep_batches(
|
||||
yield batch
|
||||
|
||||
|
||||
def _calibration_digest(quantizer_states: dict) -> str:
|
||||
"""A digest of restored calibration: every format's quantizer states and tensors, by name."""
|
||||
digest = hashlib.sha256()
|
||||
|
||||
def update(path: str, value: Any) -> None:
|
||||
if isinstance(value, dict):
|
||||
for key in sorted(value, key=str):
|
||||
update(f"{path}/{key}", value[key])
|
||||
elif isinstance(value, (list, tuple)):
|
||||
digest.update(f"{path}:{len(value)}".encode())
|
||||
for index, item in enumerate(value):
|
||||
update(f"{path}[{index}]", item)
|
||||
elif isinstance(value, torch.Tensor):
|
||||
# Its dtype and shape too: the same bytes hold other values in another.
|
||||
digest.update(f"{path}:{value.dtype}{tuple(value.shape)}".encode())
|
||||
value = value.detach().contiguous().cpu().reshape(-1).view(torch.uint8)
|
||||
digest.update(value.numpy().tobytes())
|
||||
else:
|
||||
digest.update(f"{path}={value!r}".encode())
|
||||
|
||||
for recipe in sorted(quantizer_states, key=lambda r: r.checkpoint_signature):
|
||||
# The state restore_quantizer_state rebuilds each quantizer from, and its tensors.
|
||||
update(str(recipe.checkpoint_signature), quantizer_states[recipe])
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _plan_signature(model: nn.Module) -> tuple | None:
|
||||
"""The world size, expert-parallel degree and dense layout of ``model``'s recorded plan."""
|
||||
plan = recorded_distribution_plan(model)
|
||||
return None if plan is None else (plan.world_size, plan.ep_size, plan.dense)
|
||||
|
||||
|
||||
# Whose and which run's calibration a file holds, and of which shards: a file this release writes
|
||||
# records all of it, and a file written before records none.
|
||||
_PROVENANCE = ("checkpoint_rank", "checkpoint_world_size", "parallel_layout", "search_id")
|
||||
|
||||
|
||||
def _missing_provenance(state: dict) -> list[str]:
|
||||
"""The provenance ``state`` lacks, if it records only part of it."""
|
||||
missing = [key for key in _PROVENANCE if state.get(key) is None]
|
||||
return [] if len(missing) == len(_PROVENANCE) else missing
|
||||
|
||||
|
||||
def _resume_together(progresses: list) -> None:
|
||||
if any(restored != progresses[0] for restored in progresses):
|
||||
raise ValueError(
|
||||
"Distributed AutoQuantize requires every rank's checkpoint at the same progress, every "
|
||||
"rank searching the same layers (pipeline-parallel stages, which do not, resume from a "
|
||||
"new checkpoint path). Restore all rank files from the same search, or use a new "
|
||||
"checkpoint path on every rank."
|
||||
)
|
||||
|
||||
|
||||
class _AutoQuantizeBaseSearcher(BaseSearcher, ABC):
|
||||
"""Base searcher for AutoQuantize algorithm."""
|
||||
|
||||
@@ -993,6 +1174,16 @@ class _AutoQuantizeBaseSearcher(BaseSearcher, ABC):
|
||||
"num_calib_steps": None,
|
||||
"num_score_steps": None,
|
||||
"scoring_config": {},
|
||||
# The rank, world size and distribution plan that wrote the checkpoint: its quantizer
|
||||
# states are that rank's own, an expert-parallel rank's those of its own experts.
|
||||
"checkpoint_rank": None,
|
||||
"checkpoint_world_size": None,
|
||||
"distribution_plan": None,
|
||||
# The parallel groups the writer's searched modules span, by their ranks in order, which
|
||||
# also bind a model with no plan recorded, such as Megatron's.
|
||||
"parallel_layout": None,
|
||||
# Common to the files of every rank of one search, which calibrated and scored together.
|
||||
"search_id": None,
|
||||
"best": {"recipe": {}, "constraints": {}, "score": float("inf"), "is_satisfied": False},
|
||||
}
|
||||
|
||||
@@ -1040,7 +1231,7 @@ class _AutoQuantizeBaseSearcher(BaseSearcher, ABC):
|
||||
config["format_shard"] = (index, count)
|
||||
return config
|
||||
|
||||
def validate_search_input(self, constraints, config) -> None:
|
||||
def validate_search_input(self, constraints, config, model: nn.Module | None = None) -> None:
|
||||
"""Validate method-specific inputs before quantizing the model."""
|
||||
# Refuse scores of another method or scoring options before the model is converted, so the
|
||||
# caller can retry the same model with another checkpoint. The search restores the state
|
||||
@@ -1048,7 +1239,84 @@ class _AutoQuantizeBaseSearcher(BaseSearcher, ABC):
|
||||
self.config = config
|
||||
self._preloaded_state = None
|
||||
self.reset_search()
|
||||
loaded = self.load_search_checkpoint()
|
||||
loaded = False
|
||||
|
||||
def resume_point():
|
||||
nonlocal loaded
|
||||
loaded = self.load_search_checkpoint()
|
||||
state = self.state_dict()
|
||||
# A file this release wrote records all of its provenance and an older one none: one
|
||||
# recording part of it, as no search writes, cannot show whose and which run's
|
||||
# calibration it holds.
|
||||
if (
|
||||
is_distributed_run()
|
||||
and (state["quantizer_states"] or state["candidate_stats"])
|
||||
and (missing := _missing_provenance(state))
|
||||
):
|
||||
raise ValueError(
|
||||
f"Rank {rank()}'s AutoQuantize checkpoint records only part of its provenance, "
|
||||
f"not {', '.join(missing)}. Restore each rank's own file from the same search, "
|
||||
"or use a new checkpoint path."
|
||||
)
|
||||
# On several ranks, a file another rank wrote holds other quantizer states, such as
|
||||
# other experts'.
|
||||
if is_distributed_run() and state["checkpoint_rank"] not in (None, rank()):
|
||||
raise ValueError(
|
||||
f"Rank {rank()}'s AutoQuantize checkpoint was written by rank "
|
||||
f"{state['checkpoint_rank']}. Restore each rank's own file from the same "
|
||||
"search, or use a new checkpoint path."
|
||||
)
|
||||
# A run of another size wrote its files for its own ranks, e.g. their own experts, plan
|
||||
# or none (Megatron's); one process refuses them too. Older files, unrecorded, resume.
|
||||
world_size = torch.distributed.get_world_size() if is_distributed_run() else 1
|
||||
if (state["quantizer_states"] or state["candidate_stats"]) and state[
|
||||
"checkpoint_world_size"
|
||||
] not in (None, world_size):
|
||||
raise ValueError(
|
||||
"The AutoQuantize checkpoint was written by a run of "
|
||||
f"{state['checkpoint_world_size']} ranks, not {world_size}. Resume with the "
|
||||
"same world size, or use a new checkpoint path. To re-solve its scores in one "
|
||||
"process, pass its search state and constraints to get_auto_quantize_config(), "
|
||||
"e.g. get_auto_quantize_config(state, {'effective_bits': 4.8})."
|
||||
)
|
||||
# Another plan, or none, gives a rank other experts, or another share of the dense part.
|
||||
# Older files, recording no world size, record no plan either and resume.
|
||||
plan = None if model is None else _plan_signature(model)
|
||||
recorded = state["distribution_plan"]
|
||||
if (
|
||||
is_distributed_run()
|
||||
and model is not None
|
||||
and (state["quantizer_states"] or state["candidate_stats"])
|
||||
and recorded != plan
|
||||
and (recorded is not None or state["checkpoint_world_size"] is not None)
|
||||
):
|
||||
raise ValueError(
|
||||
"The AutoQuantize checkpoint was written under (world size, expert-parallel "
|
||||
f"degree, dense layout) {recorded}, not {plan}. Resume "
|
||||
"with the same ones, or use a new checkpoint path."
|
||||
)
|
||||
# Everything restored but the solved result and what is each rank's own (its rank,
|
||||
# groups and calibrations, by format), as a digest: compared only for equality.
|
||||
restored = _comparable(
|
||||
{
|
||||
**{
|
||||
key: value
|
||||
for key, value in state.items()
|
||||
if key not in ("best", "checkpoint_rank", "parallel_layout")
|
||||
},
|
||||
"quantizer_states": sorted(
|
||||
r.checkpoint_signature for r in state["quantizer_states"]
|
||||
),
|
||||
}
|
||||
)
|
||||
return hashlib.sha256(repr(restored).encode()).hexdigest()
|
||||
|
||||
if is_distributed_run():
|
||||
# In one collective, so a file failing to load, or a rank at another point (every rank
|
||||
# searches the same layers), makes every rank raise first.
|
||||
all_reduce("AutoQuantize checkpoint", resume_point, _resume_together)
|
||||
else:
|
||||
resume_point()
|
||||
state = self.state_dict()
|
||||
self._preloaded_state = state if loaded else {}
|
||||
if not state["candidate_stats"]:
|
||||
@@ -1072,6 +1340,12 @@ class _AutoQuantizeBaseSearcher(BaseSearcher, ABC):
|
||||
self.candidate_stats = defaultdict(dict, self.candidate_stats)
|
||||
return loaded
|
||||
|
||||
def save_search_checkpoint(self, verbose=False) -> None:
|
||||
if is_distributed_run():
|
||||
_save_together(self, verbose, "AutoQuantize checkpoint save")
|
||||
else:
|
||||
super().save_search_checkpoint(verbose)
|
||||
|
||||
@staticmethod
|
||||
def _is_auto_quantize_module(module):
|
||||
if (is_quantized_linear(module) or isinstance(module, QuantLinearConvBase)) and isinstance(
|
||||
@@ -1426,11 +1700,20 @@ class _AutoQuantizeBaseSearcher(BaseSearcher, ABC):
|
||||
def _verify_resolved_constraint(self, quant_recipe_hparams) -> None:
|
||||
"""Fail before calibration when resolved per-group choices cannot meet the budget."""
|
||||
no_quant_recipe = QuantRecipe(quant_cfg=None)
|
||||
uncompressed_cost = sum(hparam.get_cost(no_quant_recipe) for hparam in quant_recipe_hparams)
|
||||
minimum_cost = sum(
|
||||
min(hparam.get_cost(recipe) for recipe in hparam.solver_choices)
|
||||
# Price every live group and choice once, in the live order every rank shares (get_cost
|
||||
# syncs over parallel groups); a resumed search reprices its saved rows from these.
|
||||
self._live_prices = {
|
||||
id(hparam): (
|
||||
hparam.get_cost(no_quant_recipe),
|
||||
{
|
||||
recipe.checkpoint_signature: hparam.get_cost(recipe)
|
||||
for recipe in hparam.solver_choices
|
||||
},
|
||||
)
|
||||
for hparam in quant_recipe_hparams
|
||||
)
|
||||
}
|
||||
uncompressed_cost = sum(prices[0] for prices in self._live_prices.values())
|
||||
minimum_cost = sum(min(prices[1].values()) for prices in self._live_prices.values())
|
||||
|
||||
# The costs are summed over every group the ranks share but not over pipeline stages, whose
|
||||
# budgets are their own: a stage refusing its budget alone would leave the others waiting.
|
||||
@@ -1482,6 +1765,44 @@ class _AutoQuantizeBaseSearcher(BaseSearcher, ABC):
|
||||
# Keep the no-quant cost as denominator metadata even when no-quant is not
|
||||
# solver-selectable for this hparam. Fixed formats must remain in the cost model.
|
||||
self.candidate_stats[name]["uncompressed_cost"] = hparam.get_cost(no_quant_recipe)
|
||||
# The group's (cost-weighted) weight size as this cost model counts it. Searches saved
|
||||
# before it was recorded may count fused experts short; see _warn_on_unsized_costs.
|
||||
self.candidate_stats[name]["weight_size"] = self.candidate_stats[name][
|
||||
"uncompressed_cost"
|
||||
]
|
||||
|
||||
def _refresh_candidate_costs(self) -> bool:
|
||||
"""Reprice restored candidates with the live prices, keeping their scores.
|
||||
|
||||
Costs depend only on the weights and formats, so a resumed search uses the prices
|
||||
_verify_resolved_constraint() took from the model rather than costs an older cost model
|
||||
may have saved. It issues no collectives of its own: saved rows and formats, which may be
|
||||
ordered differently on each rank, only look prices up. Returns whether any cost changed.
|
||||
"""
|
||||
changed = False
|
||||
# Every saved group, looked up by its saved name as run_search() does: a shared group's
|
||||
# first registered member may differ on resume.
|
||||
for name, stats in self.candidate_stats.items():
|
||||
hparam = get_hparam(self.model, name)
|
||||
if not isinstance(hparam, QuantRecipeHparam) or id(hparam) not in self._live_prices:
|
||||
raise ValueError(f"Saved AutoQuantize group {name} is not searched on resume.")
|
||||
uncompressed_cost, prices = self._live_prices[id(hparam)]
|
||||
# Match by config identity, as the resume checks do: a display name may change.
|
||||
costs = [prices[_saved_signature(fmt, hparam)] for fmt in stats["formats"]]
|
||||
if (
|
||||
costs != stats.get("costs")
|
||||
or uncompressed_cost != stats.get("uncompressed_cost")
|
||||
or uncompressed_cost != stats.get("weight_size")
|
||||
):
|
||||
stats["costs"], stats["uncompressed_cost"] = costs, uncompressed_cost
|
||||
stats["weight_size"] = uncompressed_cost
|
||||
changed = True
|
||||
# A solve recomputes the denominator; refresh the restored one too, as it is kept with them.
|
||||
if self.cost_denominator is not None:
|
||||
denominator = self._get_total_weight_size_from_candidate_stats(self.candidate_stats)
|
||||
changed = changed or denominator != self.cost_denominator
|
||||
self.cost_denominator = denominator
|
||||
return changed
|
||||
|
||||
# Whether the ranks step their batches together (_batches), set in before_search.
|
||||
_forwards_synchronize = False
|
||||
@@ -1656,6 +1977,9 @@ class _AutoQuantizeBaseSearcher(BaseSearcher, ABC):
|
||||
mismatch = self.scoring_mismatch(self.state_dict()) if self.candidate_stats else None
|
||||
if mismatch:
|
||||
raise ValueError(f"{mismatch} Use a different checkpoint path.")
|
||||
# validate_search_input refused a checkpoint of another world size or plan.
|
||||
plan = _plan_signature(self.model)
|
||||
world_size = torch.distributed.get_world_size() if is_distributed_run() else 1
|
||||
self.method = self.method_name
|
||||
self.scoring_config = self.scoring_config_from(self.config)
|
||||
self.cost_model = self.config["cost_model"]
|
||||
@@ -1663,7 +1987,18 @@ class _AutoQuantizeBaseSearcher(BaseSearcher, ABC):
|
||||
self.active_moe_expert_ratio = self.config["active_moe_expert_ratio"]
|
||||
self.disabled_layers = self.config["disabled_layers"]
|
||||
self.cost_denominator = getattr(self, "cost_denominator", None)
|
||||
self.checkpoint_rank = rank()
|
||||
self._forwards_synchronize = is_distributed_run() and is_fsdp2_model(self.model)
|
||||
self.checkpoint_world_size = world_size
|
||||
self.distribution_plan = plan
|
||||
# Rank and plan say whose shard a file holds, not which run wrote it: a resume keeps the ID
|
||||
# every rank restored alike, and a new search, or files saved without one, takes rank 0's.
|
||||
if self.search_id is None:
|
||||
self.search_id = (
|
||||
broadcast_from("AutoQuantize search ID", lambda: uuid.uuid4().hex)
|
||||
if is_distributed_run()
|
||||
else uuid.uuid4().hex
|
||||
)
|
||||
|
||||
module_search_spaces = self._normalize_module_search_spaces(
|
||||
self.config["module_search_spaces"]
|
||||
@@ -1699,6 +2034,7 @@ class _AutoQuantizeBaseSearcher(BaseSearcher, ABC):
|
||||
)
|
||||
self._verify_constraint(search_recipes)
|
||||
self._cost_model = cost_model
|
||||
restored_parallel_layout = getattr(self, "parallel_layout", None)
|
||||
# A rank refusing its search groups alone, e.g. by a rule for a group only its pipeline
|
||||
# stage holds, or refusing its own checkpoint, would leave the others in the next cost sum.
|
||||
with fail_together("AutoQuantize search groups"):
|
||||
@@ -1718,6 +2054,10 @@ class _AutoQuantizeBaseSearcher(BaseSearcher, ABC):
|
||||
resolved_search_setup_signature = self._resolved_search_setup_signature(
|
||||
quant_recipe_hparams
|
||||
)
|
||||
module_names = {id(module): name for name, module in self.model.named_modules()}
|
||||
parallel_layout = _parallel_layout(
|
||||
quant_recipe_hparams, module_names, _fsdp2_sharded_alone(self.model)
|
||||
)
|
||||
restored_resolved_search_setup_signature = getattr(
|
||||
self, "resolved_search_setup_signature", None
|
||||
)
|
||||
@@ -1738,7 +2078,56 @@ class _AutoQuantizeBaseSearcher(BaseSearcher, ABC):
|
||||
"allowed choices, scoring boundaries, or cost weights. Use a different "
|
||||
"checkpoint path."
|
||||
)
|
||||
# A file that records no layout, as those written before it was recorded, cannot show it
|
||||
# holds this rank's calibration: under tensor or expert parallelism each rank calibrates
|
||||
# its own shards, which another rank's file would restore unnoticed, also those of a
|
||||
# weight the layout records a placement of where no parallel state names its groups.
|
||||
if (
|
||||
restored_parallel_layout is None
|
||||
and self.quantizer_states
|
||||
and any(
|
||||
weights or any(kind != "dp" and len(ranks) > 1 for kind, ranks in groups)
|
||||
for _, groups, *weights in parallel_layout
|
||||
)
|
||||
):
|
||||
raise ValueError(
|
||||
"The AutoQuantize checkpoint records no parallel layout, as files written "
|
||||
"before ModelOpt 0.50 do not, so this rank cannot verify it holds the "
|
||||
"calibration of its own tensor- or expert-parallel shards. Use a new "
|
||||
"checkpoint path, or re-solve its scores with get_auto_quantize_config()."
|
||||
)
|
||||
# This rank's own file against this rank's own groups and shards.
|
||||
if has_restored_calibration_or_scores and restored_parallel_layout not in (
|
||||
None,
|
||||
parallel_layout,
|
||||
):
|
||||
raise ValueError(
|
||||
"The AutoQuantize checkpoint was written for other parallel groups or weight "
|
||||
"shards than this rank's. Resume with the same tensor-, expert- and "
|
||||
"data-parallel groups and weight placements, or use a new checkpoint path."
|
||||
)
|
||||
if is_distributed_run():
|
||||
# A file that records no run (written before it was recorded) proves its calibration one
|
||||
# run's only by matching its peers': data-parallel replicas calibrate alike, and the
|
||||
# checks above refused such files under TP or EP.
|
||||
legacy = restored_parallel_layout is None and bool(self.quantizer_states)
|
||||
|
||||
def refuse_unlike(calibrations: list) -> None:
|
||||
if len(set(calibrations)) > 1:
|
||||
raise ValueError(
|
||||
"The ranks' AutoQuantize checkpoints record no run, as files written "
|
||||
"before ModelOpt 0.50 do not, and hold other calibrations: they come from "
|
||||
"different runs. Resume every rank from the same run's files, or use a new "
|
||||
"checkpoint path."
|
||||
)
|
||||
|
||||
all_reduce(
|
||||
"AutoQuantize checkpoint calibrations",
|
||||
lambda: _calibration_digest(self.quantizer_states) if legacy else None,
|
||||
refuse_unlike,
|
||||
)
|
||||
self.resolved_search_setup_signature = resolved_search_setup_signature
|
||||
self.parallel_layout = parallel_layout
|
||||
self._verify_resolved_constraint(quant_recipe_hparams)
|
||||
|
||||
format_shard = self.config["format_shard"]
|
||||
@@ -1777,8 +2166,6 @@ class _AutoQuantizeBaseSearcher(BaseSearcher, ABC):
|
||||
source_weights = self._snapshot_source_weights(
|
||||
quant_recipe_hparams, calibration_recipes
|
||||
)
|
||||
# Free the weights conversion replaced before calibration and scoring.
|
||||
self.restore_unconverted = None
|
||||
QuantRecipe.disable_folding_pqs_to_weights()
|
||||
|
||||
# Iterate over the search recipes and calibrate the quantizers for each recipe
|
||||
@@ -1793,17 +2180,36 @@ class _AutoQuantizeBaseSearcher(BaseSearcher, ABC):
|
||||
|
||||
if recipe in self.quantizer_states:
|
||||
saved = self.quantizer_states[recipe]
|
||||
# config is unused by restore_quantizer_state
|
||||
restore_quantizer_state(
|
||||
self.model, QuantizeConfig(), {"quantizer_state": saved["metadata"]}
|
||||
)
|
||||
set_quantizer_state_dict(self.model, saved["state_dict"])
|
||||
# Each rank restores its own file, which no other rank compares (e.g. its
|
||||
# experts'): one not fitting its quantizers fails every rank, not it alone.
|
||||
with fail_together("AutoQuantize restored calibration"):
|
||||
# config is unused by restore_quantizer_state
|
||||
restore_quantizer_state(
|
||||
self.model, QuantizeConfig(), {"quantizer_state": saved["metadata"]}
|
||||
)
|
||||
# A quantizer the file holds no tensors for would keep the empty buffers
|
||||
# restore_quantizer_state allocated it.
|
||||
if missing := sorted(
|
||||
name
|
||||
for name, tensors in get_quantizer_state_dict(self.model).items()
|
||||
if tensors and name not in saved["state_dict"]
|
||||
):
|
||||
raise ValueError(
|
||||
f"The AutoQuantize checkpoint holds no tensors for {len(missing)} "
|
||||
f"quantizers of {recipe}, such as {missing[0]}. Use a new "
|
||||
"checkpoint path."
|
||||
)
|
||||
set_quantizer_state_dict(self.model, saved["state_dict"])
|
||||
if _rewrites_weights(recipe):
|
||||
self._replay_pinned_codes(quant_recipe_hparams)
|
||||
if self.config["verbose"]:
|
||||
print_rank_0(f"AutoQuantize: Restored calibration for {recipe}")
|
||||
continue
|
||||
|
||||
# Free the weights conversion replaced before calibrating, as before scoring.
|
||||
# Restoring a file's calibration, above, changes no weights, nor does replaying its
|
||||
# codes: a refusal of a later payload still hands the unconverted model back.
|
||||
self.restore_unconverted = None
|
||||
# Lets reduce the number of calibration steps for AWQ since it takes longer
|
||||
num_calib_steps = (
|
||||
self.config["num_calib_steps"]
|
||||
@@ -1851,6 +2257,7 @@ class _AutoQuantizeBaseSearcher(BaseSearcher, ABC):
|
||||
hparam.restore_active_quantizers()
|
||||
# Host memory the size of the rewritten weights; scoring does not read it.
|
||||
del source_weights
|
||||
self.restore_unconverted = None
|
||||
|
||||
if calibrated_new:
|
||||
self.save_search_checkpoint(verbose=self.config["verbose"])
|
||||
@@ -1858,6 +2265,12 @@ class _AutoQuantizeBaseSearcher(BaseSearcher, ABC):
|
||||
if self.candidate_stats:
|
||||
if self.config["verbose"]:
|
||||
print_rank_0("AutoQuantize: Restored from checkpoint, skipping scoring")
|
||||
# Solve with costs from the model, not the saved ones, which an older cost model may
|
||||
# have computed. The resume does not save the checkpoint: it may be read-only, and its
|
||||
# saved best recipe matches its saved costs (a method that saves after solving, such as
|
||||
# aumann_shapley, then saves the repriced state with its new best recipe).
|
||||
if self._refresh_candidate_costs() and self.config["verbose"]:
|
||||
print_rank_0("AutoQuantize: Recomputed the checkpoint's candidate costs")
|
||||
return
|
||||
|
||||
self.estimate_sensitivity_scores()
|
||||
@@ -1875,7 +2288,7 @@ class _AutoQuantizeBaseSearcher(BaseSearcher, ABC):
|
||||
@staticmethod
|
||||
def _get_total_weight_size(modules):
|
||||
return sum(
|
||||
_get_module_weight_numel(module)
|
||||
sum(weight.numel() for weight in _get_module_weights(module))
|
||||
if _AutoQuantizeBaseSearcher._is_auto_quantize_module(module)
|
||||
else 0
|
||||
for module in modules
|
||||
@@ -2053,9 +2466,44 @@ _SHARD_INVARIANT_STATE = (
|
||||
"resolved_search_setup_signature",
|
||||
"num_calib_steps",
|
||||
"num_score_steps",
|
||||
# Each rank's shards hold that rank's calibration, e.g. its own experts': merged per rank.
|
||||
"checkpoint_rank",
|
||||
"checkpoint_world_size",
|
||||
"distribution_plan",
|
||||
"parallel_layout",
|
||||
)
|
||||
|
||||
|
||||
def _saved_signature(fmt, hparam) -> str:
|
||||
"""A saved candidate format's config identity; a format saved as its label is looked up by it."""
|
||||
signature = getattr(fmt, "checkpoint_signature", None)
|
||||
if signature is not None:
|
||||
return signature
|
||||
for recipe in hparam.solver_choices:
|
||||
if str(recipe) == str(fmt):
|
||||
return recipe.checkpoint_signature
|
||||
raise ValueError(f"Saved candidate format {fmt} is not searched; start a new checkpoint.")
|
||||
|
||||
|
||||
def _warn_on_unsized_costs(search_state: dict) -> None:
|
||||
"""Warn when a search state predates recorded weight sizes, whose costs may count experts short.
|
||||
|
||||
Only a search on the model can recompute costs: resuming ``auto_quantize`` with the checkpoint
|
||||
solves with recomputed costs, and a new search records the sizes.
|
||||
"""
|
||||
if any("weight_size" not in stats for stats in search_state["candidate_stats"].values()):
|
||||
warnings.warn(
|
||||
"This AutoQuantize search state was saved before weight sizes were recorded; its costs "
|
||||
"may count non-gated fused experts at half size. Resume auto_quantize on the model "
|
||||
"with this checkpoint to solve with recomputed costs, or rerun the search with a new "
|
||||
"checkpoint to re-solve it without the model.",
|
||||
stacklevel=3,
|
||||
)
|
||||
|
||||
|
||||
_COST_KEYS = ("costs", "uncompressed_cost", "weight_size")
|
||||
|
||||
|
||||
def merge_auto_quantize_shards(shard_states: Sequence[dict]) -> dict:
|
||||
"""Combine the states of every format shard of one search into an unsharded search state."""
|
||||
ids = [tuple(state.get("format_shard") or ()) for state in shard_states]
|
||||
@@ -2087,6 +2535,8 @@ def merge_auto_quantize_shards(shard_states: Sequence[dict]) -> dict:
|
||||
target = merged["candidate_stats"][name]
|
||||
if [str(f) for f in stats["formats"]] != [str(f) for f in target["formats"]]:
|
||||
raise ValueError(f"Format shards list different formats for {name}.")
|
||||
if any(stats.get(key) != target.get(key) for key in _COST_KEYS):
|
||||
raise ValueError(f"Format shards hold different costs for {name}.")
|
||||
for i, score in enumerate(stats["raw_scores"]):
|
||||
current = target["raw_scores"][i]
|
||||
if score is None or current == score:
|
||||
@@ -2100,6 +2550,17 @@ def merge_auto_quantize_shards(shard_states: Sequence[dict]) -> dict:
|
||||
if any(score is None for score in stats["raw_scores"]):
|
||||
raise ValueError(f"No format shard scored every format of {name}.")
|
||||
stats["scores"] = _monotone_scores(stats["raw_scores"])
|
||||
# Every shard's run, in shard order: ranks resuming merged files compare it (resume_point), as
|
||||
# equal scores need not mean one run's calibrations. Shards written before runs were recorded
|
||||
# record none of their provenance, and neither does their merge.
|
||||
for index, state in enumerate(shards):
|
||||
if missing := _missing_provenance(state):
|
||||
raise ValueError(
|
||||
f"Format shard {index} records only part of its provenance, not "
|
||||
f"{', '.join(missing)}; rerun it."
|
||||
)
|
||||
runs = [state.get("search_id") for state in shards]
|
||||
merged["search_id"] = None if None in runs else ",".join(map(str, runs))
|
||||
merged["format_shard"] = None
|
||||
merged["best"] = {"recipe": {}, "constraints": {}, "score": float("inf"), "is_satisfied": False}
|
||||
return merged
|
||||
@@ -2920,6 +3381,7 @@ def get_auto_quantize_config(search_state, constraints=None, verbose=False, algo
|
||||
def _resolve_best_recipe(search_state, constraints, verbose=False):
|
||||
effective_bits = constraints["effective_bits"]
|
||||
compression = effective_bits / 16.0
|
||||
_warn_on_unsized_costs(search_state)
|
||||
candidate_stats = search_state["candidate_stats"]
|
||||
total_weight_size = search_state.get("cost_denominator") or sum(
|
||||
s.get("uncompressed_cost", max(s["costs"])) for s in candidate_stats.values()
|
||||
|
||||
@@ -1121,7 +1121,25 @@ def auto_quantize(
|
||||
:mod:`modelopt.torch.quantization._auto_quantize_shapley`.
|
||||
checkpoint: (Optional) Path to checkpoint file for saving/restoring auto_quantize search state.
|
||||
If the checkpoint file exists, the search state will be restored from it, skipping the
|
||||
expensive score estimation step.
|
||||
expensive score estimation step. On several ranks each rank saves and restores a file
|
||||
of its own, which a resume needs at the same world size (for the weight search also
|
||||
from the same rank, distribution plan, parallel groups and DTensor weight placements),
|
||||
or every rank refuses it.
|
||||
The ranks must search the same layers, with the same arguments, as data, FSDP2 and
|
||||
expert parallelism shard them; pipeline-parallel stages, which do not, start over from
|
||||
a new path, as the search records no pipeline groups to compare a stage's ranks by. One
|
||||
process refuses a weight search's file that a run of several ranks wrote: pass its
|
||||
search state and the constraints to :func:`get_auto_quantize_config` to re-solve its
|
||||
scores, which a pipeline stage's file holds for its own layers only.
|
||||
Weight costs are recomputed from the model on restore (scores are kept), so a
|
||||
checkpoint saved before a cost fix solves against the current budget. The cost refresh
|
||||
itself does not write the checkpoint; a search may still save it, e.g. to finish
|
||||
calibration or scoring, or after solving (``aumann_shapley``, ``cost_model="kv_cache"``).
|
||||
The returned search state carries the recomputed costs, so Python callers can finalize
|
||||
from it directly. Re-solving a checkpoint saved before the fix without the model
|
||||
(:func:`get_auto_quantize_config` with ``constraints``, as HF PTQ's finalize rerun does)
|
||||
warns that its costs may be stale; such file-only workflows should rescore into a new
|
||||
checkpoint to finalize with corrected costs.
|
||||
module_search_spaces: Optional module-specific candidate overrides. Each entry contains
|
||||
``module_name_patterns`` (one or more glob patterns), ``quantization_formats``, and
|
||||
optional ``allow_no_quant`` (default True). A matching entry replaces the global
|
||||
@@ -1324,15 +1342,15 @@ def auto_quantize(
|
||||
# already-sanitized config inside search(), which is a no-op.
|
||||
search_config = searcher.sanitize_search_config(search_config)
|
||||
search_constraints = cast("ConstraintsDict", constraints or {})
|
||||
searcher.validate_search_input(search_constraints, search_config)
|
||||
searcher.validate_search_input(search_constraints, search_config, model)
|
||||
|
||||
# A weight-rewriting candidate's refusals need the converted quantizers to tell which weights it
|
||||
# rewrites, as does a format shard's check of its count against the searched formats. A failure
|
||||
# before any candidate calibrates then hands back the unconverted modules, so the caller can
|
||||
# retry on the same model, which a converted model would refuse. The saved modules hold every
|
||||
# weight conversion replaces (HF Conv1D's), so other searches save none and the searcher drops
|
||||
# them once those checks pass.
|
||||
if rewrites_weights or format_shard is not None:
|
||||
# rewrites, as do a format shard's check of its count against the searched formats and a
|
||||
# resumed file's checks against the search groups. A failure before any candidate calibrates
|
||||
# then hands back the unconverted modules, so the caller can retry on the same model, which a
|
||||
# converted model would refuse. The saved modules hold every weight conversion replaces (HF
|
||||
# Conv1D's), so other searches save none and the searcher drops them once those checks pass.
|
||||
if rewrites_weights or format_shard is not None or searcher._preloaded_state:
|
||||
searcher.restore_unconverted = _save_module_attributes(model)
|
||||
# Calibration turns pre-quant-scale folding off for the whole process. Hand back the policy
|
||||
# found here on every exit, also after a failure while scoring, so later calibrations fold.
|
||||
@@ -1357,7 +1375,12 @@ def auto_quantize(
|
||||
finally:
|
||||
model_calib._ENABLE_FOLDING_PQS_TO_WEIGHTS = folding_pqs_to_weights
|
||||
|
||||
return model, searcher.state_dict()
|
||||
# The rank that wrote a checkpoint, its parallel layout and the search's ID mark its files, not
|
||||
# the search's result, which every rank returns alike but for its own calibrations.
|
||||
search_state = searcher.state_dict()
|
||||
for key in ("checkpoint_rank", "parallel_layout", "search_id"):
|
||||
search_state.pop(key, None)
|
||||
return model, search_state
|
||||
|
||||
|
||||
def merge_auto_quantize_checkpoints(shard_checkpoints: Sequence[str], checkpoint: str) -> None:
|
||||
@@ -1398,7 +1421,10 @@ def get_auto_quantize_config(search_state, constraints=None, verbose=False, algo
|
||||
Re-solves for ``constraints`` if provided, otherwise uses the stored best recipe.
|
||||
|
||||
Args:
|
||||
search_state: The state dict returned by :func:`auto_quantize`.
|
||||
search_state: The state dict returned by :func:`auto_quantize`. Its scores pick formats
|
||||
for the layers it scored alone, a pipeline-parallel rank's its own stage's; the config
|
||||
also carries the fixed configuration's patterns and the picked formats' own, such as
|
||||
K/V-cache ones, which can match modules outside them.
|
||||
constraints: Optional dict, e.g. ``{"effective_bits": 5.5}``, to re-solve for a
|
||||
different target without re-running calibration or scoring.
|
||||
verbose: If True, prints the per-layer recipe assignments.
|
||||
|
||||
@@ -18,12 +18,11 @@ import inspect
|
||||
import os
|
||||
import warnings
|
||||
from contextlib import contextmanager
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import torch
|
||||
import transformers
|
||||
from accelerate import init_empty_weights, load_checkpoint_and_dispatch
|
||||
from accelerate.hooks import AlignDevicesHook, SequentialHook
|
||||
from accelerate.utils import get_max_memory, infer_auto_device_map
|
||||
from accelerate.utils.dataclasses import CustomDtype
|
||||
from accelerate.utils.offload import PrefixedDataset
|
||||
@@ -31,22 +30,14 @@ from accelerate.utils.offload import PrefixedDataset
|
||||
import modelopt.torch.quantization as mtq
|
||||
|
||||
from ..nn import TensorQuantizer
|
||||
from ..utils.core_utils import _get_accelerate_offload_hook as _get_offload_hook
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from accelerate.hooks import AlignDevicesHook
|
||||
|
||||
__all__ = ["init_quantized_weights"]
|
||||
|
||||
|
||||
def _get_offload_hook(hook):
|
||||
if isinstance(hook, AlignDevicesHook) and hook.offload and hook.weights_map is not None:
|
||||
assert len(hook.weights_map) > 0
|
||||
return hook
|
||||
elif isinstance(hook, SequentialHook):
|
||||
for h in hook.hooks:
|
||||
align_hook = _get_offload_hook(h)
|
||||
if align_hook is not None:
|
||||
return align_hook
|
||||
return None
|
||||
|
||||
|
||||
def _writeback_params_to_weights_map(module, align_hook):
|
||||
"""Write all non-meta parameters and buffers back to the hook's CPU weights_map."""
|
||||
buffer_names = {name for name, _ in module.named_buffers()}
|
||||
@@ -209,6 +200,8 @@ def weight_access_and_writeback_context(module, writeback: bool = True):
|
||||
hook = _get_offload_hook(mod._hf_hook)
|
||||
if hook is None:
|
||||
continue
|
||||
# The shared detector also serves export preflight; writeback still needs a backing map.
|
||||
assert len(hook.weights_map) > 0
|
||||
# Only call pre_forward if weights need materializing; already-materialized
|
||||
# weights would be overwritten with stale CPU state_dict values.
|
||||
needs_materialize = any(p.device.type == "meta" for p in mod.parameters())
|
||||
|
||||
@@ -85,7 +85,12 @@ from ..utils import sync_moe_expert_amax
|
||||
from ..utils.layerwise_calib import LayerActivationCollector
|
||||
from .custom import CUSTOM_MODEL_PLUGINS, _ParallelLinear
|
||||
from .gated_delta_net import GatedDeltaNetStateQuantMixin
|
||||
from .transformer_engine import _QuantTEGroupedLinear, _QuantTELayerNormLinear, _QuantTELinear
|
||||
from .transformer_engine import (
|
||||
_per_channel_amax_misfits,
|
||||
_QuantTEGroupedLinear,
|
||||
_QuantTELayerNormLinear,
|
||||
_QuantTELinear,
|
||||
)
|
||||
|
||||
try:
|
||||
from megatron.core.transformer.experimental_attention_variant.dsa import DSAttention
|
||||
@@ -367,7 +372,12 @@ def quant_module_set_extra_state(self, state: Any):
|
||||
continue
|
||||
maybe_promote_nvfp4_static_quantizer(module, quantizer_substate)
|
||||
module.set_from_modelopt_state(quantizer_substate, properties_only=False)
|
||||
self.modelopt_post_restore()
|
||||
# The sharded load then fills the buffers in the shapes this plans, also at another TP size.
|
||||
self._modelopt_resharding_restore = True
|
||||
try:
|
||||
self.modelopt_post_restore()
|
||||
finally:
|
||||
del self._modelopt_resharding_restore
|
||||
try:
|
||||
layout = _swiglu_layout(self, state)
|
||||
except Exception as e:
|
||||
@@ -1399,6 +1409,26 @@ class _QuantMegatronTEGroupedLinear(_QuantTEGroupedLinear, _MegatronParallelLine
|
||||
def modelopt_post_load_extra_state(self):
|
||||
_initialize_grouped_weight_quantizer_state(self)
|
||||
|
||||
def modelopt_post_restore(self, prefix: str = ""):
|
||||
# A gated linear_fc1's weight is sharded by gate and up rows, its per-channel amax by plain
|
||||
# rows: at another expert TP size they'd load on different rows.
|
||||
if (
|
||||
getattr(self, "_modelopt_resharding_restore", False)
|
||||
and self._is_column_parallel
|
||||
and self.config.gated_linear_unit
|
||||
and isinstance(self.weight_quantizer, GroupedQuantizer)
|
||||
and any(
|
||||
_per_channel_amax_misfits(self.weight_quantizer[i], getattr(self, f"weight{i}"))
|
||||
for i in range(self.num_gemms)
|
||||
)
|
||||
):
|
||||
raise ValueError(
|
||||
f"{prefix}: the per-channel weight quantizer state of gated grouped experts can't "
|
||||
"be loaded at another expert tensor-parallel size: load it at the size it was "
|
||||
"saved at."
|
||||
)
|
||||
super().modelopt_post_restore(prefix=prefix)
|
||||
|
||||
def _held_experts_state(self, extra_states: list) -> dict | None:
|
||||
"""The extra state of this rank's experts, each expert's from the EP rank that saved it.
|
||||
|
||||
|
||||
@@ -110,6 +110,35 @@ class _QuantTELinear(_ParallelLinear):
|
||||
_quantized_linear_fn = te_quantized_linear_fn
|
||||
|
||||
|
||||
def _per_channel_amax_shape(quantizer: TensorQuantizer, weight: torch.Tensor) -> torch.Size | None:
|
||||
"""The shape ``quantizer``'s per-channel amax takes for ``weight``, None if its own already fits.
|
||||
|
||||
Judged by the buffer's own layout (its channel dims, of size > 1), as the kernels broadcast it,
|
||||
not by the configured axis. A one-entry amax (e.g. a constant_amax pin) fits every weight.
|
||||
"""
|
||||
amax = getattr(quantizer, "_amax", None)
|
||||
if amax is None or quantizer.block_sizes or amax.numel() == 1 or amax.dim() != weight.dim():
|
||||
return None
|
||||
if all(a in (1, w) for a, w in zip(amax.shape, weight.shape)):
|
||||
return None
|
||||
return torch.Size(1 if a == 1 else w for a, w in zip(amax.shape, weight.shape))
|
||||
|
||||
|
||||
def _per_channel_amax_misfits(quantizer: torch.nn.Module, weight: torch.Tensor) -> list:
|
||||
"""``quantizer``'s leaves whose per-channel amax doesn't fit the channels of ``weight``."""
|
||||
# A quantizer that doesn't quantize with its amax (disabled, quantization off, or
|
||||
# use_constant_amax) keeps the shape it was saved with.
|
||||
return [
|
||||
leaf
|
||||
for leaf in quantizer.modules()
|
||||
if isinstance(leaf, TensorQuantizer)
|
||||
and leaf.is_enabled
|
||||
and leaf._if_quant
|
||||
and not leaf._use_constant_amax
|
||||
and _per_channel_amax_shape(leaf, weight) is not None
|
||||
]
|
||||
|
||||
|
||||
# Register the public te.pytorch.GroupedLinear class
|
||||
@QuantModuleRegistry.register({te_grouped_linear.GroupedLinear: "te_GroupedLinear"})
|
||||
class _QuantTEGroupedLinear(_ParallelLinear):
|
||||
@@ -192,15 +221,24 @@ class _QuantTEGroupedLinear(_ParallelLinear):
|
||||
weight_i = getattr(self, f"weight{i}", None)
|
||||
if weight_i is None:
|
||||
continue
|
||||
if weight_i.device.type != "cuda":
|
||||
continue # export loads weights on CPU; the fp4 dry-run needs CUDA — keep loaded amax
|
||||
wq_i = self.weight_quantizer[i]
|
||||
q = wq_i[0] if isinstance(wq_i, SequentialQuantizer) else wq_i
|
||||
if not hasattr(q, "_amax") or q._amax is None:
|
||||
continue
|
||||
if any(pin_names(leaf) for leaf in wq_i.modules() if isinstance(leaf, TensorQuantizer)):
|
||||
# GGML pins hold no codes to dry-run until the weights load.
|
||||
continue
|
||||
# A per-channel amax restored at another TP size, which the per-channel kernels would
|
||||
# index past its end (a device-side assert). In a sharded restore its values load with
|
||||
# the weights, so it takes this weight's shape only, without reading the (maybe not yet
|
||||
# loaded) weight. Another restore loads the buffers as saved.
|
||||
misfits = []
|
||||
if getattr(self, "_modelopt_resharding_restore", False):
|
||||
misfits = _per_channel_amax_misfits(wq_i, weight_i)
|
||||
for leaf in misfits:
|
||||
leaf._amax = leaf._amax.new_empty(_per_channel_amax_shape(leaf, weight_i))
|
||||
if misfits or weight_i.device.type != "cuda":
|
||||
continue # export loads weights on CPU; the fp4 dry-run needs CUDA — keep loaded amax
|
||||
q = wq_i[0] if isinstance(wq_i, SequentialQuantizer) else wq_i
|
||||
if not hasattr(q, "_amax") or q._amax is None:
|
||||
continue
|
||||
prev_fake = getattr(q, "_fake_quant", True)
|
||||
q._fake_quant = True
|
||||
# The dry run checks shapes only. The buffers may not hold values yet (``mto.restore()``
|
||||
|
||||
@@ -22,6 +22,7 @@ import weakref
|
||||
from collections import namedtuple
|
||||
from collections.abc import Iterator
|
||||
from contextlib import ExitStack, contextmanager, nullcontext
|
||||
from functools import cache
|
||||
from typing import TYPE_CHECKING, Any, NamedTuple
|
||||
|
||||
import torch
|
||||
@@ -1049,22 +1050,50 @@ def requires_weight_materialization(module, root_model, names: "ModuleNames | No
|
||||
hook = getattr(module, "_hf_hook", None)
|
||||
if hook is None:
|
||||
return False
|
||||
from ..plugins.accelerate import _get_offload_hook
|
||||
|
||||
return _get_offload_hook(hook) is not None
|
||||
return _get_accelerate_offload_hook(hook) is not None
|
||||
|
||||
|
||||
def has_accelerate_offload(module: nn.Module) -> bool:
|
||||
"""Return True if any module in ``module`` has a CPU- or disk-offload accelerate hook."""
|
||||
@cache
|
||||
def _accelerate_hook_types():
|
||||
# Keep Accelerate optional without repeating imports for every offloaded owner.
|
||||
from accelerate.hooks import AlignDevicesHook, SequentialHook
|
||||
|
||||
return AlignDevicesHook, SequentialHook
|
||||
|
||||
|
||||
def _iter_accelerate_offload_hooks(hook, *, include_suspended=False):
|
||||
if hook is None:
|
||||
return
|
||||
align_cls, sequential_cls = _accelerate_hook_types()
|
||||
|
||||
if (
|
||||
isinstance(hook, align_cls)
|
||||
and (hook.offload or (include_suspended and hasattr(hook, "original_devices")))
|
||||
and hook.weights_map is not None
|
||||
):
|
||||
yield hook
|
||||
elif isinstance(hook, sequential_cls):
|
||||
for h in hook.hooks:
|
||||
yield from _iter_accelerate_offload_hooks(h, include_suspended=include_suspended)
|
||||
|
||||
|
||||
def _get_accelerate_offload_hook(hook, *, include_suspended=False):
|
||||
return next(_iter_accelerate_offload_hooks(hook, include_suspended=include_suspended), None)
|
||||
|
||||
|
||||
def has_accelerate_offload(module: nn.Module, *, include_suspended: bool = False) -> bool:
|
||||
"""Detect offload owners, optionally including hooks suspended by an outer window."""
|
||||
try:
|
||||
from ..plugins.accelerate import _get_offload_hook
|
||||
return any(
|
||||
_get_accelerate_offload_hook(
|
||||
getattr(child, "_hf_hook", None), include_suspended=include_suspended
|
||||
)
|
||||
is not None
|
||||
for child in module.modules()
|
||||
)
|
||||
except ImportError:
|
||||
return False
|
||||
|
||||
return any(
|
||||
_get_offload_hook(getattr(m, "_hf_hook", None)) is not None for m in module.modules()
|
||||
)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def persistent_materialization(layer, writeback: bool = True):
|
||||
|
||||
@@ -39,6 +39,9 @@ from .sparsegpt import SparseGPTSearcher
|
||||
|
||||
SparsityModeRegistry = _ModeRegistryCls("sparsity")
|
||||
|
||||
# Marks a checkpoint whose Megatron gated MLPs save their linear_fc1 mask in the SwiGLU layout.
|
||||
_SWIGLU_WEIGHT_MASK = "megatron_swiglu_weight_mask"
|
||||
|
||||
|
||||
def convert_sparse_model(model: nn.Module, config: ModeloptBaseConfig) -> ConvertReturnType:
|
||||
"""Function for converting a model to a sparsity meta-model."""
|
||||
@@ -46,7 +49,10 @@ def convert_sparse_model(model: nn.Module, config: ModeloptBaseConfig) -> Conver
|
||||
dynamic_space = DynamicSpace(model)
|
||||
dynamic_space.convert_to_dynamic(config.model_dump(), SpDMRegistry)
|
||||
|
||||
return dynamic_space.model, {"subnet_config": DynamicSpace(model).config()}
|
||||
return dynamic_space.model, {
|
||||
"subnet_config": DynamicSpace(model).config(),
|
||||
_SWIGLU_WEIGHT_MASK: True,
|
||||
}
|
||||
|
||||
|
||||
def restore_sparse_model(
|
||||
@@ -54,6 +60,11 @@ def restore_sparse_model(
|
||||
) -> nn.Module:
|
||||
"""Function for restoring a previously convert model to a sparsity meta-model."""
|
||||
model, _ = convert_sparse_model(model, config)
|
||||
if not metadata.get(_SWIGLU_WEIGHT_MASK, False):
|
||||
# Saved before gated MLPs' masks took Megatron's SwiGLU layout: load them as saved.
|
||||
for module in model.modules():
|
||||
if hasattr(module, "_swiglu_weight_mask"):
|
||||
module._swiglu_weight_mask = False
|
||||
|
||||
if "subnet_config" in metadata:
|
||||
DynamicSpace(model).select(metadata["subnet_config"])
|
||||
|
||||
@@ -73,7 +73,19 @@ class _MegatronRowParallelLinear(_MegatronParallelLinear):
|
||||
class _SparseMegatronMLP(_MegatronMLP):
|
||||
"""Module to support special handling of `linear_fc1` in `sharded_state_dict()` of MCore `MLP`."""
|
||||
|
||||
_modelopt_state_keys = [r"\._weight_mask$"]
|
||||
def _setup(self):
|
||||
super()._setup()
|
||||
# Whether a gated linear_fc1's mask is planned in Megatron's SwiGLU layout (gate and up rows
|
||||
# under their own keys, correct at any TP size). Checkpoints saved before keep one key. A
|
||||
# later mode's conversion (e.g. quantization) runs this again: keep the restored choice. Gone
|
||||
# on the final export, so sparsifying again starts in the new layout.
|
||||
if not hasattr(self, "_swiglu_weight_mask"):
|
||||
self._register_temp_attribute("_swiglu_weight_mask", True)
|
||||
|
||||
def _is_swiglu_state(self, key, sharded_tensor) -> bool:
|
||||
if key.endswith("linear_fc1._weight_mask"):
|
||||
return self._swiglu_weight_mask
|
||||
return super()._is_swiglu_state(key, sharded_tensor)
|
||||
|
||||
|
||||
def _get_extra_rules():
|
||||
|
||||
@@ -50,7 +50,7 @@ class BaseSparseSearcher(BaseSearcher):
|
||||
# sanity check of sparsity format
|
||||
is_nm_prune, n, m = asp.get_nmprune_info(config_sanitized["pattern"])
|
||||
assert is_nm_prune and n == 2 and m == 4, (
|
||||
f"Unsupported pattern {self.config['pattern']} for sparsity"
|
||||
f"Unsupported pattern {config_sanitized['pattern']} for sparsity"
|
||||
)
|
||||
|
||||
return config_sanitized
|
||||
|
||||
@@ -77,6 +77,7 @@ from pathlib import Path
|
||||
from typing import NamedTuple
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from transformers import PreTrainedModel
|
||||
from transformers.models.qwen3.configuration_qwen3 import Qwen3Config as _Qwen3Config
|
||||
from transformers.trainer_pt_utils import LabelSmoother
|
||||
@@ -205,6 +206,9 @@ class HFDFlashModel(DFlashModel):
|
||||
# the anchor's own position onward, so slot 0 (the given anchor) is never supervised.
|
||||
_label_shift = 0
|
||||
|
||||
# The process group the context is sharded over; set by enable_context_parallel.
|
||||
_context_group = None
|
||||
|
||||
@property
|
||||
def _base_model(self):
|
||||
return self.get_submodule(self.base_model_path)
|
||||
@@ -269,6 +273,7 @@ class HFDFlashModel(DFlashModel):
|
||||
super().modify(config)
|
||||
|
||||
self.dflash_fp32_master_weights = config.dflash_fp32_master_weights
|
||||
self._projector_type = config.dflash_architecture_config.get("projector_type")
|
||||
|
||||
base_config = self._base_llm_config
|
||||
# Use Qwen3Config (not generic PretrainedConfig) so rope_parameters is
|
||||
@@ -507,6 +512,47 @@ class HFDFlashModel(DFlashModel):
|
||||
self.dflash_module._maybe_init_rotary_emb(device=base_device)
|
||||
self._draft_placed = True
|
||||
|
||||
@property
|
||||
def context_parallel_enabled(self):
|
||||
"""Whether the training forward expects one rank's slice of the context."""
|
||||
return self._context_group is not None
|
||||
|
||||
def check_context_parallel_support(self):
|
||||
"""Raise ``ValueError`` if this draft cannot train with context parallelism."""
|
||||
unsupported = []
|
||||
if self._projector_type not in (None, "dflash"):
|
||||
unsupported.append(f"projector_type={self._projector_type!r}")
|
||||
if not self.dflash_offline:
|
||||
unsupported.append("online training")
|
||||
if self.dflash_use_torch_compile:
|
||||
unsupported.append("dflash_use_torch_compile=true")
|
||||
if self.dflash_config.attention_dropout:
|
||||
unsupported.append("attention_dropout > 0")
|
||||
if unsupported:
|
||||
raise ValueError(
|
||||
"DFlash context parallelism (cp_size > 1) supports only the plain DFlash draft, "
|
||||
"trained offline without torch.compile or attention dropout. Unsupported here: "
|
||||
f"{', '.join(unsupported)}. Change these or set cp_size=1."
|
||||
)
|
||||
|
||||
def enable_context_parallel(self, group):
|
||||
"""Shard the training context over ``group``, whose ranks must train on the same batch.
|
||||
|
||||
Each rank then passes only its slice of ``aux_hidden_states`` (see
|
||||
:meth:`shard_context`), and gradients must be averaged over the ranks, as DDP and
|
||||
FSDP2 do.
|
||||
"""
|
||||
self.check_context_parallel_support()
|
||||
self._context_group = group
|
||||
self.dflash_module.set_context_group(group)
|
||||
|
||||
def shard_context(self, base_model_outputs: dict):
|
||||
"""Replace a batch's ``aux_hidden_states`` with this rank's slice of the sequence."""
|
||||
group = self._context_group
|
||||
slices = base_model_outputs["aux_hidden_states"].chunk(dist.get_world_size(group), dim=1)
|
||||
# clone() so that nothing keeps the full-length tensor alive.
|
||||
base_model_outputs["aux_hidden_states"] = slices[dist.get_rank(group)].clone()
|
||||
|
||||
# Draft-module entries that legitimately come from the base model rather than the
|
||||
# exported draft checkpoint, so their absence (or presence) is not an error.
|
||||
_INIT_CKPT_IGNORED_KEYS = ("embed_tokens.weight", "lm_head.weight")
|
||||
@@ -656,6 +702,9 @@ class HFDFlashModel(DFlashModel):
|
||||
|
||||
keep = cols < torch.minimum(valid_counts, cap).unsqueeze(1)
|
||||
anchors = torch.where(keep, anchors, torch.tensor(0, dtype=torch.long, device=device))
|
||||
if self._context_group is not None:
|
||||
# Every rank of the group has to draft the same blocks, whatever its RNG state.
|
||||
dist.broadcast(anchors, group=self._context_group, group_src=0)
|
||||
return anchors, keep
|
||||
|
||||
def _build_noise_embedding(self, input_ids, anchor_positions, block_keep_mask, n_blocks):
|
||||
@@ -1067,6 +1116,14 @@ class HFDFlashModel(DFlashModel):
|
||||
**kwargs,
|
||||
)
|
||||
target_hidden = base_outputs.target_hidden
|
||||
if self._context_group is not None:
|
||||
cp_size = dist.get_world_size(self._context_group)
|
||||
if target_hidden.shape[1] * cp_size != seq_len:
|
||||
raise ValueError(
|
||||
f"Under context parallelism each rank passes seq_len / cp_size = "
|
||||
f"{seq_len}/{cp_size} positions of aux_hidden_states, got "
|
||||
f"{target_hidden.shape[1]}. Use shard_context() on the batch."
|
||||
)
|
||||
|
||||
# 2. Build loss mask.
|
||||
loss_mask = self._build_loss_mask(
|
||||
|
||||
@@ -44,8 +44,10 @@ The draft architecture is independent of the target model.
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
from torch.utils.checkpoint import checkpoint
|
||||
from transformers.modeling_layers import GradientCheckpointingLayer
|
||||
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
|
||||
from transformers.models.qwen3.modeling_qwen3 import Qwen3MLP as _MLP_CLS # noqa: N814
|
||||
@@ -166,6 +168,26 @@ def apply_rotary_pos_emb(q, k, cos, sin):
|
||||
return q_embed, k_embed
|
||||
|
||||
|
||||
class _GatherContext(torch.autograd.Function):
|
||||
"""All-gather each rank's slice of the context along the sequence dimension.
|
||||
|
||||
Every rank attends over the same gathered tensor and so receives the same gradient:
|
||||
backward keeps this rank's slice, scaled by the group size because the trainer averages
|
||||
gradients over ranks while the slices' gradients must be summed.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def forward(ctx, local, group):
|
||||
ctx.rank, ctx.size = dist.get_rank(group), dist.get_world_size(group)
|
||||
slices = [torch.empty_like(local) for _ in range(ctx.size)]
|
||||
dist.all_gather(slices, local.contiguous(), group=group)
|
||||
return torch.cat(slices, dim=1)
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad):
|
||||
return grad.chunk(ctx.size, dim=1)[ctx.rank] * ctx.size, None
|
||||
|
||||
|
||||
class DFlashAttention(nn.Module):
|
||||
"""Attention with KV injection, using HF's attention dispatch."""
|
||||
|
||||
@@ -183,6 +205,8 @@ class DFlashAttention(nn.Module):
|
||||
self.scaling = self.head_dim**-0.5
|
||||
self.attention_dropout = getattr(config, "attention_dropout", 0.0)
|
||||
self.is_causal = False
|
||||
# Set under context parallelism, where ``target_hidden`` is one rank's slice.
|
||||
self.context_group = None
|
||||
|
||||
attn_bias = getattr(config, "attention_bias", False)
|
||||
self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=attn_bias)
|
||||
@@ -231,8 +255,14 @@ class DFlashAttention(nn.Module):
|
||||
K and V are projected from the concatenation of target hidden states (context from the
|
||||
base model) and noise block, so the draft can attend to both context and its own block.
|
||||
"""
|
||||
inputs = (hidden_states, target_hidden, position_embeddings, attention_mask)
|
||||
if self.context_group is None or not torch.is_grad_enabled():
|
||||
return self._attend(*inputs)
|
||||
# Backward gathers the context again, so no layer holds a full-length copy of it.
|
||||
return checkpoint(self._attend, *inputs, use_reentrant=False)
|
||||
|
||||
def _attend(self, hidden_states, target_hidden, position_embeddings, attention_mask):
|
||||
bsz, q_len, _ = hidden_states.shape
|
||||
ctx_len = target_hidden.shape[1]
|
||||
|
||||
# Q from noise block only (the draft tokens being predicted), with QK-norm
|
||||
q = self.q_proj(hidden_states).view(bsz, q_len, -1, self.head_dim)
|
||||
@@ -240,12 +270,17 @@ class DFlashAttention(nn.Module):
|
||||
|
||||
# K from context + noise, with QK-norm
|
||||
k_ctx = self.k_proj(target_hidden)
|
||||
if self.context_group is not None:
|
||||
k_ctx = _GatherContext.apply(k_ctx, self.context_group)
|
||||
ctx_len = k_ctx.shape[1]
|
||||
k_noise = self.k_proj(hidden_states)
|
||||
k = torch.cat([k_ctx, k_noise], dim=1).view(bsz, ctx_len + q_len, -1, self.head_dim)
|
||||
k = self.k_norm(k).transpose(1, 2)
|
||||
|
||||
# V from context + noise (no norm)
|
||||
v_ctx = self.v_proj(target_hidden)
|
||||
if self.context_group is not None:
|
||||
v_ctx = _GatherContext.apply(v_ctx, self.context_group)
|
||||
v_noise = self.v_proj(hidden_states)
|
||||
v = (
|
||||
torch.cat([v_ctx, v_noise], dim=1)
|
||||
@@ -430,6 +465,11 @@ class DFlashModule(nn.Module):
|
||||
self._maybe_init_rotary_emb(device=noise_embedding.device)
|
||||
return self._body()(noise_embedding, target_hidden, position_ids, attention_mask)
|
||||
|
||||
def set_context_group(self, group):
|
||||
"""Attend over a context whose slices are spread across ``group``'s ranks."""
|
||||
for layer in self.layers:
|
||||
layer.self_attn.context_group = group
|
||||
|
||||
def compile_body(self):
|
||||
"""Inductor-compile the draft stack; ``_body`` runs it in training only.
|
||||
|
||||
|
||||
@@ -77,6 +77,7 @@ __all__ = [
|
||||
"load_mbridge_model_from_hf",
|
||||
"load_modelopt_megatron_checkpoint",
|
||||
"read_megatron_checkpoint_layout",
|
||||
"resolve_modelopt_megatron_checkpoint",
|
||||
"set_moe_expert_layout",
|
||||
"use_moe_grouped_gemm",
|
||||
]
|
||||
@@ -306,6 +307,20 @@ def _checkpoint_holds(model, megatron_path: str) -> tuple[str, tuple[bool, bool,
|
||||
return checkpoint_path, dist.all_reduce(f"What {checkpoint_path} holds", holds, combine=alike)
|
||||
|
||||
|
||||
def resolve_modelopt_megatron_checkpoint(
|
||||
model: list[MegatronModule], megatron_path: str
|
||||
) -> tuple[str, bool]:
|
||||
"""The iteration a load of ``megatron_path`` takes, and whether it holds a language model only.
|
||||
|
||||
That is, only the VLM ``model``'s language model, e.g. a QAD checkpoint from ``distill.py``.
|
||||
Agreed on every rank; reads checkpoint metadata only. Pass the returned iteration directory to
|
||||
:func:`load_modelopt_megatron_checkpoint`, so a newer iteration published in between can't be
|
||||
loaded instead of the one inspected here.
|
||||
"""
|
||||
checkpoint_path, (language_model_only, *_) = _checkpoint_holds(model, megatron_path)
|
||||
return checkpoint_path, language_model_only
|
||||
|
||||
|
||||
def _language_model_only(model: list[MegatronModule], checkpoint_keys: list[str]) -> bool:
|
||||
"""Whether a VLM ``model``'s checkpoint (of ``checkpoint_keys``) holds its language model only."""
|
||||
# ``distill.py`` distills a VLM's language model only, so its checkpoint holds the language
|
||||
|
||||
@@ -32,11 +32,15 @@ from tqdm import tqdm
|
||||
|
||||
__all__ = ["megatron_generate", "megatron_prefill"]
|
||||
|
||||
# ``is_hybrid_cp`` exists only in newer Megatron-Core; pass it only if the signature accepts it.
|
||||
_CP_BATCH_KWARGS = (
|
||||
{"is_hybrid_cp": False}
|
||||
if "is_hybrid_cp" in inspect.signature(get_batch_on_this_cp_rank).parameters
|
||||
else {}
|
||||
# Megatron-Core renamed ``is_hybrid_cp`` to a required ``dynamic_cp`` (keeping the old name as a
|
||||
# deprecated alias for a while); pass the newest one this build takes.
|
||||
_CP_BATCH_KWARGS = next(
|
||||
(
|
||||
{name: False}
|
||||
for name in ("dynamic_cp", "is_hybrid_cp")
|
||||
if name in inspect.signature(get_batch_on_this_cp_rank).parameters
|
||||
),
|
||||
{},
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -64,7 +64,7 @@ def _rank_1_only(case, rank, size):
|
||||
"check_exportable_quantizers",
|
||||
side_effect=AssertionError("entered Megatron-Bridge's preflight"),
|
||||
):
|
||||
assert not export.use_bridge_export(bridge, [model], _args(), False)
|
||||
assert not export.use_bridge_export(bridge, [model], _args())
|
||||
|
||||
|
||||
@pytest.mark.timeout(120)
|
||||
@@ -84,7 +84,7 @@ def test_a_forced_modelopt_export_of_an_iq_checkpoint_needs_tp_and_pp_1():
|
||||
patch.object(export, "uses_iq_quantization", return_value=True),
|
||||
pytest.raises(ValueError, match="--tp_size 1 --pp_size 1"),
|
||||
):
|
||||
export.use_bridge_export(_Bridge(), [torch.nn.Linear(4, 4)], args, False)
|
||||
export.use_bridge_export(_Bridge(), [torch.nn.Linear(4, 4)], args)
|
||||
|
||||
|
||||
def test_a_bridge_that_post_processes_exported_weights_falls_back_to_modelopt():
|
||||
@@ -98,4 +98,69 @@ def test_a_bridge_that_post_processes_exported_weights_falls_back_to_modelopt():
|
||||
bridge = _Bridge()
|
||||
bridge._model_bridge = _PostProcessing()
|
||||
with patch.object(export, "unexportable_weight", return_value=None):
|
||||
assert not export.use_bridge_export(bridge, [torch.nn.Linear(4, 4)], _args(), False)
|
||||
assert not export.use_bridge_export(bridge, [torch.nn.Linear(4, 4)], _args())
|
||||
|
||||
|
||||
class _Vlm(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.language_model = torch.nn.Linear(4, 4)
|
||||
|
||||
|
||||
def _load_checkpoint(iterations, language_model_only, **arg_overrides):
|
||||
"""Run load_quantized_checkpoint while the checkpoint root's latest iteration advances.
|
||||
|
||||
Each resolution of the root takes the next of ``iterations``; an iteration in
|
||||
``language_model_only`` holds the language model alone. Returns the iteration loaded and
|
||||
whether the HF weights were loaded first.
|
||||
"""
|
||||
export = _export_script()
|
||||
# Imported here, so the pytest process loads Megatron-Bridge only for these tests.
|
||||
import modelopt.torch.utils.plugins.mbridge as mbridge
|
||||
|
||||
root, latest, loaded, preloaded = "ckpt", iter(iterations), [], []
|
||||
|
||||
def resolve(path, ckpt_step=None):
|
||||
return next(latest) if path == root else path
|
||||
|
||||
def keys(path):
|
||||
return ["decoder.weight"] if path in language_model_only else ["language_model.weight"]
|
||||
|
||||
bridge = _Bridge()
|
||||
bridge.load_hf_weights = lambda model, hf_path: preloaded.append(hf_path)
|
||||
args = _args(
|
||||
megatron_path=root, local_checkpoint_path="hf", vllm_fakequant_export=False, **arg_overrides
|
||||
)
|
||||
with (
|
||||
patch.object(mbridge, "_get_modelopt_checkpoint_path", resolve),
|
||||
patch.object(mbridge, "_checkpoint_keys", keys),
|
||||
# The real load resolves the path it gets, as here.
|
||||
patch.object(
|
||||
export, "load_modelopt_megatron_checkpoint", lambda m, p: loaded.append(resolve(p))
|
||||
),
|
||||
):
|
||||
export.load_quantized_checkpoint(bridge, [_Vlm()], args)
|
||||
return loaded, bool(preloaded)
|
||||
|
||||
|
||||
def test_the_checkpoint_iteration_is_resolved_once():
|
||||
"""A language-model-only iteration published after the full VLM one was inspected isn't loaded."""
|
||||
loaded, preloaded = _load_checkpoint(["iter_1", "iter_2"], language_model_only={"iter_2"})
|
||||
assert loaded == ["iter_1"]
|
||||
assert not preloaded
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("arg_overrides", "expect_preload"),
|
||||
[({}, True), ({"modelopt_megatron_exporter": True}, False)],
|
||||
ids=["bridge", "forced_modelopt"],
|
||||
)
|
||||
def test_a_language_model_only_checkpoint_loads_over_the_hf_weights_for_bridge_only(
|
||||
arg_overrides, expect_preload
|
||||
):
|
||||
"""ModelOpt's exporter copies the vision tower itself, so it needs no HF weight load."""
|
||||
loaded, preloaded = _load_checkpoint(
|
||||
["iter_1"], language_model_only={"iter_1"}, **arg_overrides
|
||||
)
|
||||
assert loaded == ["iter_1"]
|
||||
assert preloaded == expect_preload
|
||||
|
||||
@@ -130,8 +130,7 @@ def test_qad(tmp_path: Path, num_gpus, create_student, lora_rank, full_rank):
|
||||
else "general/ptq/nvfp4_default-kv_fp8"
|
||||
if lora_rank
|
||||
else "general/ptq/fp8_default-kv_fp8",
|
||||
# The VLM quantizes no KV cache, which Megatron-Bridge's export can carry, so only the
|
||||
# language-model-only routing keeps its export below on ModelOpt's exporter.
|
||||
# The VLM quantizes no KV cache, so Megatron-Bridge writes its export below.
|
||||
quant_cfg="fp8" if is_vlm else None,
|
||||
lora_rank=lora_rank,
|
||||
tp_size=tp_size,
|
||||
@@ -278,9 +277,9 @@ def test_qad(tmp_path: Path, num_gpus, create_student, lora_rank, full_rank):
|
||||
run_example_command(export_cmd, example_path="megatron_bridge", setup_free_port=True)
|
||||
quant_config = json.loads((hf_export_path / "config.json").read_text())["quantization_config"]
|
||||
if is_vlm:
|
||||
# A VLM's language-model-only QAD checkpoint holds no vision tower, which only ModelOpt's
|
||||
# exporter copies from the HF source: the export must take that path (its sidecar shows it).
|
||||
assert (hf_export_path / "hf_quant_config.json").exists()
|
||||
# A VLM's language-model-only QAD checkpoint holds no vision tower: Megatron-Bridge still
|
||||
# writes the export (ModelOpt's exporter would add hf_quant_config.json), with the HF tower.
|
||||
assert not (hf_export_path / "hf_quant_config.json").exists()
|
||||
if lora_rank:
|
||||
assert not (hf_export_path / "adapter_config.json").exists()
|
||||
index = json.loads((hf_export_path / "model.safetensors.index.json").read_text())
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from _test_utils.examples.run_command import MODELOPT_ROOT, run_example_command
|
||||
|
||||
DFLASH_YAML = str(
|
||||
MODELOPT_ROOT / "modelopt_recipes" / "general" / "speculative_decoding" / "dflash.yaml"
|
||||
)
|
||||
|
||||
|
||||
def test_offline_dflash_context_parallel(tiny_llama_path, tmp_path, num_gpus):
|
||||
"""Train an offline DFlash draft with the context split over two GPUs."""
|
||||
if num_gpus < 2:
|
||||
pytest.skip(f"cp_size=2 requires at least 2 GPUs, but only {num_gpus} found.")
|
||||
|
||||
data_dir = tmp_path / "hidden_states"
|
||||
data_dir.mkdir()
|
||||
torch.manual_seed(0)
|
||||
for i in range(8):
|
||||
sample = {
|
||||
"input_ids": torch.randint(1, 32, (128,)),
|
||||
"hidden_states": torch.randn(128, 512),
|
||||
"aux_hidden_states": torch.randn(128, 512), # one draft layer
|
||||
}
|
||||
torch.save(sample, data_dir / f"sample_{i}.pt")
|
||||
|
||||
run_example_command(
|
||||
[
|
||||
"./launch_train.sh",
|
||||
"--config",
|
||||
DFLASH_YAML,
|
||||
f"model.model_name_or_path={tiny_llama_path}",
|
||||
f"data.offline_data_path={data_dir}",
|
||||
f"training.output_dir={tmp_path / 'ckpt'}",
|
||||
"training.num_train_epochs=1",
|
||||
"training.training_seq_len=128",
|
||||
"training.answer_only_loss=false",
|
||||
"training.cp_size=2",
|
||||
"training.tf32=false", # the recipe's tf32 needs Ampere or newer
|
||||
"dflash.dflash_mask_token_id=0",
|
||||
"dflash.dflash_architecture_config.num_hidden_layers=1",
|
||||
],
|
||||
"speculative_decoding",
|
||||
)
|
||||
@@ -14,12 +14,14 @@
|
||||
# limitations under the License.
|
||||
import copy
|
||||
import json
|
||||
from contextlib import ExitStack
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from _test_utils.torch.distributed.utils import bounded_collectives
|
||||
from _test_utils.torch.export.utils import SmallQKVModel, ToyModel
|
||||
from _test_utils.torch.misc import minimum_sm
|
||||
from _test_utils.torch.quantization.tied_modules import (
|
||||
@@ -37,6 +39,7 @@ from modelopt.torch.export.model_utils import TiedWeightMap
|
||||
from modelopt.torch.export.unified_export_hf import (
|
||||
_export_quantized_weight,
|
||||
_export_transformers_checkpoint,
|
||||
export_hf_checkpoint,
|
||||
requantize_resmooth_fused_llm_layers,
|
||||
)
|
||||
from modelopt.torch.export.unified_export_hf_streaming import _export_fsdp2_checkpoint_streaming
|
||||
@@ -47,6 +50,7 @@ from modelopt.torch.quantization.utils import (
|
||||
module_name_maps,
|
||||
patch_fsdp_mp_dtypes,
|
||||
)
|
||||
from modelopt.torch.utils.distributed import DistributionPlan, set_distribution_plan
|
||||
|
||||
|
||||
def _update_weight_test(rank, size):
|
||||
@@ -504,3 +508,80 @@ def test_fsdp2_streaming_export_matches_reference(dist_workers, tmp_path, quant_
|
||||
quant_config=quant_config,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _one_rank_has_suspended_fsdp_offload_job(rank, size, tmp_dir, direct, writer, wrapped):
|
||||
# Accelerate is optional; this worker is only launched after the guarded parent test.
|
||||
from accelerate import cpu_offload
|
||||
|
||||
from modelopt.torch.export import export_hf_vllm_fq_checkpoint
|
||||
|
||||
model = get_tiny_llama(dtype=torch.float32).cuda().eval()
|
||||
if wrapped:
|
||||
fully_shard(model.model.layers[0])
|
||||
set_distribution_plan(model, DistributionPlan(size, dense="fsdp"))
|
||||
if not direct or rank == 0:
|
||||
cpu_offload(
|
||||
model.model.layers[1],
|
||||
execution_device=torch.device("cuda", torch.cuda.current_device()),
|
||||
)
|
||||
with ExitStack() as stack:
|
||||
if rank == 0:
|
||||
stack.enter_context(
|
||||
enable_weight_access_and_writeback(
|
||||
model.model.layers[1].mlp.down_proj, model, writeback=False
|
||||
)
|
||||
)
|
||||
parameters = tuple(model.parameters())
|
||||
refused = False
|
||||
with bounded_collectives(5):
|
||||
try:
|
||||
if writer == "vllm":
|
||||
export_hf_vllm_fq_checkpoint(model, export_dir=tmp_dir)
|
||||
elif direct:
|
||||
_export_transformers_checkpoint(model, dtype=torch.float32)
|
||||
else:
|
||||
export_hf_checkpoint(model, export_dir=tmp_dir)
|
||||
except NotImplementedError as error:
|
||||
refused = "weight-access window" in str(error)
|
||||
assert refused
|
||||
assert all(
|
||||
actual is original
|
||||
for actual, original in zip(model.parameters(), parameters, strict=True)
|
||||
)
|
||||
assert not tmp_dir.exists()
|
||||
# Closing a window restores the offload flag; public dispatch must still agree across ranks.
|
||||
parameters = tuple(model.parameters())
|
||||
refused = False
|
||||
with bounded_collectives(5):
|
||||
try:
|
||||
if writer == "vllm":
|
||||
export_hf_vllm_fq_checkpoint(model, export_dir=tmp_dir)
|
||||
else:
|
||||
export_hf_checkpoint(model, export_dir=tmp_dir)
|
||||
except NotImplementedError:
|
||||
refused = True
|
||||
assert refused
|
||||
assert all(
|
||||
actual is original for actual, original in zip(model.parameters(), parameters, strict=True)
|
||||
)
|
||||
assert not tmp_dir.exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("wrapped", [False, True])
|
||||
@pytest.mark.parametrize("writer", ["hf", "vllm"])
|
||||
@pytest.mark.parametrize("direct", [False, True])
|
||||
def test_fsdp_export_refuses_one_ranks_suspended_offload_before_mutation(
|
||||
need_2_gpus, dist_workers, tmp_path, direct, writer, wrapped, monkeypatch
|
||||
):
|
||||
pytest.importorskip("accelerate")
|
||||
pytest.importorskip("transformers")
|
||||
monkeypatch.setattr(dist_workers, "job_timeout", 45)
|
||||
monkeypatch.setattr(dist_workers, "failure_grace", 2)
|
||||
dist_workers.run(
|
||||
_one_rank_has_suspended_fsdp_offload_job,
|
||||
tmp_dir=tmp_path / "export",
|
||||
direct=direct,
|
||||
writer=writer,
|
||||
wrapped=wrapped,
|
||||
)
|
||||
|
||||
@@ -19,10 +19,12 @@ import pytest
|
||||
import torch
|
||||
from _test_utils.torch.quantization.offload import make_cpu_offloaded_model, make_layerwise_cfg
|
||||
from _test_utils.torch.transformers_models import create_tiny_llama_dir, create_tiny_qwen3_moe_dir
|
||||
from accelerate.hooks import AlignDevicesHook, add_hook_to_module
|
||||
from transformers import AutoModelForCausalLM
|
||||
|
||||
import modelopt.torch.quantization as mtq
|
||||
from modelopt.torch.export import export_hf_vllm_fq_checkpoint
|
||||
from modelopt.torch.export.plugins.vllm_fakequant_hf import _resmooth_experts_for_export
|
||||
from modelopt.torch.quantization.model_quant import fold_weight
|
||||
from modelopt.torch.quantization.utils import enable_weight_access_and_writeback
|
||||
from modelopt.torch.utils import safe_load
|
||||
@@ -246,3 +248,44 @@ def test_hf_vllm_export_resized_vocab(tmp_path):
|
||||
def test_hf_vllm_export_tiny_qwen3_moe(tmp_path, quant_cfg):
|
||||
tiny_model_dir = create_tiny_qwen3_moe_dir(tmp_path, num_hidden_layers=2)
|
||||
_test_hf_vllm_export(tmp_path, quant_cfg, tiny_model_dir)
|
||||
|
||||
|
||||
def test_resmooth_publishes_resident_offload_weights():
|
||||
class SharedInputs(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.embed = torch.nn.Embedding(4, 128)
|
||||
self.left = torch.nn.Linear(128, 4, bias=False)
|
||||
self.right = torch.nn.Linear(128, 4, bias=False)
|
||||
|
||||
def forward(self, ids):
|
||||
hidden = self.embed(ids)
|
||||
return self.left(hidden) + self.right(hidden)
|
||||
|
||||
model = SharedInputs().cuda().eval()
|
||||
config = deepcopy(mtq.INT4_AWQ_CFG)
|
||||
config["algorithm"] = "max"
|
||||
config["quant_cfg"].append({"quantizer_name": "*input_quantizer", "enable": True})
|
||||
mtq.quantize(model, config, lambda m: m(torch.ones(1, 2, device="cuda", dtype=torch.long)))
|
||||
expected = []
|
||||
|
||||
def leave_resident(owner, args, output):
|
||||
# Native onload may leave an enabled offload hook owning a resident CUDA weight.
|
||||
owner._hf_hook.pre_forward(owner)
|
||||
|
||||
for owner, scale in zip((model.left, model.right), (1.0, 3.0), strict=True):
|
||||
owner.input_quantizer.pre_quant_scale = torch.full((128,), scale, device="cuda")
|
||||
expected.append(owner.weight.detach().clone() * (scale / 2))
|
||||
master = {name: value.detach().cpu().clone() for name, value in owner.state_dict().items()}
|
||||
add_hook_to_module(
|
||||
owner, AlignDevicesHook(execution_device="cuda", offload=True, weights_map=master)
|
||||
)
|
||||
owner.register_forward_hook(leave_resident)
|
||||
_, changed = _resmooth_experts_for_export(model, None, inplace=True)
|
||||
assert changed == {"left.weight", "right.weight"}
|
||||
for owner, weight in zip((model.left, model.right), expected, strict=True):
|
||||
hook = owner._hf_hook
|
||||
hook.post_forward(owner, None)
|
||||
hook.pre_forward(owner)
|
||||
torch.testing.assert_close(owner.weight, weight)
|
||||
hook.post_forward(owner, None)
|
||||
|
||||
@@ -161,6 +161,42 @@ class TestSkipSoftmax:
|
||||
)
|
||||
torch.testing.assert_close(out_skip, out_dense, rtol=5e-2, atol=5e-2)
|
||||
|
||||
def test_new_threshold_reuses_compiled_kernels(self):
|
||||
"""Calibrated thresholds (scale_factor / seq_k) change every call; none may recompile."""
|
||||
import modelopt.torch.kernels.common.attention.triton_fa as tfa
|
||||
|
||||
jit_fns = (tfa._attn_fwd.fn, tfa._attn_bwd_dq, tfa._attn_bwd_dkdv)
|
||||
|
||||
def num_binaries():
|
||||
return sum(len(c[0]) for fn in jit_fns for c in fn.device_caches.values())
|
||||
|
||||
q, k, v, locs, lens = self._make_inputs(batch=1)
|
||||
q.requires_grad_(True)
|
||||
one = torch.ones(1, device="cuda", dtype=torch.int32)
|
||||
|
||||
def run(threshold):
|
||||
for measure in (False, True): # serving and calibration-counter launches
|
||||
attention(
|
||||
q[:1].detach(),
|
||||
k,
|
||||
v,
|
||||
locs,
|
||||
one,
|
||||
1,
|
||||
b_start_loc_k=locs,
|
||||
b_seq_len_k=lens,
|
||||
max_input_len_k=256,
|
||||
skip_softmax_threshold=threshold,
|
||||
measure_sparsity=measure,
|
||||
)
|
||||
attention(q, k, v, locs, lens, 256, skip_softmax_threshold=threshold).sum().backward()
|
||||
|
||||
run(0.1 / 256)
|
||||
compiled = num_binaries()
|
||||
for threshold in (0.1 / 257, 0.2 / 300):
|
||||
run(threshold)
|
||||
assert num_binaries() == compiled
|
||||
|
||||
|
||||
@pytest.mark.skipif(not TRITON_KERNEL_AVAILABLE, reason="Need CUDA + triton")
|
||||
class TestSkipSoftmaxVsPytorchRef:
|
||||
|
||||
@@ -85,7 +85,7 @@ def _export_with_megatron_exporter(source, quant_cfg_name, export_dir, rank, siz
|
||||
|
||||
def _export_with_bridge(source, quant_cfg_name, export_dir, rank, size):
|
||||
bridge, model, _ = _quantize(source, quant_cfg_name, size)
|
||||
bridge.save_hf_pretrained_modelopt(model, str(export_dir))
|
||||
bridge.save_hf_pretrained_modelopt(model, str(export_dir), source_path=str(source))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@@ -1184,8 +1184,10 @@ def _test_qkv_slicing_gqa_tp2(tmp_path, rank, size):
|
||||
"num_key_value_heads": num_query_groups,
|
||||
"torch_dtype": "bfloat16",
|
||||
}
|
||||
with open(tmp_path / "config.json", "w") as f:
|
||||
json.dump(pretrained_config, f)
|
||||
if rank == 0:
|
||||
with open(tmp_path / "config.json", "w") as f:
|
||||
json.dump(pretrained_config, f)
|
||||
torch.distributed.barrier()
|
||||
|
||||
export_dir = tmp_path / "export"
|
||||
export_mcore_gpt_to_hf(
|
||||
|
||||
@@ -62,6 +62,7 @@ from megatron.core.parallel_state import (
|
||||
destroy_model_parallel,
|
||||
get_data_parallel_group,
|
||||
get_expert_model_parallel_rank,
|
||||
get_expert_tensor_parallel_rank,
|
||||
get_pipeline_model_parallel_rank,
|
||||
get_tensor_model_parallel_group,
|
||||
get_tensor_model_parallel_rank,
|
||||
@@ -91,6 +92,7 @@ from modelopt.torch.quantization.plugins.megatron import (
|
||||
_has_swiglu_rows,
|
||||
_initialize_grouped_weight_quantizer_state,
|
||||
_MegatronParallelLinear,
|
||||
_MegatronTEGroupedColumnParallelLinear,
|
||||
_output_layer_extra_state_has_data,
|
||||
_output_layer_untied,
|
||||
_QuantMegatronMLP,
|
||||
@@ -1156,8 +1158,19 @@ def test_te_grouped_vs_sequential_default_amax(dist_workers_size_1, quant_cfg):
|
||||
)
|
||||
|
||||
|
||||
def _grouped_amax(linear, leaf, amax, value):
|
||||
"""``amax`` holding ``value``; per channel, scaled by each global output channel (exact in BF16)."""
|
||||
if leaf.axis is None or leaf.block_sizes or amax.numel() == 1:
|
||||
return torch.full_like(amax, value)
|
||||
first = 0
|
||||
if isinstance(linear, _MegatronTEGroupedColumnParallelLinear):
|
||||
first = amax.shape[0] * get_expert_tensor_parallel_rank()
|
||||
rows = torch.arange(first + 1, first + 1 + amax.shape[0], device=amax.device, dtype=amax.dtype)
|
||||
return rows.view(-1, *[1] * (amax.dim() - 1)) * 2 ** (value - 1)
|
||||
|
||||
|
||||
def _set_te_grouped_weight_quantizer_state(model, ep_rank, num_local_experts):
|
||||
"""Give every local expert distinct quantizer state derived from its global index."""
|
||||
"""Give every local expert distinct quantizer state derived from its global index (and rows)."""
|
||||
for linear in model.modules():
|
||||
if not isinstance(linear, _QuantMegatronTEGroupedLinear):
|
||||
continue
|
||||
@@ -1167,7 +1180,8 @@ def _set_te_grouped_weight_quantizer_state(model, ep_rank, num_local_experts):
|
||||
for leaf in leaves:
|
||||
amax = getattr(leaf, "_amax", None)
|
||||
if amax is not None:
|
||||
amax.fill_(1.0 + ep_rank * num_local_experts + local_expert_idx)
|
||||
value = 1.0 + ep_rank * num_local_experts + local_expert_idx
|
||||
amax.copy_(_grouped_amax(linear, leaf, amax, value))
|
||||
global_amax = getattr(leaf, "_global_amax", None)
|
||||
if global_amax is not None:
|
||||
global_amax.fill_(1.0 + ep_rank * num_local_experts + local_expert_idx)
|
||||
@@ -1187,7 +1201,8 @@ def _assert_te_grouped_weight_quantizer_state(model, expected_amax, expect_globa
|
||||
"TEGrouped per-expert weight quantizer amax was not restored"
|
||||
)
|
||||
checked += 1
|
||||
assert torch.equal(amax, torch.full_like(amax, expected_amax[local_expert_idx]))
|
||||
expected = _grouped_amax(linear, leaf, amax, expected_amax[local_expert_idx])
|
||||
assert torch.equal(amax, expected)
|
||||
global_amax = getattr(leaf, "_global_amax", None)
|
||||
if expect_global_amax:
|
||||
assert global_amax is not None, (
|
||||
@@ -1252,8 +1267,10 @@ def _test_te_grouped_sharded_state_dict_reshard_helper(
|
||||
save_etp_size=None,
|
||||
load_etp_size=None,
|
||||
override_modelopt_tp_group=False,
|
||||
gated=False,
|
||||
):
|
||||
"""Round-trip TEGroupedMLP amax through a topology change."""
|
||||
shape = {"activation_func": "swiglu"} if gated else {}
|
||||
num_experts = 4
|
||||
save_num_local_experts = num_experts // save_ep_size
|
||||
initialize_for_megatron(
|
||||
@@ -1271,6 +1288,7 @@ def _test_te_grouped_sharded_state_dict_reshard_helper(
|
||||
moe_grouped_gemm=True,
|
||||
transformer_impl="transformer_engine",
|
||||
num_moe_experts=num_experts,
|
||||
**shape,
|
||||
)
|
||||
forward = get_forward(source, batch_size=8)
|
||||
for module in source.modules():
|
||||
@@ -1302,8 +1320,17 @@ def _test_te_grouped_sharded_state_dict_reshard_helper(
|
||||
moe_grouped_gemm=True,
|
||||
transformer_impl="transformer_engine",
|
||||
num_moe_experts=num_experts,
|
||||
**shape,
|
||||
)
|
||||
# Megatron-Bridge restores the modelopt_state into a model whose weights are not loaded yet.
|
||||
for name, param in target.named_parameters():
|
||||
if re.search(r"\.experts\.linear_fc\d\.weight\d+$", name):
|
||||
param.data.fill_(float("nan"))
|
||||
target_models = [target]
|
||||
if gated:
|
||||
with pytest.raises(ValueError, match="gated grouped experts"):
|
||||
restore_sharded_modelopt_state(target_models, checkpoint_path)
|
||||
return
|
||||
restore_sharded_modelopt_state(target_models, checkpoint_path)
|
||||
target = target_models[0]
|
||||
if override_modelopt_tp_group:
|
||||
@@ -1337,6 +1364,9 @@ def _test_te_grouped_sharded_state_dict_reshard_helper(
|
||||
pytest.param(mtq.NVFP4_DEFAULT_CFG, False, 1, 1, 1, 2, id="nvfp4-ep-upsize"),
|
||||
pytest.param(mtq.NVFP4_DEFAULT_CFG, False, 1, 1, 2, 1, id="nvfp4-tp-upsize"),
|
||||
pytest.param(mtq.NVFP4_DEFAULT_CFG, False, 2, 1, 1, 1, id="nvfp4-tp-downsize"),
|
||||
# Per-channel amax at a TP change: fewer rows than the weight's, then more.
|
||||
pytest.param(mtq.INT8_DEFAULT_CFG, False, 2, 1, 1, 1, id="int8-tp-downsize"),
|
||||
pytest.param(mtq.FP8_PER_CHANNEL_PER_TOKEN_CFG, False, 1, 1, 2, 1, id="fp8-pc-tp-upsize"),
|
||||
pytest.param(
|
||||
mtq.NVFP4_W4A4_WEIGHT_MSE_FP8_SWEEP_CFG,
|
||||
True,
|
||||
@@ -1381,6 +1411,23 @@ def test_te_grouped_sharded_state_dict_reshard(
|
||||
)
|
||||
|
||||
|
||||
def test_te_grouped_gated_per_channel_reshard_rejected(dist_workers_size_2, tmp_path):
|
||||
"""Gated experts' per-channel amax doesn't follow their weight's gate and up rows to another TP size."""
|
||||
dist_workers_size_2.run(
|
||||
partial(
|
||||
_test_te_grouped_sharded_state_dict_reshard_helper,
|
||||
2,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
mtq.INT8_DEFAULT_CFG,
|
||||
False,
|
||||
tmp_path,
|
||||
gated=True,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("override_modelopt_tp_group", [False, True])
|
||||
def test_te_grouped_sharded_state_dict_combined_tp_ep(
|
||||
dist_workers_size_4, tmp_path, override_modelopt_tp_group
|
||||
|
||||
@@ -24,6 +24,7 @@ from _test_utils.torch.quantization.quantize_common import quantize_model_and_fo
|
||||
|
||||
import modelopt.torch.opt as mto
|
||||
import modelopt.torch.quantization as mtq
|
||||
from modelopt.torch.quantization.conversion import set_quantizer_attributes_partial
|
||||
from modelopt.torch.quantization.extensions import get_cuda_ext_mx
|
||||
from modelopt.torch.quantization.nn import GroupedQuantizer, QuantModule
|
||||
|
||||
@@ -118,7 +119,8 @@ def test_quantize(model_cls, config):
|
||||
quantize_model_and_forward(model, config, calib_data)
|
||||
|
||||
|
||||
def test_grouped_post_restore_preserves_weight_amax():
|
||||
@pytest.mark.parametrize("pinned_per_channel", [False, True])
|
||||
def test_grouped_post_restore_preserves_weight_amax(pinned_per_channel):
|
||||
"""Grouped restore must not clear calibrated state for non-representative experts."""
|
||||
model = TEGroupedLinear().cuda()
|
||||
with torch.no_grad():
|
||||
@@ -126,10 +128,16 @@ def test_grouped_post_restore_preserves_weight_amax():
|
||||
getattr(model.net, f"weight{index}").fill_(0.25 + index)
|
||||
|
||||
data = model.get_input().cuda()
|
||||
mtq.quantize(model, copy.deepcopy(mtq.FP8_DEFAULT_CFG), lambda module: module(data))
|
||||
config = mtq.INT8_DEFAULT_CFG if pinned_per_channel else mtq.FP8_DEFAULT_CFG
|
||||
mtq.quantize(model, copy.deepcopy(config), lambda module: module(data))
|
||||
|
||||
quantizers = model.net.weight_quantizer
|
||||
assert isinstance(quantizers, GroupedQuantizer)
|
||||
if pinned_per_channel:
|
||||
# A per-channel quantizer's one-entry amax (e.g. a constant_amax pin) fits every channel.
|
||||
for index, quantizer in enumerate(quantizers):
|
||||
quantizer.reset_amax()
|
||||
quantizer.amax = torch.tensor(2.0 + index, device="cuda")
|
||||
before_restore = [quantizer.amax.clone() for quantizer in quantizers]
|
||||
|
||||
model.net.modelopt_post_restore()
|
||||
@@ -138,6 +146,56 @@ def test_grouped_post_restore_preserves_weight_amax():
|
||||
torch.testing.assert_close(quantizer.amax, expected)
|
||||
|
||||
|
||||
def test_grouped_post_restore_resizes_per_channel_amax_off_cuda():
|
||||
"""A per-channel amax restored at another TP size takes the weight's channels on any device."""
|
||||
model = TEGroupedLinear().cuda()
|
||||
data = model.get_input().cuda()
|
||||
mtq.quantize(model, copy.deepcopy(mtq.INT8_DEFAULT_CFG), lambda module: module(data))
|
||||
model.cpu()
|
||||
for quantizer in model.net.weight_quantizer:
|
||||
quantizer.reset_amax()
|
||||
quantizer.amax = torch.ones(model.net.weight0.shape[0] // 2, 1) # saved at twice the TP
|
||||
|
||||
# As Megatron's sharded extra-state restore runs it.
|
||||
model.net._modelopt_resharding_restore = True
|
||||
model.net.modelopt_post_restore()
|
||||
|
||||
for quantizer in model.net.weight_quantizer:
|
||||
assert quantizer.amax.shape == (model.net.weight0.shape[0], 1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"case", ["disable", "disable_quant", "use_constant_amax", "fp8_other_axis", "oversized"]
|
||||
)
|
||||
def test_grouped_restore_keeps_disabled_quantizer_amax(case):
|
||||
"""A saved amax the weight still takes (or doesn't use) keeps its shape on an unchanged restore."""
|
||||
model_quant, model_ref = TEGroupedLinear().cuda(), TEGroupedLinear().cuda()
|
||||
data = model_quant.get_input().cuda()
|
||||
config = mtq.FP8_PER_CHANNEL_PER_TOKEN_CFG if case == "fp8_other_axis" else mtq.INT8_DEFAULT_CFG
|
||||
mtq.quantize(model_quant, copy.deepcopy(config), lambda module: module(data))
|
||||
if case == "disable_quant":
|
||||
for quantizer in model_quant.net.weight_quantizer:
|
||||
quantizer.disable_quant()
|
||||
if case == "oversized":
|
||||
# The INT8 kernel indexes only the first entries of a larger per-channel amax.
|
||||
for quantizer in model_quant.net.weight_quantizer:
|
||||
quantizer.reset_amax()
|
||||
quantizer.amax = torch.ones(2 * model_quant.net.weight0.shape[0], 1, device="cuda")
|
||||
else:
|
||||
# The configured axis no longer describes the saved amax, which the kernels still use.
|
||||
attributes = {"axis": 1}
|
||||
if case == "disable":
|
||||
attributes["enable"] = False
|
||||
elif case == "use_constant_amax":
|
||||
attributes["use_constant_amax"] = True
|
||||
set_quantizer_attributes_partial(model_quant, "*weight_quantizer*", attributes)
|
||||
|
||||
mto.restore_from_modelopt_state(model_ref, mto.modelopt_state(model_quant))
|
||||
model_ref.load_state_dict(model_quant.state_dict())
|
||||
for restored, saved in zip(model_ref.net.weight_quantizer, model_quant.net.weight_quantizer):
|
||||
assert torch.equal(restored.amax, saved.amax)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("share_weight_quantizer", [False, True])
|
||||
def test_fold_weight_grouped_linear(share_weight_quantizer):
|
||||
model = TEGroupedLinear().cuda()
|
||||
|
||||
+90
-3
@@ -13,13 +13,26 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import copy
|
||||
from functools import partial
|
||||
|
||||
from _test_utils.torch.megatron.models import MegatronModel
|
||||
from _test_utils.torch.megatron.utils import initialize_for_megatron, sharded_state_dict_test_helper
|
||||
import pytest
|
||||
import torch
|
||||
from _test_utils.torch.megatron.models import MegatronModel, get_mcore_gpt_model
|
||||
from _test_utils.torch.megatron.utils import (
|
||||
get_forward,
|
||||
initialize_for_megatron,
|
||||
load_distributed_checkpoint,
|
||||
save_distributed_checkpoint,
|
||||
sharded_state_dict_test_helper,
|
||||
)
|
||||
from _test_utils.torch.sparsity.utils import sample_subnet_with_sparsity
|
||||
from megatron.core.parallel_state import destroy_model_parallel, get_tensor_model_parallel_group
|
||||
|
||||
from modelopt.torch.opt.conversion import apply_mode
|
||||
import modelopt.torch.quantization as mtq
|
||||
import modelopt.torch.sparsity as mts
|
||||
from modelopt.torch.opt.conversion import ModeloptStateManager, apply_mode
|
||||
from modelopt.torch.opt.plugins import restore_sharded_modelopt_state, save_sharded_modelopt_state
|
||||
|
||||
|
||||
def _test_sharded_state_dict(tmp_path, rank, size):
|
||||
@@ -38,3 +51,77 @@ def _test_sharded_state_dict(tmp_path, rank, size):
|
||||
|
||||
def test_sharded_state_dict(dist_workers, tmp_path):
|
||||
dist_workers.run(partial(_test_sharded_state_dict, tmp_path))
|
||||
|
||||
|
||||
def _fc1_masks(model):
|
||||
return {
|
||||
name: module._weight_mask
|
||||
for name, module in model.named_modules()
|
||||
if name.endswith("mlp.linear_fc1")
|
||||
}
|
||||
|
||||
|
||||
def _test_swiglu_weight_mask_tp_reshard(tmp_path, legacy, rank, size):
|
||||
# The old layout loads right at the same TP size only. Sparsity and quantization stacked at
|
||||
# TP > 1 also save the mask without its TP sharding (OMNIML-6311), so that case uses TP=1.
|
||||
save_tp = 1 if legacy else 2
|
||||
initialize_for_megatron(tensor_model_parallel_size=save_tp, seed=1234)
|
||||
source = get_mcore_gpt_model(tensor_model_parallel_size=save_tp).cuda()
|
||||
mts.sparsify(source, "sparse_magnitude")
|
||||
if legacy:
|
||||
# A later mode's replay converts the MLP again, which must keep the restored mask layout.
|
||||
mtq.quantize(source, copy.deepcopy(mtq.FP8_DEFAULT_CFG), get_forward(source))
|
||||
# Megatron's order: all gate rows, then all up rows (each rank holds its own gate and up rows).
|
||||
expected = {}
|
||||
for name, mask in _fc1_masks(source).items():
|
||||
shards = [torch.empty_like(mask) for _ in range(save_tp)]
|
||||
torch.distributed.all_gather(shards, mask, group=get_tensor_model_parallel_group())
|
||||
expected[name] = torch.cat(
|
||||
[s.chunk(2)[0] for s in shards] + [s.chunk(2)[1] for s in shards]
|
||||
)
|
||||
if legacy:
|
||||
# Saved as before: one key for the whole mask, and no record of the SwiGLU layout.
|
||||
for _, _, metadata in ModeloptStateManager(source).modes_with_states():
|
||||
metadata.pop("megatron_swiglu_weight_mask", None)
|
||||
for module in source.modules():
|
||||
if hasattr(module, "_swiglu_weight_mask"):
|
||||
module._swiglu_weight_mask = False
|
||||
save_distributed_checkpoint(tmp_path, source)
|
||||
save_sharded_modelopt_state([source], tmp_path)
|
||||
torch.distributed.barrier()
|
||||
del source
|
||||
destroy_model_parallel()
|
||||
|
||||
initialize_for_megatron(tensor_model_parallel_size=1, seed=1234)
|
||||
target = get_mcore_gpt_model(tensor_model_parallel_size=1).cuda()
|
||||
restore_sharded_modelopt_state([target], tmp_path)
|
||||
target = load_distributed_checkpoint(tmp_path, target)
|
||||
masks = _fc1_masks(target)
|
||||
assert masks.keys() == expected.keys()
|
||||
for name, mask in masks.items():
|
||||
assert torch.equal(mask, expected[name])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("legacy", [False, True])
|
||||
def test_swiglu_weight_mask_tp_reshard(dist_workers_size_2, tmp_path, legacy):
|
||||
"""A gated linear_fc1's mask loads on its rows at another TP size; one saved before still loads."""
|
||||
dist_workers_size_2.run(partial(_test_swiglu_weight_mask_tp_reshard, tmp_path, legacy))
|
||||
|
||||
|
||||
def _test_resparsify_after_legacy_export(rank, size):
|
||||
initialize_for_megatron(seed=1234)
|
||||
model = get_mcore_gpt_model().cuda()
|
||||
mts.sparsify(model, "sparse_magnitude")
|
||||
# As restored from a checkpoint saved before the SwiGLU mask layout.
|
||||
for module in model.modules():
|
||||
if hasattr(module, "_swiglu_weight_mask"):
|
||||
module._swiglu_weight_mask = False
|
||||
mts.export(model)
|
||||
mts.sparsify(model, "sparse_magnitude")
|
||||
layouts = [m._swiglu_weight_mask for m in model.modules() if hasattr(m, "_swiglu_weight_mask")]
|
||||
assert layouts and all(layouts)
|
||||
|
||||
|
||||
def test_resparsify_after_legacy_export(dist_workers_size_2):
|
||||
"""Sparsifying again after the final export saves masks in the layout its metadata records."""
|
||||
dist_workers_size_2.run(_test_resparsify_after_legacy_export)
|
||||
|
||||
@@ -224,6 +224,14 @@ def test_context_parallelism_is_rejected(main_mod, stub_tokenizers):
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("mode", "seq_len"), [("streaming", 128), ("offline", 129)])
|
||||
def test_dflash_context_parallel_needs_divisible_offline_data(main_mod, mode, seq_len):
|
||||
recipe = types.SimpleNamespace(data=types.SimpleNamespace(mode=mode))
|
||||
args = types.SimpleNamespace(cp_size=2, training_seq_len=seq_len)
|
||||
with pytest.raises(ValueError, match="cp_size"):
|
||||
main_mod.check_dflash_context_parallel(None, recipe, args)
|
||||
|
||||
|
||||
def test_caller_supplied_base_tokenizer_is_used(main_mod, monkeypatch):
|
||||
"""The fresh path already holds the base tokenizer; it must not be re-fetched."""
|
||||
calls = []
|
||||
|
||||
@@ -185,9 +185,13 @@ def test_a_sharded_model_is_refused_on_every_rank(tmp_path, cpu_dist_workers):
|
||||
def test_an_offloaded_model_is_refused_before_any_converter_runs(converter, monkeypatch, tmp_path):
|
||||
# A model with offload hooks; export_hf_checkpoint takes the offloaded export for it.
|
||||
monkeypatch.setattr(
|
||||
"modelopt.torch.export.unified_export_hf.has_accelerate_offload", lambda model: True
|
||||
"modelopt.torch.export.unified_export_hf.has_accelerate_offload",
|
||||
lambda model, **kwargs: True,
|
||||
)
|
||||
model = _quantize(get_tiny_llama())
|
||||
quantizers = {
|
||||
name: owner for name, owner in model.named_modules() if isinstance(owner, TensorQuantizer)
|
||||
}
|
||||
|
||||
with pytest.raises(NotImplementedError, match="offloaded"):
|
||||
_export_transformers_checkpoint(model)
|
||||
@@ -197,6 +201,7 @@ def test_an_offloaded_model_is_refused_before_any_converter_runs(converter, monk
|
||||
):
|
||||
export_hf_checkpoint(model, export_dir=tmp_path)
|
||||
|
||||
assert all(model.get_submodule(name) is owner for name, owner in quantizers.items())
|
||||
converter.assert_not_called()
|
||||
assert not any(tmp_path.iterdir())
|
||||
|
||||
|
||||
@@ -321,12 +321,13 @@ def test_export_mcore_gpt_to_hf_passes_kv_cache_clamping_option(
|
||||
|
||||
monkeypatch.setattr(unified_export_megatron, "GPTModelExporter", FakeExporter)
|
||||
|
||||
unified_export_megatron.export_mcore_gpt_to_hf(
|
||||
object(),
|
||||
tmp_path,
|
||||
export_dir=tmp_path,
|
||||
clamp_kv_cache_scales=clamp_kv_cache_scales,
|
||||
)
|
||||
with pytest.warns(DeprecationWarning, match="export_mcore_gpt_to_hf is deprecated"):
|
||||
unified_export_megatron.export_mcore_gpt_to_hf(
|
||||
object(),
|
||||
tmp_path,
|
||||
export_dir=tmp_path,
|
||||
clamp_kv_cache_scales=clamp_kv_cache_scales,
|
||||
)
|
||||
|
||||
assert exporter_args["clamp_kv_cache_scales"] is clamp_kv_cache_scales
|
||||
|
||||
|
||||
@@ -1421,7 +1421,9 @@ def test_an_expert_parallel_export_it_cannot_write_is_refused_before_folding(
|
||||
mtq.quantize(model, mtq.FP8_DEFAULT_CFG, lambda m: m(torch.randn(2, 16)))
|
||||
set_distribution_plan(model, plan)
|
||||
if offloaded:
|
||||
monkeypatch.setattr(unified_export_hf, "has_accelerate_offload", lambda model: True)
|
||||
monkeypatch.setattr(
|
||||
unified_export_hf, "has_accelerate_offload", lambda model, **kwargs: True
|
||||
)
|
||||
before = {k: v.clone() for k, v in model.state_dict().items()}
|
||||
|
||||
with pytest.raises(NotImplementedError, match=refusal):
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
|
||||
import copy
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
import warnings
|
||||
from contextlib import nullcontext
|
||||
from types import SimpleNamespace
|
||||
@@ -26,6 +28,8 @@ from _test_utils.torch.distributed.utils import bounded_collectives
|
||||
from _test_utils.torch.quantization.models import SimpleConv, SimpleConvLinear, SimpleLinear
|
||||
from torch.distributed.device_mesh import init_device_mesh
|
||||
from torch.distributed.fsdp import fully_shard
|
||||
from torch.distributed.tensor import Replicate
|
||||
from torch.distributed.tensor.parallel import ColwiseParallel, RowwiseParallel, parallelize_module
|
||||
|
||||
import modelopt.torch.opt as mto
|
||||
import modelopt.torch.quantization as mtq
|
||||
@@ -33,7 +37,7 @@ import modelopt.torch.quantization.model_quant as model_quant
|
||||
from modelopt.torch.quantization import model_calib
|
||||
from modelopt.torch.quantization._auto_quantize_cost import (
|
||||
EXCLUDED_MODULE_NAME_PATTERNS_KEY,
|
||||
_get_module_weight_numel,
|
||||
_get_module_weights,
|
||||
get_auto_quantize_cost_model,
|
||||
infer_active_moe_expert_ratio,
|
||||
)
|
||||
@@ -47,11 +51,17 @@ from modelopt.torch.quantization.algorithms import (
|
||||
_get_kl_div_loss,
|
||||
_get_log_prob,
|
||||
_module_search_space_signature,
|
||||
_save_together,
|
||||
estimate_quant_compression,
|
||||
)
|
||||
from modelopt.torch.quantization.config import _base_disable_all, _default_disabled_quantizer_cfg
|
||||
from modelopt.torch.utils import safe_load, safe_save
|
||||
from modelopt.torch.utils.distributed import DistributedProcessGroup, ParallelState
|
||||
from modelopt.torch.utils.distributed import (
|
||||
DistributedProcessGroup,
|
||||
DistributionPlan,
|
||||
ParallelState,
|
||||
set_distribution_plan,
|
||||
)
|
||||
|
||||
|
||||
class _AttentionLayer(torch.nn.Module):
|
||||
@@ -294,9 +304,10 @@ def test_auto_quantize_cost_model_excludes_module_name_patterns():
|
||||
)
|
||||
|
||||
|
||||
def test_active_moe_cost_model_counts_fused_experts_without_weight():
|
||||
@pytest.mark.parametrize("first_proj", ["gate_up_proj", "up_proj"])
|
||||
def test_active_moe_cost_model_counts_fused_experts_without_weight(first_proj):
|
||||
fused_experts = torch.nn.Module()
|
||||
fused_experts.gate_up_proj = torch.nn.Parameter(torch.empty(2, 3, 5))
|
||||
setattr(fused_experts, first_proj, torch.nn.Parameter(torch.empty(2, 3, 5)))
|
||||
fused_experts.down_proj = torch.nn.Parameter(torch.empty(2, 5, 3))
|
||||
cost_model = get_auto_quantize_cost_model("active_moe")
|
||||
cost_constraints = {
|
||||
@@ -304,10 +315,12 @@ def test_active_moe_cost_model_counts_fused_experts_without_weight():
|
||||
EXCLUDED_MODULE_NAME_PATTERNS_KEY: ["*visual*"],
|
||||
}
|
||||
|
||||
# Fused experts expose no `.weight`; their size is summed across all parameters.
|
||||
assert _get_module_weight_numel(fused_experts) == (
|
||||
fused_experts.gate_up_proj.numel() + fused_experts.down_proj.numel()
|
||||
)
|
||||
# Fused experts expose no `.weight`; their weights are both projections,
|
||||
# gated (gate_up_proj) or not (up_proj).
|
||||
assert _get_module_weights(fused_experts) == [
|
||||
getattr(fused_experts, first_proj),
|
||||
fused_experts.down_proj,
|
||||
]
|
||||
# Routed MoE experts are scaled by the active-expert ratio; excluded modules drop to zero.
|
||||
assert cost_model.module_cost_weight(["layers.0.mlp.experts"], cost_constraints) == 0.25
|
||||
assert cost_model.module_cost_weight(["model.visual.blocks.0.attn.qkv"], cost_constraints) == 0
|
||||
@@ -933,6 +946,13 @@ def test_format_shards_merge_into_the_unsharded_search(tmp_path, monkeypatch, me
|
||||
search(fewer, (1, 2), score_steps=1)
|
||||
with pytest.raises(ValueError, match="num_score_steps"):
|
||||
model_quant.merge_auto_quantize_checkpoints([shards[0], fewer], str(tmp_path / "x.pth"))
|
||||
# A shard another rank wrote holds that rank's calibration, e.g. its own experts'.
|
||||
other_rank = tmp_path / "other_rank.pth"
|
||||
safe_save({**safe_load(shards[1]), "checkpoint_rank": 1}, other_rank)
|
||||
with pytest.raises(ValueError, match=r"search setups \(checkpoint_rank\)"):
|
||||
model_quant.merge_auto_quantize_checkpoints(
|
||||
[shards[0], other_rank], str(tmp_path / "w.pth")
|
||||
)
|
||||
# So are shards that recorded no counts, as earlier versions saved them.
|
||||
unlabeled = [tmp_path / f"unlabeled{i}.pth" for i in range(2)]
|
||||
for shard, path in zip(shards, unlabeled):
|
||||
@@ -941,6 +961,16 @@ def test_format_shards_merge_into_the_unsharded_search(tmp_path, monkeypatch, me
|
||||
safe_save(state, path)
|
||||
with pytest.raises(ValueError, match="num_calib_steps"):
|
||||
model_quant.merge_auto_quantize_checkpoints(unlabeled, str(tmp_path / "y.pth"))
|
||||
# Shards that price a group differently, e.g. one saved before a cost fix, are refused.
|
||||
for key, value in (("costs", None), ("weight_size", 1.0)):
|
||||
skewed = safe_load(shards[1])
|
||||
stats = next(iter(skewed["candidate_stats"].values()))
|
||||
stats[key] = [cost / 2 for cost in stats["costs"]] if value is None else value
|
||||
safe_save(skewed, tmp_path / f"skewed_{key}.pth")
|
||||
with pytest.raises(ValueError, match="different costs"):
|
||||
model_quant.merge_auto_quantize_shards(
|
||||
[safe_load(shards[0]), safe_load(tmp_path / f"skewed_{key}.pth")]
|
||||
)
|
||||
# A shard resumes its calibration and scores only under the counts that produced them.
|
||||
interrupted = safe_load(shards[0])
|
||||
interrupted["candidate_stats"] = {} # as saved between calibration and scoring
|
||||
@@ -1006,6 +1036,31 @@ def test_format_shards_merge_into_the_unsharded_search(tmp_path, monkeypatch, me
|
||||
model_quant.merge_auto_quantize_checkpoints(shards, str(merged))
|
||||
assert not merged.exists() # so the merge can be retried
|
||||
model_quant.merge_auto_quantize_checkpoints(list(reversed(shards)), str(merged))
|
||||
# A rerun of shard 1 scores alike, but a merge with it holds another run's calibration.
|
||||
search(tmp_path / "rerun1.pth", (1, 2))
|
||||
model_quant.merge_auto_quantize_checkpoints(
|
||||
[shards[0], tmp_path / "rerun1.pth"], str(tmp_path / "rerun.pth")
|
||||
)
|
||||
assert safe_load(tmp_path / "rerun.pth")["search_id"] != safe_load(merged)["search_id"]
|
||||
# A shard that records no run, as none this release writes, is refused, not merged as "None".
|
||||
unrun = {k: v for k, v in safe_load(tmp_path / "rerun1.pth").items() if k != "search_id"}
|
||||
safe_save(unrun, tmp_path / "unrun1.pth")
|
||||
with pytest.raises(ValueError, match="only part of its provenance"):
|
||||
model_quant.merge_auto_quantize_checkpoints(
|
||||
[shards[0], tmp_path / "unrun1.pth"], str(tmp_path / "unrun.pth")
|
||||
)
|
||||
# Shards 0.49 wrote, recording no writer or run, merge into a file recording no run either, so
|
||||
# its resume takes a new search ID, not one every such merge would share.
|
||||
legacy = [tmp_path / f"legacy{index}.pth" for index in range(len(shards))]
|
||||
for shard, path in zip(shards, legacy):
|
||||
state = safe_load(shard)
|
||||
for key in ("checkpoint_rank", "checkpoint_world_size", "distribution_plan"):
|
||||
state.pop(key)
|
||||
for key in ("parallel_layout", "search_id"):
|
||||
state.pop(key)
|
||||
safe_save(state, path)
|
||||
model_quant.merge_auto_quantize_checkpoints(legacy, str(tmp_path / "legacy.pth"))
|
||||
assert safe_load(tmp_path / "legacy.pth")["search_id"] is None
|
||||
with pytest.raises(ValueError, match="format shard"):
|
||||
search(shards[0])
|
||||
_, state = search(merged, score_steps=1) # unsharded, the counts may change to re-solve
|
||||
@@ -1185,6 +1240,523 @@ def test_scores_of_a_module_one_rank_never_runs(cpu_dist_workers):
|
||||
cpu_dist_workers.run(_test_scores_of_a_module_one_rank_never_runs)
|
||||
|
||||
|
||||
def _test_resume_from_another_point_on_one_rank(rank, size, directory, rank1_file):
|
||||
torch.manual_seed(rank)
|
||||
data_loader = [SimpleLinear().get_input() for _ in range(2)]
|
||||
|
||||
def search(checkpoint=directory, model=None):
|
||||
mtq.auto_quantize(
|
||||
SimpleLinear() if model is None else model,
|
||||
constraints={"effective_bits": 11.0},
|
||||
quantization_formats=[mtq.INT8_SMOOTHQUANT_CFG],
|
||||
data_loader=data_loader,
|
||||
forward_step=lambda model, batch: model(batch),
|
||||
loss_func=lambda output, data: output.sum(),
|
||||
num_calib_steps=2,
|
||||
num_score_steps=2,
|
||||
# aumann_shapley's own entry check passes the model, and so its plan, on.
|
||||
method=(
|
||||
"aumann_shapley" if rank1_file in ("other_scoring", "under_another_plan") else None
|
||||
),
|
||||
checkpoint=str(checkpoint),
|
||||
)
|
||||
|
||||
rng = torch.get_rng_state()
|
||||
search()
|
||||
# The same search again: only the search's ID tells them apart.
|
||||
if rank1_file in ("other_run", "other_run_no_ids"):
|
||||
torch.set_rng_state(rng)
|
||||
search(directory / "other_run")
|
||||
if rank1_file == "legacy_other_calibration": # the other on new data
|
||||
search(directory / "other_run")
|
||||
if rank1_file.startswith("legacy_"): # files that record no run
|
||||
for path in directory.glob(f"**/rank{rank}.pth"):
|
||||
state = safe_load(path)
|
||||
for key in ("checkpoint_rank", "checkpoint_world_size", "distribution_plan"):
|
||||
state.pop(key)
|
||||
for key in ("parallel_layout", "search_id"):
|
||||
state.pop(key)
|
||||
safe_save({**state, "candidate_stats": {}}, path) # calibrated, not yet scored
|
||||
if rank1_file == "of_a_larger_run": # ranks 0 and 1 of a run of four, no plan recorded
|
||||
path = directory / f"rank{rank}.pth"
|
||||
safe_save({**safe_load(path), "checkpoint_world_size": 4}, path)
|
||||
elif rank1_file == "under_another_plan": # e.g. an expert-parallel run's
|
||||
path = directory / f"rank{rank}.pth"
|
||||
safe_save({**safe_load(path), "distribution_plan": (size, size, "replicate")}, path)
|
||||
elif rank1_file == "under_no_plan":
|
||||
pass # resumed under a plan, below
|
||||
elif rank1_file == "under_other_groups": # its groups' sizes, but one module's shard another
|
||||
path = directory / f"rank{rank}.pth"
|
||||
layout = safe_load(path)["parallel_layout"]
|
||||
# Module by module, which ranks each group holds, in order, not only how many.
|
||||
assert [groups for _, groups in layout] == [(("dp", (0, 1)),)] * len(layout)
|
||||
name, _ = layout[0]
|
||||
other = ((name, (("dp", (1, 0)),)), *layout[1:])
|
||||
safe_save({**safe_load(path), "parallel_layout": other}, path)
|
||||
elif rank == 1:
|
||||
path = directory / "rank1.pth"
|
||||
if rank1_file == "missing":
|
||||
path.unlink()
|
||||
elif rank1_file == "truncated": # by an interrupted save
|
||||
path.write_bytes(path.read_bytes()[:64])
|
||||
elif rank1_file in ("other_run", "other_run_no_ids", "legacy_other_calibration"):
|
||||
(directory / "other_run" / "rank1.pth").replace(path)
|
||||
elif rank1_file == "bad_payload": # readable, missing one quantizer's state
|
||||
state = safe_load(path)
|
||||
for saved in state["quantizer_states"].values():
|
||||
del saved["metadata"][next(iter(saved["metadata"]))]
|
||||
safe_save(state, path)
|
||||
elif (
|
||||
rank1_file == "missing_tensors"
|
||||
): # readable, one quantizer's tensors gone, not its state
|
||||
state = safe_load(path)
|
||||
for saved in state["quantizer_states"].values():
|
||||
del saved["state_dict"][next(n for n, t in saved["state_dict"].items() if t)]
|
||||
safe_save(state, path)
|
||||
elif rank1_file == "of_rank_0": # another rank's, which can hold that rank's experts
|
||||
path.write_bytes((directory / "rank0.pth").read_bytes())
|
||||
elif rank1_file == "of_rank_0_stripped": # its writer and run's size gone, as no run writes
|
||||
state = safe_load(directory / "rank0.pth")
|
||||
for key in ("checkpoint_rank", "checkpoint_world_size"):
|
||||
del state[key]
|
||||
safe_save(state, path)
|
||||
elif rank1_file == "legacy_other_metadata": # the same tensors, another quantizer state
|
||||
state = safe_load(path)
|
||||
for saved in state["quantizer_states"].values():
|
||||
quantizer = saved["metadata"][next(iter(saved["metadata"]))]
|
||||
quantizer["_unsigned"] = not quantizer["_unsigned"]
|
||||
safe_save(state, path)
|
||||
else:
|
||||
state = safe_load(path)
|
||||
if rank1_file == "older": # saved after calibrating, before scoring
|
||||
state["candidate_stats"] = {}
|
||||
elif rank1_file == "other_setup": # from a search whose groups resolved otherwise
|
||||
state["resolved_search_setup_signature"] = ()
|
||||
elif rank1_file == "other_scoring": # at the same progress, with other path settings
|
||||
state["scoring_signature"] = {"num_path_nodes": -1}
|
||||
else: # at the same progress and setup, scored on other data
|
||||
for stats in state["candidate_stats"].values():
|
||||
stats["scores"] = [None if s is None else s + 1.0 for s in stats["scores"]]
|
||||
safe_save(state, path)
|
||||
if rank1_file == "other_run_no_ids": # and neither rank's file records its run
|
||||
path = directory / f"rank{rank}.pth"
|
||||
safe_save({k: v for k, v in safe_load(path).items() if k != "search_id"}, path)
|
||||
# Rank 1 alone would calibrate or score again, refuse its setup or fail to load its file, while
|
||||
# rank 0 went on: every rank raises instead, rank 0 naming rank 1's failure to load.
|
||||
if rank1_file == "truncated":
|
||||
error, match = (
|
||||
(RuntimeError, "rank 1 failed to compute") if rank == 0 else (Exception, None)
|
||||
)
|
||||
elif rank1_file == "of_a_larger_run":
|
||||
error, match = ValueError, "written by a run of 4 ranks"
|
||||
elif rank1_file in ("under_another_plan", "under_no_plan"):
|
||||
error, match = ValueError, "written under"
|
||||
elif rank1_file in ("of_rank_0", "of_rank_0_stripped"):
|
||||
error, match = (
|
||||
(RuntimeError, "rank 1 failed to compute AutoQuantize checkpoint")
|
||||
if rank == 0
|
||||
else (
|
||||
ValueError,
|
||||
"written by rank 0" if rank1_file == "of_rank_0" else "only part of its provenance",
|
||||
)
|
||||
)
|
||||
elif rank1_file == "under_other_groups":
|
||||
error, match = ValueError, "parallel groups"
|
||||
elif rank1_file in ("legacy_other_calibration", "legacy_other_metadata"):
|
||||
error, match = ValueError, "hold other calibrations"
|
||||
elif rank1_file in ("bad_payload", "missing_tensors"): # refused as restored, on every rank
|
||||
error, match = (
|
||||
(RuntimeError, "Extra keys")
|
||||
if rank == 1 and rank1_file == "bad_payload"
|
||||
else (ValueError, "holds no tensors")
|
||||
if rank == 1
|
||||
else (RuntimeError, "rank 1 failed to compute AutoQuantize restored calibration")
|
||||
)
|
||||
elif rank1_file == "other_run_no_ids":
|
||||
error, match = ValueError, "only part of its provenance"
|
||||
else:
|
||||
error, match = ValueError, "checkpoint at the same progress"
|
||||
model = SimpleLinear()
|
||||
if rank1_file == "under_no_plan":
|
||||
set_distribution_plan(model, DistributionPlan(size))
|
||||
with bounded_collectives(), pytest.raises(error, match=match):
|
||||
search(model=model)
|
||||
# Refused once the search converted the model, which it hands back to search again.
|
||||
converted = (
|
||||
"under_other_groups",
|
||||
"legacy_other_calibration",
|
||||
"legacy_other_metadata",
|
||||
"bad_payload",
|
||||
"missing_tensors",
|
||||
)
|
||||
if rank1_file in converted:
|
||||
with bounded_collectives():
|
||||
search(directory / "fresh", model=model)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"rank1_file",
|
||||
[
|
||||
"missing",
|
||||
"older",
|
||||
"other_setup",
|
||||
"other_scoring",
|
||||
"other_scores",
|
||||
"other_run",
|
||||
"other_run_no_ids",
|
||||
"of_rank_0",
|
||||
"of_rank_0_stripped",
|
||||
"of_a_larger_run",
|
||||
"under_another_plan",
|
||||
"under_no_plan",
|
||||
"under_other_groups",
|
||||
"bad_payload",
|
||||
"missing_tensors",
|
||||
"legacy_other_calibration",
|
||||
"legacy_other_metadata",
|
||||
"truncated",
|
||||
],
|
||||
)
|
||||
def test_resume_from_another_point_on_one_rank_raises_on_every_rank(
|
||||
cpu_dist_workers, tmp_path, rank1_file
|
||||
):
|
||||
cpu_dist_workers.run(
|
||||
_test_resume_from_another_point_on_one_rank, directory=tmp_path, rank1_file=rank1_file
|
||||
)
|
||||
|
||||
|
||||
def _test_resume_files_that_record_no_writer(rank, size, directory, layout):
|
||||
# Files saved before they recorded their writer: data-parallel replicas calibrate alike, so
|
||||
# theirs resume, but a tensor-parallel rank's own shards cannot be told from another rank's.
|
||||
torch.manual_seed(0)
|
||||
weights = SimpleLinear().state_dict()
|
||||
# Tensor-parallel ranks the same data: their files hold alike calibrations, refused by layout.
|
||||
torch.manual_seed(rank if layout == "replicated" else 0)
|
||||
data_loader = [SimpleLinear().get_input() for _ in range(2)]
|
||||
|
||||
def search(forward_step, plan=None):
|
||||
model = SimpleLinear()
|
||||
model.load_state_dict(weights)
|
||||
if plan is not None:
|
||||
set_distribution_plan(model, plan)
|
||||
for module in model.modules():
|
||||
if isinstance(module, torch.nn.Linear) and layout == "tensor_parallel":
|
||||
module._parallel_state = ParallelState(-1, tensor_parallel_group=None)
|
||||
if layout == "dtensor_parallel": # a DTensor's shards, with no parallel state naming them
|
||||
mesh = init_device_mesh("cpu", (size,))
|
||||
parallelize_module(model.net[0], mesh, ColwiseParallel(output_layouts=Replicate()))
|
||||
return mtq.auto_quantize(
|
||||
model,
|
||||
constraints={"effective_bits": 11.0},
|
||||
# SmoothQuant cannot scale a DTensor weight.
|
||||
quantization_formats=[
|
||||
mtq.INT8_DEFAULT_CFG if layout == "dtensor_parallel" else mtq.INT8_SMOOTHQUANT_CFG
|
||||
],
|
||||
data_loader=data_loader,
|
||||
forward_step=forward_step,
|
||||
loss_func=lambda output, data: output.sum(),
|
||||
num_calib_steps=2,
|
||||
num_score_steps=2,
|
||||
checkpoint=str(directory),
|
||||
)[1]
|
||||
|
||||
def no_forward(model, batch):
|
||||
raise AssertionError("a resumed search ran a forward")
|
||||
|
||||
with bounded_collectives():
|
||||
searched = search(lambda model, batch: model(batch))
|
||||
path = directory / f"rank{rank}.pth"
|
||||
state = safe_load(path)
|
||||
for key in ("checkpoint_rank", "checkpoint_world_size", "distribution_plan"):
|
||||
state.pop(key)
|
||||
for key in ("parallel_layout", "search_id"):
|
||||
state.pop(key)
|
||||
safe_save(state, path)
|
||||
if layout == "replicated": # also under a plan, which the files predate
|
||||
resumed = search(no_forward, DistributionPlan(size))
|
||||
assert resumed["candidate_stats"] == searched["candidate_stats"]
|
||||
else:
|
||||
with pytest.raises(ValueError, match="records no parallel layout"):
|
||||
search(no_forward)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("layout", ["replicated", "tensor_parallel", "dtensor_parallel"])
|
||||
def test_resume_files_that_record_no_writer(cpu_dist_workers, tmp_path, layout):
|
||||
cpu_dist_workers.run(
|
||||
_test_resume_files_that_record_no_writer, directory=tmp_path, layout=layout
|
||||
)
|
||||
|
||||
|
||||
def _test_resume_under_another_weight_placement(rank, size, directory):
|
||||
def tensor_parallel_model(parallel_style):
|
||||
torch.manual_seed(0)
|
||||
model = SimpleLinear()
|
||||
# Its first projection's weight a DTensor sharded over the ranks, by rows or by columns.
|
||||
mesh = init_device_mesh("cpu", (size,))
|
||||
parallelize_module(model.net[0], mesh, parallel_style)
|
||||
# Its tensor-parallel group, as a tensor-parallel load seeds it: the same either way.
|
||||
model.net[0]._parallel_state = ParallelState(-1, tensor_parallel_group=mesh.get_group())
|
||||
return model
|
||||
|
||||
torch.manual_seed(rank)
|
||||
data = [SimpleLinear.get_input() for _ in range(2)]
|
||||
|
||||
def search(model, forward_step):
|
||||
return mtq.auto_quantize(
|
||||
model,
|
||||
constraints={"effective_bits": 8.0},
|
||||
quantization_formats=[mtq.INT8_DEFAULT_CFG],
|
||||
data_loader=data,
|
||||
forward_step=forward_step,
|
||||
loss_func=lambda output, _: output.sum(),
|
||||
num_calib_steps=1,
|
||||
num_score_steps=1,
|
||||
checkpoint=str(directory),
|
||||
)[1]
|
||||
|
||||
def no_forward(model, batch):
|
||||
raise AssertionError("a resumed search ran a forward")
|
||||
|
||||
by_rows = ColwiseParallel(output_layouts=Replicate())
|
||||
with bounded_collectives():
|
||||
searched = search(tensor_parallel_model(by_rows), lambda model, batch: model(batch))
|
||||
resumed = search(tensor_parallel_model(by_rows), no_forward)
|
||||
assert resumed["candidate_stats"] == searched["candidate_stats"]
|
||||
model = tensor_parallel_model(
|
||||
RowwiseParallel(input_layouts=Replicate(), output_layouts=Replicate())
|
||||
)
|
||||
with pytest.raises(ValueError, match="other parallel groups or weight shards"):
|
||||
search(model, no_forward)
|
||||
assert not mto.ModeloptStateManager.is_converted(model)
|
||||
|
||||
|
||||
def test_resume_under_another_weight_placement_is_refused(cpu_dist_workers, tmp_path):
|
||||
"""The same tensor-parallel group can shard a weight by rows or by columns: a file resumes under
|
||||
the placement it records, and every rank refuses it under another, handing the model back."""
|
||||
cpu_dist_workers.run(_test_resume_under_another_weight_placement, directory=tmp_path)
|
||||
|
||||
|
||||
def _test_fsdp2_resumes_with_no_weight_placements(rank, size, directory):
|
||||
def search(forward_step):
|
||||
torch.manual_seed(0)
|
||||
model = SimpleLinear()
|
||||
fully_shard(model, mesh=init_device_mesh("cpu", (size,)))
|
||||
torch.manual_seed(rank)
|
||||
return mtq.auto_quantize(
|
||||
model,
|
||||
constraints={"effective_bits": 11.0},
|
||||
quantization_formats=[mtq.INT8_DEFAULT_CFG],
|
||||
data_loader=[SimpleLinear.get_input() for _ in range(size)],
|
||||
forward_step=forward_step,
|
||||
loss_func=lambda output, _: output.sum(),
|
||||
num_calib_steps=size,
|
||||
num_score_steps=size,
|
||||
checkpoint=str(directory),
|
||||
)[1]
|
||||
|
||||
def no_forward(model, batch):
|
||||
raise AssertionError("a resumed search ran a forward")
|
||||
|
||||
with bounded_collectives():
|
||||
searched = search(lambda model, batch: model(batch))
|
||||
layout = safe_load(directory / f"rank{rank}.pth")["parallel_layout"]
|
||||
assert all(len(entry) == 2 for entry in layout) # each module's name and groups alone
|
||||
resumed = search(no_forward)
|
||||
assert resumed["candidate_stats"] == searched["candidate_stats"]
|
||||
|
||||
|
||||
def test_fsdp2_resumes_with_no_weight_placements(cpu_dist_workers, tmp_path):
|
||||
"""FSDP2 calibrates the weights it alone shards whole, so a file records no placements for
|
||||
them, and resumes with no forward."""
|
||||
cpu_dist_workers.run(_test_fsdp2_resumes_with_no_weight_placements, directory=tmp_path)
|
||||
|
||||
|
||||
def _test_resume_with_the_same_nan_diagnostics_on_every_rank(rank, size, directory):
|
||||
torch.manual_seed(rank)
|
||||
data_loader = [SimpleLinear().get_input() for _ in range(2)]
|
||||
|
||||
def search():
|
||||
return mtq.auto_quantize(
|
||||
SimpleLinear(),
|
||||
constraints={"effective_bits": 11.0},
|
||||
quantization_formats=[mtq.INT8_SMOOTHQUANT_CFG],
|
||||
data_loader=data_loader,
|
||||
forward_step=lambda model, batch: model(batch),
|
||||
loss_func=lambda output, data: output.sum(),
|
||||
num_calib_steps=2,
|
||||
num_score_steps=2,
|
||||
method="aumann_shapley",
|
||||
checkpoint=str(directory),
|
||||
)[1]
|
||||
|
||||
searched = search()
|
||||
# The NaN diagnostics a damage model records when it scored no tokens, on every rank alike.
|
||||
path = directory / f"rank{rank}.pth"
|
||||
state = safe_load(path)
|
||||
state["damage_model"] = {
|
||||
**state["damage_model"],
|
||||
"completeness": float("nan"),
|
||||
"f_corner": float("nan"),
|
||||
}
|
||||
safe_save(state, path)
|
||||
with bounded_collectives():
|
||||
assert search()["best"]["recipe"] == searched["best"]["recipe"]
|
||||
|
||||
|
||||
def test_resume_with_the_same_nan_diagnostics_on_every_rank(cpu_dist_workers, tmp_path):
|
||||
cpu_dist_workers.run(
|
||||
_test_resume_with_the_same_nan_diagnostics_on_every_rank, directory=tmp_path
|
||||
)
|
||||
|
||||
|
||||
def _test_search_on_ranks_of_their_own_groups(rank, size, directory):
|
||||
# Each rank a tensor-parallel group of its own, as ranks of other expert-parallel rows or TP
|
||||
# pairs hold. A group of one rank shards nothing, so the files record no such group.
|
||||
own = [torch.distributed.new_group([r]) for r in range(size)]
|
||||
torch.manual_seed(rank)
|
||||
data_loader = [SimpleLinear().get_input() for _ in range(2)]
|
||||
|
||||
def search(own_groups=True):
|
||||
model = SimpleLinear()
|
||||
for module in model.modules():
|
||||
if isinstance(module, torch.nn.Linear) and own_groups:
|
||||
module._parallel_state = ParallelState(None, tensor_parallel_group=own[rank])
|
||||
return mtq.auto_quantize(
|
||||
model,
|
||||
constraints={"effective_bits": 11.0},
|
||||
quantization_formats=[mtq.INT8_SMOOTHQUANT_CFG],
|
||||
data_loader=data_loader,
|
||||
forward_step=lambda model, batch: model(batch),
|
||||
loss_func=lambda output, data: output.sum(),
|
||||
num_calib_steps=2,
|
||||
num_score_steps=2,
|
||||
checkpoint=str(directory),
|
||||
)[1]
|
||||
|
||||
try:
|
||||
with bounded_collectives():
|
||||
searched = search()
|
||||
assert search()["candidate_stats"] == searched["candidate_stats"]
|
||||
# A group of one rank shards nothing: resumed without it, as from a one-rank load.
|
||||
assert search(own_groups=False)["candidate_stats"] == searched["candidate_stats"]
|
||||
# Every rank returns the same state, but for its own calibrations.
|
||||
states = [None] * size
|
||||
shared = {key: value for key, value in searched.items() if key != "quantizer_states"}
|
||||
torch.distributed.all_gather_object(states, shared)
|
||||
assert states[0] == states[1]
|
||||
finally:
|
||||
torch.distributed.destroy_process_group(own[rank])
|
||||
|
||||
|
||||
def test_search_on_ranks_of_their_own_groups(cpu_dist_workers, tmp_path):
|
||||
"""Ranks holding groups of their own resume each from its own file."""
|
||||
cpu_dist_workers.run(_test_search_on_ranks_of_their_own_groups, directory=tmp_path)
|
||||
|
||||
|
||||
def _test_checkpoint_save_failing_on_one_rank(rank, size, directory, step):
|
||||
torch.manual_seed(rank)
|
||||
data_loader = [SimpleLinear().get_input() for _ in range(2)]
|
||||
fails = rank == 1
|
||||
if fails and step == "write": # a file where rank 1's checkpoint directory would be
|
||||
(directory / "file").write_text("")
|
||||
checkpoint = (
|
||||
directory / "file" / "search" if fails and step == "write" else directory / "search"
|
||||
)
|
||||
error, match = {
|
||||
"write": (NotADirectoryError, None),
|
||||
"rename": (PermissionError, "read-only"),
|
||||
}[step]
|
||||
if not fails:
|
||||
label = {"write": "", "rename": r" \(rename\)"}[step]
|
||||
error, match = (
|
||||
RuntimeError,
|
||||
f"rank 1 failed to compute AutoQuantize checkpoint save{label}:",
|
||||
)
|
||||
replace = os.replace
|
||||
|
||||
def replace_unless_staged(src, dst):
|
||||
if str(src).endswith(".saving"):
|
||||
raise PermissionError("read-only")
|
||||
replace(src, dst)
|
||||
|
||||
renames = (
|
||||
mock.patch("os.replace", replace_unless_staged)
|
||||
if fails and step == "rename"
|
||||
else nullcontext()
|
||||
)
|
||||
with bounded_collectives(), renames, pytest.raises(error, match=match):
|
||||
mtq.auto_quantize(
|
||||
SimpleLinear(),
|
||||
constraints={"effective_bits": 11.0},
|
||||
quantization_formats=[mtq.INT8_SMOOTHQUANT_CFG],
|
||||
data_loader=data_loader,
|
||||
forward_step=lambda model, batch: model(batch),
|
||||
loss_func=lambda output, data: output.sum(),
|
||||
num_calib_steps=2,
|
||||
num_score_steps=2,
|
||||
checkpoint=str(checkpoint),
|
||||
)
|
||||
if step == "write":
|
||||
# Rank 0 wrote its file but kept none: a file ahead of rank 1's would fail the next resume.
|
||||
assert not checkpoint.exists() or not any(checkpoint.iterdir())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("step", ["write", "rename"])
|
||||
def test_checkpoint_save_failing_on_one_rank_raises_on_every_rank(cpu_dist_workers, tmp_path, step):
|
||||
cpu_dist_workers.run(_test_checkpoint_save_failing_on_one_rank, directory=tmp_path, step=step)
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform == "win32", reason="requires POSIX file modes")
|
||||
def test_checkpoint_save_keeps_the_checkpoint_mode(tmp_path):
|
||||
"""A re-save keeps an owner-only checkpoint owner-only, as a write over it would."""
|
||||
path = tmp_path / "search.pth"
|
||||
path.write_bytes(b"")
|
||||
path.chmod(0o600)
|
||||
searcher = SimpleNamespace(
|
||||
_get_checkpoint_path=lambda: str(path), state_dict=lambda: {"step": 1}
|
||||
)
|
||||
umask = os.umask(0o022) # under which a new file is 0o644
|
||||
try:
|
||||
_save_together(searcher, verbose=False, label="AutoQuantize checkpoint save")
|
||||
finally:
|
||||
os.umask(umask)
|
||||
assert path.stat().st_mode & 0o777 == 0o600
|
||||
assert safe_load(path) == {"step": 1}
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform == "win32", reason="requires POSIX symlink support")
|
||||
def test_checkpoint_save_writes_through_no_link(tmp_path):
|
||||
"""Links planted at the staged name a save once used, or at its path, redirect nothing.
|
||||
|
||||
A staged name the save did not create, e.g. a concurrent save's, is left alone, also when it is
|
||||
the name a save draws, which the exclusive open then refuses.
|
||||
"""
|
||||
victim = tmp_path / "victim"
|
||||
victim.write_bytes(b"kept")
|
||||
path = tmp_path / "search.pth"
|
||||
(tmp_path / "search.pth.saving").symlink_to(victim)
|
||||
other = tmp_path / "search.pth.0123.saving"
|
||||
other.write_bytes(b"other")
|
||||
path.symlink_to(victim)
|
||||
searcher = SimpleNamespace(
|
||||
_get_checkpoint_path=lambda: str(path), state_dict=lambda: {"step": 1}
|
||||
)
|
||||
_save_together(searcher, verbose=False, label="AutoQuantize checkpoint save")
|
||||
assert victim.read_bytes() == b"kept"
|
||||
assert not path.is_symlink()
|
||||
assert safe_load(path) == {"step": 1}
|
||||
assert other.read_bytes() == b"other"
|
||||
searcher.state_dict = lambda: {"step": 2}
|
||||
drawn = SimpleNamespace(hex="0123") # the other save's name
|
||||
with (
|
||||
mock.patch("modelopt.torch.quantization.algorithms.uuid.uuid4", return_value=drawn),
|
||||
pytest.raises(FileExistsError),
|
||||
):
|
||||
_save_together(searcher, verbose=False, label="AutoQuantize checkpoint save")
|
||||
assert other.read_bytes() == b"other"
|
||||
assert safe_load(path) == {"step": 1}
|
||||
|
||||
|
||||
def _test_refused_on_one_rank_raises_on_every_rank(rank, size, fault, directory):
|
||||
# Rank 1 alone makes its loss's gradients infinite from the first of two batches, groups two
|
||||
# layers into one decision, which a rule for one of them splits, as a rule can for a group only
|
||||
@@ -2008,6 +2580,198 @@ def test_tensor_parallel_kl_keeps_small_differences_over_a_large_shared_kl(cpu_d
|
||||
cpu_dist_workers.run(_tensor_parallel_kl_job)
|
||||
|
||||
|
||||
def test_auto_quantize_resume_recomputes_costs_saved_by_an_older_cost_model(tmp_path):
|
||||
"""A checkpoint saved before weight sizes were recorded, whose costs and budget denominator an
|
||||
older cost model computed (e.g. one that left out half of each non-gated expert), warns when
|
||||
re-solved without the model and merges as before. Resumed on the model, even from a single
|
||||
extensionless file with renamed formats, it solves with the current costs and denominator and
|
||||
its saved scores, and is left unchanged."""
|
||||
checkpoint_path = str(tmp_path / "autoquant_stale_costs.pth")
|
||||
budget = {"effective_bits": 6.0}
|
||||
# Custom configs (presets would keep their preset names), so the names below take effect.
|
||||
formats = []
|
||||
for preset in (mtq.INT4_BLOCKWISE_WEIGHT_ONLY_CFG, mtq.INT8_DEFAULT_CFG):
|
||||
cfg = copy.deepcopy(preset)
|
||||
cfg["quant_cfg"].append({"quantizer_name": "unused_quantizer", "enable": False})
|
||||
formats.append(cfg)
|
||||
old, new = QuantRecipe(formats[0], name="int4_old"), QuantRecipe(formats[0], name="int4_new")
|
||||
assert str(old) != str(new) and old.checkpoint_signature == new.checkpoint_signature
|
||||
|
||||
def run(checkpoint, names):
|
||||
model = TransformerBlock()
|
||||
return mtq.auto_quantize(
|
||||
model,
|
||||
constraints={"effective_bits": 8.0},
|
||||
quantization_formats=list(zip(formats, names)),
|
||||
data_loader=[model.get_input()],
|
||||
forward_step=lambda model, batch: model(batch),
|
||||
loss_func=lambda output, data: output.sum(),
|
||||
num_calib_steps=1,
|
||||
num_score_steps=1,
|
||||
checkpoint=checkpoint,
|
||||
)[1]
|
||||
|
||||
fresh = run(checkpoint_path, ["int4_old", "int8_old"])
|
||||
with warnings.catch_warnings():
|
||||
# A current checkpoint re-solves without a warning of its own; other libraries' deprecation
|
||||
# warnings (e.g. PuLP's solver) are not this test's concern.
|
||||
warnings.simplefilter("error", UserWarning)
|
||||
mtq.get_auto_quantize_config(fresh, budget, algorithm="max")
|
||||
stale = safe_load(checkpoint_path)
|
||||
for stats in stale["candidate_stats"].values():
|
||||
stats["costs"] = [cost / 2 for cost in stats["costs"]]
|
||||
stats["uncompressed_cost"] /= 2
|
||||
del stats["weight_size"]
|
||||
stale["cost_denominator"] = fresh["cost_denominator"] / 2
|
||||
# Saved as a single file without an extension, which a single process resumes from as is.
|
||||
checkpoint_path = str(tmp_path / "search")
|
||||
safe_save(stale, checkpoint_path)
|
||||
|
||||
with pytest.warns(UserWarning, match="before weight sizes were recorded"):
|
||||
mtq.get_auto_quantize_config(stale, budget, algorithm="max")
|
||||
merged = model_quant.merge_auto_quantize_shards([{**stale, "format_shard": (0, 1)}])
|
||||
with pytest.warns(UserWarning, match="before weight sizes were recorded"):
|
||||
mtq.get_auto_quantize_config(merged, budget, algorithm="max")
|
||||
|
||||
# Renaming the formats keeps their identity, so the resume matches them to their saved scores.
|
||||
resumed = run(checkpoint_path, ["int4_new", "int8_new"])
|
||||
for name, stats in resumed["candidate_stats"].items():
|
||||
assert stats["costs"] == fresh["candidate_stats"][name]["costs"]
|
||||
assert stats["weight_size"] == fresh["candidate_stats"][name]["weight_size"]
|
||||
assert stats["raw_scores"] == stale["candidate_stats"][name]["raw_scores"]
|
||||
assert resumed["cost_denominator"] == pytest.approx(fresh["cost_denominator"])
|
||||
assert resumed["best"]["recipe"] == fresh["best"]["recipe"]
|
||||
# The checkpoint is left as saved, e.g. on a read-only mount; offline it still warns.
|
||||
assert os.path.isfile(checkpoint_path)
|
||||
saved = safe_load(checkpoint_path)
|
||||
assert all("weight_size" not in stats for stats in saved["candidate_stats"].values())
|
||||
assert saved["cost_denominator"] == pytest.approx(stale["cost_denominator"])
|
||||
with pytest.warns(UserWarning, match="before weight sizes were recorded"):
|
||||
mtq.get_auto_quantize_config(saved, budget, algorithm="max")
|
||||
|
||||
|
||||
class _ReorderedAttentionLayer(_AttentionLayer):
|
||||
"""The same layer with k_proj registered before q_proj, as a model rebuilt another way may."""
|
||||
|
||||
def __init__(self):
|
||||
torch.nn.Module.__init__(self)
|
||||
self.k_proj = torch.nn.Linear(32, 32)
|
||||
self.q_proj = torch.nn.Linear(32, 32)
|
||||
self.v_proj = torch.nn.Linear(32, 32)
|
||||
self.o_proj = torch.nn.Linear(32, 32)
|
||||
|
||||
|
||||
def test_auto_quantize_resume_reprices_a_grouped_layer_saved_under_another_member(
|
||||
tmp_path, monkeypatch
|
||||
):
|
||||
"""A Q/K/V group is saved under its first registered member. Resumed on a model that registers
|
||||
another member first, the group is still repriced by its saved name, so stale costs saved for
|
||||
that group alone cannot change the solve."""
|
||||
checkpoint_path = str(tmp_path / "autoquant_qkv.pth")
|
||||
formats = [mtq.INT4_BLOCKWISE_WEIGHT_ONLY_CFG, mtq.INT8_DEFAULT_CFG]
|
||||
|
||||
def run(model, checkpoint):
|
||||
torch.manual_seed(0)
|
||||
return mtq.auto_quantize(
|
||||
model,
|
||||
constraints={"effective_bits": 6.0},
|
||||
quantization_formats=formats,
|
||||
data_loader=[torch.ones(1, 4, 32)],
|
||||
forward_step=lambda model, batch: model(batch),
|
||||
loss_func=lambda output, data: output.sum(),
|
||||
num_calib_steps=1,
|
||||
num_score_steps=1,
|
||||
checkpoint=checkpoint,
|
||||
)[1]
|
||||
|
||||
torch.manual_seed(0)
|
||||
fresh = run(TransformerBlock(), checkpoint_path)
|
||||
qkv = "attn.q_proj.quant_recipe"
|
||||
assert qkv in fresh["candidate_stats"]
|
||||
|
||||
stale = safe_load(checkpoint_path)
|
||||
stats = stale["candidate_stats"][qkv]
|
||||
stats["costs"] = [cost / 4 for cost in stats["costs"]]
|
||||
stats["uncompressed_cost"] /= 4
|
||||
del stats["weight_size"]
|
||||
stale["cost_denominator"] = None
|
||||
safe_save(stale, checkpoint_path)
|
||||
|
||||
torch.manual_seed(0)
|
||||
reordered = TransformerBlock()
|
||||
reordered.attn = _ReorderedAttentionLayer()
|
||||
# Saved rows are repriced from the live prices, in the live order every rank shares: the
|
||||
# resume prices each live choice once and nothing in saved-row order (no rank-local collectives).
|
||||
priced = []
|
||||
get_cost = QuantRecipeHparam.get_cost
|
||||
|
||||
def counting_get_cost(self, recipe, *args, **kwargs):
|
||||
priced.append(recipe)
|
||||
return get_cost(self, recipe, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(QuantRecipeHparam, "get_cost", counting_get_cost)
|
||||
resumed = run(reordered, checkpoint_path)
|
||||
monkeypatch.undo()
|
||||
live_choices = sum(len(stats["formats"]) + 1 for stats in fresh["candidate_stats"].values())
|
||||
assert len(priced) <= live_choices + len(fresh["candidate_stats"])
|
||||
assert resumed["candidate_stats"][qkv]["costs"] == fresh["candidate_stats"][qkv]["costs"]
|
||||
assert resumed["cost_denominator"] == pytest.approx(fresh["cost_denominator"])
|
||||
assert resumed["best"]["recipe"] == fresh["best"]["recipe"]
|
||||
# The stale costs alone would solve differently, so the repricing decides the recipe.
|
||||
budget = {"effective_bits": 6.0}
|
||||
with pytest.warns(UserWarning, match="before weight sizes were recorded"):
|
||||
stale_config = mtq.get_auto_quantize_config(stale, budget, algorithm="max")
|
||||
assert stale_config != mtq.get_auto_quantize_config(fresh, budget, algorithm="max")
|
||||
|
||||
|
||||
def _resume_with_a_shorter_saved_ladder_job(rank, world_size, tmp_path):
|
||||
def run(checkpoint):
|
||||
torch.manual_seed(0)
|
||||
return mtq.auto_quantize(
|
||||
TransformerBlock(),
|
||||
constraints={"effective_bits": 6.0},
|
||||
quantization_formats=[mtq.INT4_BLOCKWISE_WEIGHT_ONLY_CFG, mtq.INT8_DEFAULT_CFG],
|
||||
data_loader=[torch.ones(1, 4, 32)],
|
||||
forward_step=lambda model, batch: model(batch),
|
||||
loss_func=lambda output, data: output.sum(),
|
||||
num_calib_steps=1,
|
||||
num_score_steps=1,
|
||||
checkpoint=checkpoint,
|
||||
)[1]
|
||||
|
||||
# In a distributed run each rank saves and restores its own file, autoquant<rank>.pth.
|
||||
checkpoint = str(tmp_path / "autoquant.pth")
|
||||
fresh = run(checkpoint)
|
||||
if rank == 1:
|
||||
# Drop a format this rank's search did not select from one saved row: its saved ladder is
|
||||
# now shorter than rank 0's for that group.
|
||||
rank_file = str(tmp_path / "autoquant1.pth")
|
||||
saved = safe_load(rank_file)
|
||||
name, index = next(
|
||||
(name, i)
|
||||
for name, stats in saved["candidate_stats"].items()
|
||||
for i, fmt in enumerate(stats["formats"])
|
||||
if fmt != fresh["best"]["recipe"][name] and fmt.compression < 1
|
||||
)
|
||||
stats = saved["candidate_stats"][name]
|
||||
length = len(stats["formats"])
|
||||
for value in stats.values():
|
||||
if isinstance(value, list) and len(value) == length:
|
||||
del value[index]
|
||||
safe_save(saved, rank_file)
|
||||
|
||||
# The files no longer hold one search's state: every rank refuses them, in the collective that
|
||||
# restores them.
|
||||
with pytest.raises(ValueError, match="same progress"):
|
||||
run(checkpoint)
|
||||
|
||||
|
||||
def test_auto_quantize_resume_with_a_shorter_saved_ladder_on_one_rank(cpu_dist_workers, tmp_path):
|
||||
"""Ranks resuming from checkpoints whose saved ladders differ refuse them together: the files
|
||||
do not hold one search's state."""
|
||||
cpu_dist_workers.run(_resume_with_a_shorter_saved_ladder_job, tmp_path=tmp_path)
|
||||
|
||||
|
||||
def test_auto_quantize_checkpoint_rejects_changed_fixed_ptq_baseline(tmp_path):
|
||||
checkpoint_path = str(tmp_path / "autoquant_fixed_baseline_checkpoint.pth")
|
||||
|
||||
|
||||
@@ -50,6 +50,7 @@ from modelopt.torch.quantization.utils.calib_utils import (
|
||||
gptq_blockwise_update,
|
||||
)
|
||||
from modelopt.torch.quantization.utils.layerwise_calib import LayerActivationCollector
|
||||
from modelopt.torch.utils import safe_load, safe_save
|
||||
|
||||
|
||||
def _problem(rows=6, cols=16, seed=0):
|
||||
@@ -776,7 +777,7 @@ def _recipe(algorithm, num_bits):
|
||||
return config, num_bits
|
||||
|
||||
|
||||
def _search(model, inputs, formats, effective_bits):
|
||||
def _search(model, inputs, formats, effective_bits, checkpoint=None):
|
||||
_, state = mtq.auto_quantize(
|
||||
model,
|
||||
constraints={"effective_bits": effective_bits},
|
||||
@@ -786,6 +787,7 @@ def _search(model, inputs, formats, effective_bits):
|
||||
loss_func=lambda output, x: output.square().sum(),
|
||||
num_calib_steps=1,
|
||||
num_score_steps=1,
|
||||
checkpoint=checkpoint,
|
||||
)
|
||||
return state
|
||||
|
||||
@@ -934,6 +936,7 @@ def test_auto_quantize_snapshots_only_the_weights_calibration_rewrites(moe, monk
|
||||
"rotated_imatrix",
|
||||
"awq_gptq",
|
||||
"layerwise_checkpoint",
|
||||
"after_restored_codes",
|
||||
],
|
||||
)
|
||||
def test_auto_quantize_refusal_hands_back_the_unconverted_model(case, request):
|
||||
@@ -941,7 +944,18 @@ def test_auto_quantize_refusal_hands_back_the_unconverted_model(case, request):
|
||||
source = _two_layers()
|
||||
# An INT4 weight quantizer cannot hold the codes GPTQ would choose.
|
||||
formats = [(_int4_config(GPTQ), "INT4_GPTQ")]
|
||||
if case == "tied":
|
||||
checkpoint = None
|
||||
if case == "after_restored_codes":
|
||||
# GPTQ's codes, at fewer bits, restore and replay before INT8's calibration, refused for
|
||||
# a quantizer's missing tensors: replaying the codes rewrote no weights.
|
||||
formats = [_recipe(GPTQ, "iq2_xxs"), mtq.INT8_DEFAULT_CFG]
|
||||
checkpoint = str(request.getfixturevalue("tmp_path") / "search.pth")
|
||||
_search(copy.deepcopy(source), inputs, formats, 16.0, checkpoint)
|
||||
state = safe_load(checkpoint)
|
||||
saved = list(state["quantizer_states"].values())[-1] # INT8's, calibrated after GPTQ's
|
||||
del saved["state_dict"][next(name for name, t in saved["state_dict"].items() if t)]
|
||||
safe_save(state, checkpoint)
|
||||
elif case == "tied":
|
||||
# GPTQ would rewrite the weight under both layers.
|
||||
source[1] = torch.nn.Linear(512, 512, bias=False)
|
||||
source[1].weight = source[0].weight
|
||||
@@ -983,7 +997,7 @@ def test_auto_quantize_refusal_hands_back_the_unconverted_model(case, request):
|
||||
held = [dict(vars(config)) for config in configs]
|
||||
|
||||
with pytest.raises((ValueError, NotImplementedError)):
|
||||
_search(model, inputs, formats, 16.0)
|
||||
_search(model, inputs, formats, 16.0, checkpoint)
|
||||
|
||||
assert not mto.ModeloptStateManager.is_converted(model)
|
||||
assert [type(m) for m in model.modules()] == [type(m) for m in source.modules()]
|
||||
|
||||
@@ -1095,3 +1095,30 @@ def test_fsdp2_registration_windows_preserve_persistent_shards(cpu_dist_workers,
|
||||
cpu_dist_workers.run(_fsdp2_registration_windows_job, case)
|
||||
finally:
|
||||
cpu_dist_workers.job_timeout, cpu_dist_workers.failure_grace = timeout, grace
|
||||
|
||||
|
||||
@pytest.mark.parametrize("nested", [False, True])
|
||||
def test_accelerate_offload_detection_preserves_native_lifecycle(nested):
|
||||
hooks = pytest.importorskip("accelerate.hooks")
|
||||
model = torch.nn.Linear(4, 4, bias=False)
|
||||
weights = dict(model.state_dict())
|
||||
plain = hooks.AlignDevicesHook(execution_device="cpu", weights_map=weights)
|
||||
offload = hooks.AlignDevicesHook(execution_device="cpu", offload=True, weights_map=weights)
|
||||
# Pin the upstream lifecycle field used to distinguish suspended offload from plain hooks.
|
||||
assert not hasattr(plain, "original_devices")
|
||||
assert not hasattr(offload, "original_devices")
|
||||
hooks.add_hook_to_module(model, plain)
|
||||
assert not core_utils.has_accelerate_offload(model, include_suspended=True)
|
||||
hooks.remove_hook_from_module(model)
|
||||
hook = hooks.SequentialHook(hooks.ModelHook(), offload) if nested else offload
|
||||
hooks.add_hook_to_module(model, hook)
|
||||
try:
|
||||
assert hasattr(offload, "original_devices")
|
||||
assert core_utils.has_accelerate_offload(model)
|
||||
offload.pre_forward(model)
|
||||
offload.offload = False
|
||||
assert not core_utils.has_accelerate_offload(model)
|
||||
assert core_utils.has_accelerate_offload(model, include_suspended=True)
|
||||
finally:
|
||||
offload.offload = True
|
||||
hooks.remove_hook_from_module(model)
|
||||
|
||||
@@ -18,6 +18,7 @@ import copy
|
||||
import pytest
|
||||
from _test_utils.torch.misc import compare_outputs
|
||||
from _test_utils.torch.nas_prune.models import BaseExampleModel, get_example_models
|
||||
from torch import nn
|
||||
|
||||
import modelopt.torch.opt as mto
|
||||
import modelopt.torch.sparsity as mts
|
||||
@@ -113,3 +114,9 @@ def test_specify_forward_loop():
|
||||
# try specifying both
|
||||
with pytest.raises(AssertionError, match="Only provide `data_loader` or `forward_loop`!"):
|
||||
searcher.search(model, {}, (), {**config_data_loader, **config_loop})
|
||||
|
||||
|
||||
def test_unsupported_pattern():
|
||||
model = nn.Sequential(nn.Linear(32, 16))
|
||||
with pytest.raises(AssertionError, match="Unsupported pattern 4:8 sparsity for sparsity"):
|
||||
mts.sparsify(model, "sparse_magnitude", {"pattern": "4:8 sparsity"})
|
||||
|
||||
@@ -15,6 +15,9 @@
|
||||
|
||||
"""CPU unit tests for DFlash offline training support."""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from _test_utils.torch.speculative.dflash import get_dflash_config
|
||||
from _test_utils.torch.transformers_models import get_tiny_llama
|
||||
|
||||
@@ -23,6 +26,7 @@ from modelopt.recipe.config import ModelOptDFlashRecipe
|
||||
|
||||
NUM_BASE_LAYERS = 4
|
||||
NUM_DRAFT_LAYERS = 2
|
||||
SEQ_LEN = 16
|
||||
|
||||
|
||||
def test_convert_online_keeps_base_layers():
|
||||
@@ -71,3 +75,76 @@ def test_dflash_recipe_derives_offline_from_data():
|
||||
# offline_data_path absent → offline=False
|
||||
recipe = ModelOptDFlashRecipe(dflash=dflash_section)
|
||||
assert recipe.dflash.dflash_offline is False
|
||||
|
||||
|
||||
def _loss_and_grads(model, input_ids, features, seed):
|
||||
model.zero_grad()
|
||||
torch.manual_seed(seed) # seeds the anchor sampling
|
||||
loss = model(input_ids=input_ids, base_model_outputs=features).loss
|
||||
loss.backward()
|
||||
grads = {name: p.grad.clone() for name, p in model.dflash_module.named_parameters()}
|
||||
return loss.detach(), grads
|
||||
|
||||
|
||||
def _context_parallel_parity_job(rank, size, gradient_checkpointing):
|
||||
model = get_tiny_llama(num_hidden_layers=NUM_BASE_LAYERS, dtype=torch.float32)
|
||||
model.config.num_orig_hidden_layers = NUM_BASE_LAYERS
|
||||
mtsp.convert(model, [("dflash", get_dflash_config(offline=True))])
|
||||
model.train()
|
||||
if gradient_checkpointing:
|
||||
model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
|
||||
|
||||
generator = torch.Generator().manual_seed(0)
|
||||
hidden_size = model.config.hidden_size
|
||||
input_ids = torch.randint(1, model.config.vocab_size, (2, SEQ_LEN), generator=generator)
|
||||
features = {
|
||||
"aux_hidden_states": torch.randn(
|
||||
2, SEQ_LEN, NUM_DRAFT_LAYERS * hidden_size, generator=generator
|
||||
),
|
||||
"base_model_hidden_states": torch.randn(2, SEQ_LEN, hidden_size, generator=generator),
|
||||
}
|
||||
expected_loss, expected_grads = _loss_and_grads(model, input_ids, dict(features), seed=0)
|
||||
|
||||
model.enable_context_parallel(dist.group.WORLD)
|
||||
model.shard_context(features)
|
||||
assert features["aux_hidden_states"].shape[1] == SEQ_LEN // size
|
||||
# Ranks seeded apart must still draft the blocks rank 0 samples.
|
||||
loss, grads = _loss_and_grads(model, input_ids, features, seed=rank)
|
||||
|
||||
for grad in grads.values():
|
||||
dist.all_reduce(grad) # the trainer averages gradients over the ranks
|
||||
# Assert only after the last collective, so a failing rank cannot leave its peer waiting.
|
||||
torch.testing.assert_close(loss, expected_loss)
|
||||
for name, grad in grads.items():
|
||||
torch.testing.assert_close(
|
||||
grad / size, expected_grads[name], rtol=1e-4, atol=1e-5, msg=name
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("gradient_checkpointing", [False, True])
|
||||
def test_context_parallel_matches_single_rank(cpu_dist_workers, gradient_checkpointing):
|
||||
"""Two ranks with half the context each reproduce the one-rank loss and gradients."""
|
||||
cpu_dist_workers.run(_context_parallel_parity_job, gradient_checkpointing)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("setting", "value", "match"),
|
||||
[
|
||||
("dflash_offline", False, "online training"),
|
||||
("dflash_use_torch_compile", True, "torch_compile"),
|
||||
("dflash_architecture_config", {"projector_type": "dspark", "markov_rank": 8}, "dspark"),
|
||||
("dflash_architecture_config", {"attention_dropout": 0.1}, "attention_dropout"),
|
||||
],
|
||||
)
|
||||
def test_context_parallel_rejects_unsupported_setups(setting, value, match):
|
||||
config = get_dflash_config(offline=True)
|
||||
if setting == "dflash_architecture_config":
|
||||
value = {**config[setting], **value}
|
||||
config[setting] = value
|
||||
model = get_tiny_llama(num_hidden_layers=NUM_BASE_LAYERS)
|
||||
model.config.num_orig_hidden_layers = NUM_BASE_LAYERS
|
||||
mtsp.convert(model, [("dflash", config)])
|
||||
|
||||
with pytest.raises(ValueError, match=match):
|
||||
model.enable_context_parallel(None)
|
||||
assert not model.context_parallel_enabled
|
||||
|
||||
Reference in New Issue
Block a user