Files
realAsmaandClaude Opus 4.8 196c091027 [1/N] Refactor llm_qat example: YAML configs + ModelOptArgParser (#1172)
### What does this PR do?

Type of change: new example

Refactors `examples/llm_qat` from a monolithic launch/script flow into a
modular, config-driven Hugging Face QAT/QAD workflow. The high-level
user flow is now:

1. Quantize a base model with a ModelOpt PTQ recipe.
2. Train or evaluate the quantized checkpoint with QAT, QAD, LoRA QAT,
QLoRA, or fine-tuning configs.
3. Export the trained checkpoint for deployment.

Highlights:

- Replaces the legacy `examples/llm_qat/launch.sh` +
`examples/llm_qat/main.py` path with separate `quantize.py` and
`train.py` entrypoints.
- Adds YAML-driven argument parsing through `ModelOptArgParser`,
including `--config <yaml>` defaults, CLI overrides, and generated
`examples/llm_qat/ARGUMENTS.md`.
- Adds declarative configs under `examples/llm_qat/configs/` for
training modes, dataset blends, and Accelerate backends.
- Adds `dataset_utils.py` for weighted multi-source dataset blending,
Hugging Face streaming, local dataset loading, distributed rank-aware
loading, tokenization caching, pre-tokenization, chat templating, and
assistant-token label masking.
- Moves the Hugging Face QAD flow into the shared trainer path through
`DistillArguments`, `QADTrainer`, and teacher-model distillation kwargs.
- Updates `QuantizationArguments` to prefer recipe paths via `--recipe`,
while keeping legacy `--quant_cfg` available with deprecation warnings
for in-trainer quantization.
- Updates `QATTrainer` handling for pre-quantized checkpoints, FSDP2
TensorQuantizer buffers, and recipe-resolved PTQ configs.
- Adds the `general/ptq/int4_blockwise_weight_only` recipe and refreshes
docs for NVFP4, FP8, INT4, FSDP2, DDP, DeepSpeed, QLoRA, and
LLaMA-Factory integration.
- Adds focused parser, dataset tokenization, assistant-mask, and example
workflow coverage.

### Usage

From the repo root:

```sh
cd examples/llm_qat

# 1. Quantize
python quantize.py \
  --model_name_or_path Qwen/Qwen3-8B \
  --dataset_config configs/dataset/blend.yaml \
  --recipe general/ptq/nvfp4_default-kv_fp8 \
  --output_dir qwen3-8b-quantized

# 2. QAT train
accelerate launch --config-file configs/accelerate/fsdp2.yaml train.py \
  --config configs/train/qat_nvfp4.yaml \
  --model_name_or_path qwen3-8b-quantized \
  --output_dir qwen3-8b-qat-nvfp4

# 3. QAD train
accelerate launch --config-file configs/accelerate/fsdp2.yaml train.py \
  --config configs/train/qad_nvfp4.yaml \
  --model_name_or_path qwen3-8b-quantized \
  --teacher_model Qwen/Qwen3-8B \
  --output_dir qwen3-8b-qad-nvfp4
```

Dataset blends can be pre-tokenized and cached before training:

```sh
cd examples/llm_qat
python dataset_utils.py \
  --dataset_config configs/dataset/blend.yaml \
  --model_name_or_path Qwen/Qwen3-8B
```

### Testing

Focused coverage added or updated:

- `tests/unit/torch/opt/plugins/test_modelopt_arg_parser.py`
- `tests/examples/llm_qat/test_dataset_tokenization.py`
- `tests/examples/llm_qat/test_assistant_mask.py`
- `tests/examples/llm_qat/test_llm_qat.py`

Recorded validation:

- [x] `pytest tests/unit/torch/opt/plugins/test_modelopt_arg_parser.py`
- [x] `pytest
tests/examples/llm_qat/test_llm_qat.py::test_dataset_utils_pretokenize`
- [x] `pre-commit run --all-files`
- [ ] `pytest tests/examples/llm_qat/test_llm_qat.py` full GPU/backend
suite

### Before your PR is "*Ready for review*"

Make sure you read and follow [Contributor
guidelines](https://github.com/NVIDIA/Model-Optimizer/blob/main/CONTRIBUTING.md)
and your commits are signed (`git commit -s -S`).

Make sure you read and follow the [Security Best
Practices](https://github.com/NVIDIA/Model-Optimizer/blob/main/SECURITY.md#security-coding-practices-for-contributors)
(e.g. avoiding hardcoded `trust_remote_code=True`, `torch.load(...,
weights_only=False)`, `pickle`, etc.).

- Is this change backward compatible?: No for the legacy
`examples/llm_qat` CLI/file layout (`main.py`, `launch.sh`, and FSDP1
config are removed); library `quant_cfg` usage remains available but is
deprecated for this workflow.
- If you copied code from any other sources or added a new PIP
dependency, did you follow guidance in `CONTRIBUTING.md`: Yes.
`train.py`/`simple_qat_train.py` retain the upstream Alpaca attribution
where applicable; `examples/llm_qat/requirements.txt` switches
`tensorboardX` to `tensorboard`.
- Did you write any new necessary tests?: Yes. Parser, dataset
tokenization, assistant masking, pre-tokenization, and QAT/QAD workflow
tests were added or updated.
- Did you update
[Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?:
Yes.
- Did you get Claude approval on this PR?: N/A in this description
update.

### Additional Information

This PR intentionally changes the `llm_qat` example surface. Existing
users should move from `examples/llm_qat/main.py` and
`examples/llm_qat/launch.sh` to `examples/llm_qat/quantize.py`,
`examples/llm_qat/train.py`, and the YAML configs under
`examples/llm_qat/configs/`.

---------

Signed-off-by: realAsma <akuriparambi@nvidia.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-03 01:25:02 +00:00

79 lines
2.4 KiB
Python

# SPDX-FileCopyrightText: Copyright (c) 2024 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 torch
import transformers
from peft import LoraConfig, TaskType
from transformers import default_data_collator
def make_supervised_data_module(
data_args,
tokenizer: transformers.PreTrainedTokenizer,
) -> dict:
"""Build train/eval datasets and a default collator."""
from dataset_utils import build_blend_dataset, load_blend_config
config = load_blend_config(data_args.dataset_config)
max_length = getattr(tokenizer, "model_max_length", 4096)
ds = build_blend_dataset(
config,
tokenizer,
max_length,
seed=data_args.dataset_seed,
cache_dir=data_args.dataset_cache_dir,
shuffle=data_args.shuffle,
shuffle_buffer=data_args.shuffle_buffer,
num_proc=data_args.num_proc,
)
train_ds = ds["train"]
if data_args.train_samples > 0 and data_args.train_samples < len(train_ds):
train_ds = train_ds.select(range(data_args.train_samples))
eval_ds = ds["eval"]
if data_args.eval_samples > 0 and data_args.eval_samples < len(eval_ds):
eval_ds = eval_ds.select(range(data_args.eval_samples))
return {
"train_dataset": train_ds,
"eval_dataset": eval_ds,
"data_collator": default_data_collator,
}
def get_lora_config():
return LoraConfig(
r=8,
target_modules=[
"q_proj",
"o_proj",
"k_proj",
"v_proj",
"gate_proj",
"up_proj",
"down_proj",
],
task_type=TaskType.CAUSAL_LM,
)
def get_metrics_with_perplexity(metrics):
"""Add perplexity to the metrics."""
if "eval_loss" in metrics:
metrics["perplexity"] = float(torch.exp(torch.tensor(metrics["eval_loss"])))
return metrics