Closed
feat(w4a16): 添加 Qwen3 整网训练、推理与评测示例 #199
chen_pengyuAdd on 2 days agoClosed at 1 day ago
feat(w4a16): 添加 Qwen3 整网训练、推理与评测示例 #199
Closed
Total: 9 files changed+680-10
| @@ -0,0 +1,30 @@ | |||
| 1 | +# Copyright (c) 2026, Huawei Technologies Co., Ltd | ||
| 2 | + | ||
| 3 | +"""Run lm-eval with the Qwen3 Ascend inference loader.""" | ||
| 4 | + | ||
| 5 | +from lm_eval.models.huggingface import HFLM | ||
| 6 | +from transformers import AutoTokenizer | ||
| 7 | + | ||
| 8 | +from examples.qwen3.inference_w4a16 import load_qwen3_model | ||
| 9 | + | ||
| 10 | + | ||
| 11 | +class Qwen3W4A16LM(HFLM): | ||
| 12 | + def __init__( | ||
| 13 | + self, | ||
| 14 | + pretrained, | ||
| 15 | + device="npu:0", | ||
| 16 | + npu_count=1, | ||
| 17 | + max_memory_per_npu="40GiB", | ||
| 18 | + **kwargs, | ||
| 19 | + ): | ||
| 20 | + devices = [device] if npu_count == 1 else [f"npu:{i}" for i in range(npu_count)] | ||
| 21 | + model, converted = load_qwen3_model( | ||
| 22 | + pretrained, | ||
| 23 | + devices=devices, | ||
| 24 | + max_memory_per_npu=max_memory_per_npu, | ||
| 25 | + ) | ||
| 26 | + if converted is not None: | ||
| 27 | + print(f"[load-packed] {converted}", flush=True) | ||
| 28 | + model.config.use_cache = False | ||
| 29 | + tokenizer = AutoTokenizer.from_pretrained(pretrained, local_files_only=True) | ||
| 30 | + super().__init__(pretrained=model, tokenizer=tokenizer, backend="causal", **kwargs) | ||
| @@ -0,0 +1,12 @@ | |||
| 1 | +# Copyright (c) 2026, Huawei Technologies Co., Ltd | ||
| 2 | + | ||
| 3 | +"""Register the Qwen3 W4A16 QAT backend for the lm-eval CLI.""" | ||
| 4 | + | ||
| 5 | +import os | ||
| 6 | + | ||
| 7 | +# The W4A16 QAT benchmark enables this only for its lm_eval subprocess. | ||
| 8 | +if os.environ.pop("TORCHAO_ASCEND_LM_EVAL", None) == "1": | ||
| 9 | + import lm_eval.models # noqa: F401 -- populate the built-in model aliases | ||
| 10 | + from lm_eval.api.registry import model_registry | ||
| 11 | + | ||
| 12 | + model_registry.register("qwen3_w4a16", target="qwen3_w4a16_lm:Qwen3W4A16LM") | ||
Mbenchmarks/quantization/measure_accuracy_and_performance.sh+128-6File content is under review, please try again later
| @@ -90,3 +90,22 @@ assert dense_output.shape == moe_output.shape == (10, 128) | |||
| 90 | ``` | 90 | ``` |
| 91 | 91 | ||
| 92 | 接入框架模型时,用与训练一致的模型配置和参数名创建推理模型。加载 packed state dict 时使用 `assign=True`,以保留 Tensor 子类。完整模型的配置、tokenizer 和 MoE 路由由模型框架管理。推理使用加载后的 packed 权重,可以直接进入 `torch.inference_mode()`。 | 92 | 接入框架模型时,用与训练一致的模型配置和参数名创建推理模型。加载 packed state dict 时使用 `assign=True`,以保留 Tensor 子类。完整模型的配置、tokenizer 和 MoE 路由由模型框架管理。推理使用加载后的 packed 权重,可以直接进入 `torch.inference_mode()`。 |
| 93 | + | ||
| 94 | +## 加载完整 Qwen3 模型 | ||
| 95 | + | ||
| 96 | +从仓库根目录运行以下命令生成文本续写。 | ||
| 97 | + | ||
| 98 | +```bash | ||
| 99 | +python -m examples.qwen3.inference_w4a16 /path/to/qwen3-w4a16 \ | ||
| 100 | + --prompt "The capital of France is" --max-new-tokens 32 | ||
| 101 | +``` | ||
| 102 | + | ||
| 103 | +在 Python 里也可以直接调用加载函数。 | ||
| 104 | + | ||
| 105 | +```python | ||
| 106 | +from examples.qwen3.inference_w4a16 import load_qwen3_model | ||
| 107 | + | ||
| 108 | +model, packed_counts = load_qwen3_model(checkpoint, devices=("npu:0",)) | ||
| 109 | +``` | ||
| 110 | + | ||
| 111 | +Qwen3 Dense 的 K-packed checkpoint 由原版 `nn.Linear` 自动分发到融合权重量化矩阵乘。W4A16 和 BF16 都使用 Transformers 的原版 RMSNorm。该入口使用 Transformers 和 Accelerate。 | ||
| @@ -0,0 +1,113 @@ | |||
| 1 | +# Copyright (c) 2026, Huawei Technologies Co., Ltd | ||
| 2 | + | ||
| 3 | +"""Generate text from a local Qwen3 W4A16 or BF16 checkpoint on Ascend.""" | ||
| 4 | + | ||
| 5 | +import argparse | ||
| 6 | +from pathlib import Path | ||
| 7 | + | ||
| 8 | +import torch | ||
| 9 | +import torch_npu # noqa: F401 -- register the NPU backend | ||
| 10 | +from accelerate import dispatch_model, infer_auto_device_map, init_empty_weights | ||
| 11 | +from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer | ||
| 12 | + | ||
| 13 | +from torchao_ascend.features.inference.w4a16 import W4A16DenseTensor, W4A16GMMTensor | ||
| 14 | +from torchao_ascend.features.inference.w4a16.w4a16_gmm import _install_qwen3_grouped_forward | ||
| 15 | +from torchao_ascend.serialization import load_safetensors | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +QWEN3_MODEL_TYPES = ("qwen3", "qwen3_moe") | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +def place_on_npu(model, devices, max_memory_per_npu): | ||
| 22 | + devices = [torch.device(device) for device in devices] | ||
| 23 | + if not devices or any(device.type != "npu" or device.index is None for device in devices): | ||
| 24 | + raise ValueError("Provide explicit NPU IDs, e.g. npu:0 npu:1") | ||
| 25 | + if len(set(devices)) != len(devices): | ||
| 26 | + raise ValueError("Provide distinct NPU IDs") | ||
| 27 | + if len(devices) == 1: | ||
| 28 | + return model.to(devices[0]) | ||
| 29 | + budget = {device.index: max_memory_per_npu for device in devices} | ||
| 30 | + placement = infer_auto_device_map( | ||
| 31 | + model, max_memory=budget, no_split_module_classes=model._no_split_modules | ||
| 32 | + ) | ||
| 33 | + if any(device not in budget for device in placement.values()): | ||
| 34 | + raise RuntimeError("The model did not fit on the requested NPUs. Add NPUs or increase the budget.") | ||
| 35 | + return dispatch_model(model, device_map={name: f"npu:{idx}" for name, idx in placement.items()}) | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +def _restore_packed_weights(model, state): | ||
| 39 | + dense = 0 | ||
| 40 | + expert_modules = [] | ||
| 41 | + for name, module in model.named_modules(): | ||
| 42 | + prefix = f"{name}." if name else "" | ||
| 43 | + if isinstance(state.get(prefix + "weight"), W4A16DenseTensor): | ||
| 44 | + if not isinstance(module, torch.nn.Linear): | ||
| 45 | + raise ValueError(f"W4A16 Dense checkpoint targets a non-Linear module: {name}") | ||
| 46 | + dense += 1 | ||
| 47 | + gate = isinstance(state.get(prefix + "gate_up_proj"), W4A16GMMTensor) | ||
| 48 | + down = isinstance(state.get(prefix + "down_proj"), W4A16GMMTensor) | ||
| 49 | + if gate != down: | ||
| 50 | + raise ValueError(f"W4A16 checkpoint must contain both expert projections for {name}") | ||
| 51 | + if gate: | ||
| 52 | + expert_modules.append(module) | ||
| 53 | + if not dense or (model.config.model_type == "qwen3_moe" and not expert_modules): | ||
| 54 | + raise ValueError("Checkpoint is missing packed Dense or MoE weights") | ||
| 55 | + model.load_state_dict(state, assign=True, strict=True) | ||
| 56 | + model.tie_weights() | ||
| 57 | + for module in expert_modules: | ||
| 58 | + _install_qwen3_grouped_forward(module) | ||
| 59 | + return {"dense": dense, "moe": len(expert_modules)} | ||
| 60 | + | ||
| 61 | + | ||
| 62 | +def load_packed_model(checkpoint, config): | ||
| 63 | + """Restore a Qwen3 packed checkpoint on CPU before device placement.""" | ||
| 64 | + with init_empty_weights(): | ||
| 65 | + model = AutoModelForCausalLM.from_config(config, dtype=torch.bfloat16).eval() | ||
| 66 | + converted = _restore_packed_weights(model, load_safetensors(checkpoint)) | ||
| 67 | + return model, converted | ||
| 68 | + | ||
| 69 | + | ||
| 70 | +def load_qwen3_model(checkpoint, *, devices=("npu:0",), max_memory_per_npu="40GiB"): | ||
| 71 | + """Return an NPU inference model and its packed module counts, if any.""" | ||
| 72 | + if not torch.npu.is_available(): | ||
| 73 | + raise RuntimeError("Ascend NPU is required for Qwen3 inference") | ||
| 74 | + checkpoint = Path(checkpoint) | ||
| 75 | + config = AutoConfig.from_pretrained(checkpoint, local_files_only=True) | ||
| 76 | + if config.model_type not in QWEN3_MODEL_TYPES: | ||
| 77 | + raise ValueError(f"Expected one of {QWEN3_MODEL_TYPES}, got {config.model_type}") | ||
| 78 | + packed = getattr(config, "torchao_ascend_weight_format", None) == "w4a16" | ||
| 79 | + | ||
| 80 | + if packed: | ||
| 81 | + model, converted = load_packed_model(checkpoint, config) | ||
| 82 | + else: | ||
| 83 | + model = AutoModelForCausalLM.from_pretrained( | ||
| 84 | + checkpoint, config=config, dtype=torch.bfloat16, local_files_only=True | ||
| 85 | + ).eval() | ||
| 86 | + converted = None | ||
| 87 | + model = place_on_npu(model, devices, max_memory_per_npu) | ||
| 88 | + if {parameter.device.type for parameter in model.parameters()} != {"npu"}: | ||
| 89 | + raise RuntimeError("Qwen3 inference requires all model parameters on NPU") | ||
| 90 | + return model, converted | ||
| 91 | + | ||
| 92 | + | ||
| 93 | +def main(): | ||
| 94 | + parser = argparse.ArgumentParser(description=__doc__) | ||
| 95 | + parser.add_argument("checkpoint", type=Path, help="Local Qwen3 checkpoint directory") | ||
| 96 | + parser.add_argument("--prompt", required=True, help="Text to continue") | ||
| 97 | + parser.add_argument("--devices", nargs="+", default=("npu:0",), help="NPU device IDs") | ||
| 98 | + parser.add_argument("--max-new-tokens", type=int, default=32) | ||
| 99 | + args = parser.parse_args() | ||
| 100 | + if args.max_new_tokens < 1: | ||
| 101 | + parser.error("--max-new-tokens must be positive") | ||
| 102 | + | ||
| 103 | + model, _ = load_qwen3_model(args.checkpoint, devices=args.devices) | ||
| 104 | + tokenizer = AutoTokenizer.from_pretrained(args.checkpoint, local_files_only=True) | ||
| 105 | + inputs = tokenizer(args.prompt, return_tensors="pt").to(model.get_input_embeddings().weight.device) | ||
| 106 | + with torch.inference_mode(): | ||
| 107 | + output = model.generate(**inputs, max_new_tokens=args.max_new_tokens, do_sample=False) | ||
| 108 | + continuation = output[0, inputs.input_ids.size(-1):] | ||
| 109 | + print(tokenizer.decode(continuation, skip_special_tokens=True)) | ||
| 110 | + | ||
| 111 | + | ||
| 112 | +if __name__ == "__main__": | ||
| 113 | + main() | ||
| @@ -0,0 +1,245 @@ | |||
| 1 | +# Copyright (c) 2026, Huawei Technologies Co., Ltd | ||
| 2 | + | ||
| 3 | +"""Train Qwen3 Dense or fused Qwen3 MoE with TorchAO NPU W4A16 QAT.""" | ||
| 4 | + | ||
| 5 | +from __future__ import annotations | ||
| 6 | + | ||
| 7 | +import argparse | ||
| 8 | +import math | ||
| 9 | +import os | ||
| 10 | +from pathlib import Path | ||
| 11 | +from tempfile import TemporaryDirectory | ||
| 12 | + | ||
| 13 | +import torch | ||
| 14 | +import torch.distributed as dist | ||
| 15 | +import torch_npu # noqa: F401 -- registers the NPU backend | ||
| 16 | +from datasets import load_dataset | ||
| 17 | +from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper | ||
| 18 | +from torch.distributed.checkpoint.state_dict import StateDictOptions, get_model_state_dict | ||
| 19 | +from torch.distributed.device_mesh import init_device_mesh | ||
| 20 | +from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard | ||
| 21 | +from torch.utils.data import DataLoader, DistributedSampler | ||
| 22 | +from torchao.quantization import quantize_ | ||
| 23 | +from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer | ||
| 24 | + | ||
| 25 | +from torchao_ascend.features.qat.w4a16 import ( | ||
| 26 | + W4A16GMM, | ||
| 27 | + W4A16GMMConfig, | ||
| 28 | + W4A16Linear, | ||
| 29 | + W4A16LinearConfig, | ||
| 30 | + w4a16_module_filter_fn, | ||
| 31 | + w4a16_moe_filter_fn, | ||
| 32 | +) | ||
| 33 | +from torchao_ascend.features.qat.w4a16.weight_conversion import pack_checkpoint_weights | ||
| 34 | +from torchao_ascend.serialization import save_safetensors | ||
| 35 | + | ||
| 36 | + | ||
| 37 | +def parse_args(argv=None): | ||
| 38 | + parser = argparse.ArgumentParser(description=__doc__) | ||
| 39 | + parser.add_argument("--model", type=Path, required=True, help="Local HF model and tokenizer directory") | ||
| 40 | + parser.add_argument("--train-file", type=Path, required=True, help="Training text (.txt or .parquet)") | ||
| 41 | + parser.add_argument("--text-column", default="text", help="Text column for parquet input") | ||
| 42 | + parser.add_argument("--output-dir", type=Path, required=True, help="New HF model output directory") | ||
| 43 | + parser.add_argument("--export-dtype", choices=("w4a16", "bf16"), default="w4a16") | ||
| 44 | + parser.add_argument("--steps", type=int, default=200, help="Optimizer updates") | ||
| 45 | + parser.add_argument("--batch-size", type=int, default=1, help="Microbatch size per rank") | ||
| 46 | + parser.add_argument("--seq-length", type=int, default=1024) | ||
| 47 | + parser.add_argument("--grad-accumulation", type=int, default=1) | ||
| 48 | + parser.add_argument("--lr", type=float, default=1e-5) | ||
| 49 | + parser.add_argument("--weight-decay", type=float, default=0.1) | ||
| 50 | + parser.add_argument("--seed", type=int, default=42) | ||
| 51 | + args = parser.parse_args(argv) | ||
| 52 | + if not args.model.is_dir(): | ||
| 53 | + parser.error(f"Model directory not found: {args.model}") | ||
| 54 | + if not args.train_file.is_file() or args.train_file.suffix.lower() not in (".parquet", ".txt"): | ||
| 55 | + parser.error("--train-file must be an existing .parquet or .txt file") | ||
| 56 | + if args.output_dir.exists(): | ||
| 57 | + parser.error(f"Output directory already exists: {args.output_dir}") | ||
| 58 | + if min(args.steps, args.batch_size, args.grad_accumulation) < 1 or args.seq_length < 2: | ||
| 59 | + parser.error("Steps, batch size and accumulation must be positive, and sequence length must be at least 2") | ||
| 60 | + if not math.isfinite(args.lr) or args.lr <= 0 or not math.isfinite(args.weight_decay) or args.weight_decay < 0: | ||
| 61 | + parser.error("Learning rate must be positive and weight decay must be nonnegative") | ||
| 62 | + return args | ||
| 63 | + | ||
| 64 | + | ||
| 65 | +def build_dataloader(args, tokenizer, rank, world_size): | ||
| 66 | + file_type = "parquet" if args.train_file.suffix.lower() == ".parquet" else "text" | ||
| 67 | + rows = load_dataset(file_type, data_files=str(args.train_file), split="train") | ||
| 68 | + if args.text_column not in rows.column_names: | ||
| 69 | + raise ValueError(f"Missing training text column {args.text_column!r}") | ||
| 70 | + if tokenizer.eos_token_id is None: | ||
| 71 | + raise ValueError("The tokenizer must define an EOS token to separate training documents") | ||
| 72 | + | ||
| 73 | + blocks = [] | ||
| 74 | + pending = [] | ||
| 75 | + for batch in rows.select_columns([args.text_column]).iter(batch_size=128): | ||
| 76 | + texts = [text for text in batch[args.text_column] if isinstance(text, str) and text.strip()] | ||
| 77 | + if not texts: | ||
| 78 | + continue | ||
| 79 | + for ids in tokenizer(texts, add_special_tokens=False, verbose=False)["input_ids"]: | ||
| 80 | + pending.extend(ids) | ||
| 81 | + pending.append(tokenizer.eos_token_id) | ||
| 82 | + stop = len(pending) // args.seq_length * args.seq_length | ||
| 83 | + if stop: | ||
| 84 | + blocks.append(torch.tensor(pending[:stop], dtype=torch.long).view(-1, args.seq_length)) | ||
| 85 | + pending = pending[stop:] | ||
| 86 | + if not blocks: | ||
| 87 | + raise ValueError(f"Training data has fewer than {args.seq_length} usable tokens") | ||
| 88 | + tokens = torch.cat(blocks) | ||
| 89 | + sampler = DistributedSampler(tokens, num_replicas=world_size, rank=rank, seed=args.seed, drop_last=True) | ||
| 90 | + loader = DataLoader(tokens, batch_size=args.batch_size, sampler=sampler, drop_last=True) | ||
| 91 | + if len(loader) == 0: | ||
| 92 | + raise ValueError(f"Need at least {world_size * args.batch_size} complete token blocks for one global batch") | ||
| 93 | + return loader | ||
| 94 | + | ||
| 95 | + | ||
| 96 | +def train_batches(loader): | ||
| 97 | + epoch = 0 | ||
| 98 | + while True: | ||
| 99 | + loader.sampler.set_epoch(epoch) | ||
| 100 | + yield from loader | ||
| 101 | + epoch += 1 | ||
| 102 | + | ||
| 103 | + | ||
| 104 | +def prepare_qat(model): | ||
| 105 | + linear = W4A16LinearConfig(step="prepare", w4a16_apply_modules=["model.layers.{*}"]) | ||
| 106 | + linear_filter = w4a16_module_filter_fn(linear) | ||
| 107 | + linear_count = sum(linear_filter(module, name) for name, module in model.named_modules()) | ||
| 108 | + if not linear_count: | ||
| 109 | + raise ValueError("Qwen3 QAT requires at least one matching Linear") | ||
| 110 | + | ||
| 111 | + moe_count = 0 | ||
| 112 | + if model.config.model_type == "qwen3_moe": | ||
| 113 | + moe = W4A16GMMConfig.from_linear(linear) | ||
| 114 | + moe_filter = w4a16_moe_filter_fn(moe) | ||
| 115 | + experts = [module for name, module in model.named_modules() if moe_filter(module, name)] | ||
| 116 | + if not experts or any( | ||
| 117 | + not isinstance(weight, torch.nn.Parameter) or weight.ndim != 3 | ||
| 118 | + for module in experts | ||
| 119 | + for weight in (module.gate_up_proj, module.down_proj) | ||
| 120 | + ): | ||
| 121 | + raise ValueError("Qwen3 MoE QAT requires fused 3D gate_up_proj and down_proj parameters") | ||
| 122 | + moe_count = len(experts) | ||
| 123 | + | ||
| 124 | + quantize_(model, linear, filter_fn=linear_filter) | ||
| 125 | + if moe_count: | ||
| 126 | + quantize_(model, moe, filter_fn=moe_filter) | ||
| 127 | + actual = ( | ||
| 128 | + sum(isinstance(module, W4A16Linear) for module in model.modules()), | ||
| 129 | + sum(isinstance(module, W4A16GMM) for module in model.modules()), | ||
| 130 | + ) | ||
| 131 | + if actual != (linear_count, moe_count): | ||
| 132 | + raise RuntimeError(f"Expected QAT coverage {(linear_count, moe_count)}, got {actual}") | ||
| 133 | + return actual | ||
| 134 | + | ||
| 135 | + | ||
| 136 | +def train(model, loader, args, device, rank, world_size): | ||
| 137 | + optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.weight_decay, foreach=False) | ||
| 138 | + batches = train_batches(loader) | ||
| 139 | + for step in range(1, args.steps + 1): | ||
| 140 | + optimizer.zero_grad(set_to_none=True) | ||
| 141 | + step_loss = torch.zeros((), dtype=torch.float32, device=device) | ||
| 142 | + for _ in range(args.grad_accumulation): | ||
| 143 | + tokens = next(batches).to(device) | ||
| 144 | + loss = model(input_ids=tokens, labels=tokens, use_cache=False).loss | ||
| 145 | + step_loss.add_(loss.detach().float() / args.grad_accumulation) | ||
| 146 | + (loss / args.grad_accumulation).backward() | ||
| 147 | + | ||
| 148 | + if world_size > 1: | ||
| 149 | + dist.all_reduce(step_loss) | ||
| 150 | + step_loss /= world_size | ||
| 151 | + loss_value = step_loss.item() | ||
| 152 | + if not math.isfinite(loss_value): | ||
| 153 | + raise RuntimeError(f"Nonfinite loss at optimizer step {step}: {loss_value}") | ||
| 154 | + optimizer.step() | ||
| 155 | + if rank == 0: | ||
| 156 | + print(f"[train] step={step}/{args.steps} loss={loss_value:.6f}", flush=True) | ||
| 157 | + optimizer.zero_grad(set_to_none=True) | ||
| 158 | + | ||
| 159 | + | ||
| 160 | +def export_hf(model, tokenizer, args, architecture, rank, world_size, device, dense_names, expert_names): | ||
| 161 | + if world_size > 1: | ||
| 162 | + state = get_model_state_dict(model, options=StateDictOptions(full_state_dict=True, cpu_offload=True)) | ||
| 163 | + else: | ||
| 164 | + state = model.cpu().state_dict() | ||
| 165 | + | ||
| 166 | + if rank == 0: | ||
| 167 | + output_dir = args.output_dir | ||
| 168 | + if args.export_dtype == "w4a16": | ||
| 169 | + pack_checkpoint_weights(state, dense_names, expert_names, device) | ||
| 170 | + if model.config.tie_word_embeddings: | ||
| 171 | + head = state["lm_head.weight"] | ||
| 172 | + if head.data_ptr() == state["model.embed_tokens.weight"].data_ptr(): | ||
| 173 | + # Safetensors requires distinct storage for the two names in one shard. | ||
| 174 | + state["lm_head.weight"] = head.clone() | ||
| 175 | + output_dir.parent.mkdir(parents=True, exist_ok=True) | ||
| 176 | + with TemporaryDirectory(prefix=".w4a16-export-", dir=output_dir.parent) as temporary: | ||
| 177 | + staging = Path(temporary) / "model" | ||
| 178 | + shards = save_safetensors(state, staging) | ||
| 179 | + # FSDP2 changes the live model class. Restore the HF architecture name in the export. | ||
| 180 | + model.config.architectures = [architecture] | ||
| 181 | + model.config.torchao_ascend_weight_format = args.export_dtype | ||
| 182 | + model.config.save_pretrained(staging) | ||
| 183 | + if model.generation_config is not None: | ||
| 184 | + model.generation_config.save_pretrained(staging) | ||
| 185 | + tokenizer.save_pretrained(staging) | ||
| 186 | + if output_dir.exists(): | ||
| 187 | + raise FileExistsError(output_dir) | ||
| 188 | + staging.rename(output_dir) | ||
| 189 | + print(f"[export] {len(shards)} safetensors shards with {args.export_dtype} weights: {output_dir}", flush=True) | ||
| 190 | + | ||
| 191 | + | ||
| 192 | +def main(): | ||
| 193 | + args = parse_args() | ||
| 194 | + if not torch.npu.is_available(): | ||
| 195 | + raise RuntimeError("W4A16 QAT requires an available Ascend NPU") | ||
| 196 | + world_size = int(os.environ.get("WORLD_SIZE", "1")) | ||
| 197 | + rank = int(os.environ.get("RANK", "0")) | ||
| 198 | + device = torch.device("npu", int(os.environ.get("LOCAL_RANK", "0"))) | ||
| 199 | + torch.npu.set_device(device) | ||
| 200 | + if world_size > 1: | ||
| 201 | + dist.init_process_group(backend="hccl") | ||
| 202 | + | ||
| 203 | + try: | ||
| 204 | + torch.manual_seed(args.seed) | ||
| 205 | + config = AutoConfig.from_pretrained(args.model, local_files_only=True) | ||
| 206 | + if config.model_type not in ("qwen3", "qwen3_moe"): | ||
| 207 | + raise ValueError(f"Expected Qwen3 Dense or MoE, got {config.model_type!r}") | ||
| 208 | + config.use_cache = False | ||
| 209 | + tokenizer = AutoTokenizer.from_pretrained(args.model, local_files_only=True) | ||
| 210 | + loader = build_dataloader(args, tokenizer, rank, world_size) | ||
| 211 | + model, loading_info = AutoModelForCausalLM.from_pretrained( | ||
| 212 | + args.model, config=config, dtype=torch.bfloat16, local_files_only=True, output_loading_info=True, | ||
| 213 | + ) | ||
| 214 | + issues = {name: values for name, values in loading_info.items() if values} | ||
| 215 | + if issues: | ||
| 216 | + raise ValueError(f"Base model did not load cleanly: {issues}") | ||
| 217 | + architecture = type(model).__name__ | ||
| 218 | + model.train() | ||
| 219 | + linear_count, moe_count = prepare_qat(model) | ||
| 220 | + dense_names = [name for name, module in model.named_modules() if isinstance(module, W4A16Linear)] | ||
| 221 | + expert_names = { | ||
| 222 | + name: config.hidden_size for name, module in model.named_modules() if isinstance(module, W4A16GMM) | ||
| 223 | + } | ||
| 224 | + # Wrap first so FSDP's unshard hooks run outside activation recomputation. | ||
| 225 | + for index, layer in enumerate(model.model.layers): | ||
| 226 | + model.model.layers[index] = checkpoint_wrapper(layer) | ||
| 227 | + if world_size > 1: | ||
| 228 | + mesh = init_device_mesh("npu", (world_size,)) | ||
| 229 | + policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32) | ||
| 230 | + for layer in model.model.layers: | ||
| 231 | + fully_shard(layer, mesh=mesh, mp_policy=policy) | ||
| 232 | + fully_shard(model, mesh=mesh, mp_policy=policy) | ||
| 233 | + else: | ||
| 234 | + model.to(device) | ||
| 235 | + if rank == 0: | ||
| 236 | + print(f"[prepare] {config.model_type} Dense={linear_count}, MoE={moe_count}, ranks={world_size}", flush=True) | ||
| 237 | + train(model, loader, args, device, rank, world_size) | ||
| 238 | + export_hf(model, tokenizer, args, architecture, rank, world_size, device, dense_names, expert_names) | ||
| 239 | + finally: | ||
| 240 | + if dist.is_initialized(): | ||
| 241 | + dist.destroy_process_group() | ||
| 242 | + | ||
| 243 | + | ||
| 244 | +if __name__ == "__main__": | ||
| 245 | + main() | ||