From 87e7cf6896fef4fe7f12a31add1a65ec62a360bd Mon Sep 17 00:00:00 2001 From: Zilin Zhu Date: Mon, 12 Jan 2026 06:38:38 +0000 Subject: [PATCH] [refactor] refactor int4 qat code --- examples/low_precision/README.md | 17 +++++------------ .../run-kimi-k2-Thinking-int4.sh | 9 +-------- .../run-moonlight-16B-A3B-int4.sh | 9 +-------- .../low_precision/run-qwen3-235B-A22B-int4.sh | 9 +-------- .../low_precision/run-qwen3-30B-A3B-int4.sh | 9 +-------- examples/low_precision/run-qwen3-4b-fp8.sh | 11 +---------- .../megatron_utils/megatron_to_hf/__init__.py | 6 +----- .../megatron_to_hf/processors/__init__.py | 15 +++++++++++++++ .../quantizer_compressed_tensors.py} | 19 ++++++++----------- .../{quantizer.py => quantizer_fp8.py} | 12 +----------- .../update_weight_from_distributed.py | 4 ++-- .../update_weight_from_tensor.py | 4 ++-- slime/utils/arguments.py | 5 ----- tools/convert_hf_to_hf_int4.py | 4 ++-- 14 files changed, 41 insertions(+), 92 deletions(-) rename slime/{utils/int4_kernel.py => backends/megatron_utils/megatron_to_hf/processors/quantizer_compressed_tensors.py} (92%) rename slime/backends/megatron_utils/megatron_to_hf/processors/{quantizer.py => quantizer_fp8.py} (90%) diff --git a/examples/low_precision/README.md b/examples/low_precision/README.md index 87b8e3a960..32fd6bfda4 100644 --- a/examples/low_precision/README.md +++ b/examples/low_precision/README.md @@ -85,14 +85,7 @@ This guide provides examples for INT4 STE (Straight-Through Estimator) training ### Quick Start -#### 1. Configure Training Arguments -Ensure your training script is properly configured. For training tasks, you must add the following flag to your launch arguments: - -```bash ---int4-params-rollout -``` - -#### 2. Convert HuggingFace Weights to INT4 +#### 1. Convert HuggingFace Weights to INT4 First, download the PTQ (Post-Training Quantization) calibration dataset from HuggingFace: [https://huggingface.co/datasets/Salesforce/wikitext/tree/main/wikitext-2-raw-v1](https://huggingface.co/datasets/Salesforce/wikitext/tree/main/wikitext-2-raw-v1) @@ -100,12 +93,12 @@ Next, use the `tools/convert_hf_to_hf_int4.py` script to convert BF16 weights to ```bash python tools/convert_hf_to_hf_int4.py \ - --model_id /path/to/your/original/models \ - --output_dir /path/to/your/save/models \ - --local_data_path /path/to/your/wikitext + --input-dir /path/to/your/original/models \ + --output-dir /path/to/your/save/models \ + --data-dir /path/to/your/wikitext ``` -#### 3. Start INT4 Training +#### 2. Start INT4 Training You need to configure the specific environment variables for quantization settings. diff --git a/examples/low_precision/run-kimi-k2-Thinking-int4.sh b/examples/low_precision/run-kimi-k2-Thinking-int4.sh index 3f4b707a84..0cbfe20889 100644 --- a/examples/low_precision/run-kimi-k2-Thinking-int4.sh +++ b/examples/low_precision/run-kimi-k2-Thinking-int4.sh @@ -155,12 +155,6 @@ MISC_ARGS=( --no-check-for-nan-in-loss-and-grad ) -PRECISE_ARGS=( - --transformer-impl transformer_engine - --bf16 - --int4-params-rollout -) - # Build the runtime environment JSON with proper variable substitution RUNTIME_ENV_JSON="{ \"env_vars\": { @@ -192,5 +186,4 @@ ray job submit --address="http://127.0.0.1:8265" \ ${PERF_ARGS[@]} \ ${EVAL_ARGS[@]} \ ${SGLANG_ARGS[@]} \ - ${MISC_ARGS[@]} \ - ${PRECISE_ARGS[@]} \ No newline at end of file + ${MISC_ARGS[@]} \ No newline at end of file diff --git a/examples/low_precision/run-moonlight-16B-A3B-int4.sh b/examples/low_precision/run-moonlight-16B-A3B-int4.sh index 0ad1375736..47c38b4b71 100644 --- a/examples/low_precision/run-moonlight-16B-A3B-int4.sh +++ b/examples/low_precision/run-moonlight-16B-A3B-int4.sh @@ -132,12 +132,6 @@ MISC_ARGS=( --moe-token-dispatcher-type flex ) -PRECISE_ARGS=( - --transformer-impl transformer_engine - --bf16 - --int4-params-rollout -) - # launch the master node of ray in container export MASTER_ADDR=${MASTER_ADDR:-"127.0.0.1"} ray start --head --node-ip-address ${MASTER_ADDR} --num-gpus 4 --disable-usage-stats --dashboard-host=0.0.0.0 --dashboard-port=8265 @@ -168,5 +162,4 @@ ray job submit --address="http://127.0.0.1:8265" \ ${PERF_ARGS[@]} \ ${EVAL_ARGS[@]} \ ${SGLANG_ARGS[@]} \ - ${MISC_ARGS[@]} \ - ${PRECISE_ARGS[@]} + ${MISC_ARGS[@]} diff --git a/examples/low_precision/run-qwen3-235B-A22B-int4.sh b/examples/low_precision/run-qwen3-235B-A22B-int4.sh index 59f3018ea9..b74add7ec1 100644 --- a/examples/low_precision/run-qwen3-235B-A22B-int4.sh +++ b/examples/low_precision/run-qwen3-235B-A22B-int4.sh @@ -139,12 +139,6 @@ MISC_ARGS=( # --moe-token-dispatcher-type flex ) -PRECISE_ARGS=( - --transformer-impl transformer_engine - --bf16 - --int4-params-rollout -) - # Build the runtime environment JSON with proper variable substitution RUNTIME_ENV_JSON="{ \"env_vars\": { @@ -174,5 +168,4 @@ ray job submit --address="http://127.0.0.1:8265" \ ${PERF_ARGS[@]} \ ${EVAL_ARGS[@]} \ ${SGLANG_ARGS[@]} \ - ${MISC_ARGS[@]} \ - ${PRECISE_ARGS[@]} \ No newline at end of file + ${MISC_ARGS[@]} \ No newline at end of file diff --git a/examples/low_precision/run-qwen3-30B-A3B-int4.sh b/examples/low_precision/run-qwen3-30B-A3B-int4.sh index 3c9d2b8ca3..5fd8093c6f 100644 --- a/examples/low_precision/run-qwen3-30B-A3B-int4.sh +++ b/examples/low_precision/run-qwen3-30B-A3B-int4.sh @@ -131,12 +131,6 @@ MISC_ARGS=( # --moe-token-dispatcher-type flex ) -PRECISE_ARGS=( - --transformer-impl transformer_engine - --bf16 - --int4-params-rollout -) - # launch the master node of ray in container export MASTER_ADDR=${MASTER_ADDR:-"127.0.0.1"} ray start --head --node-ip-address ${MASTER_ADDR} --num-gpus 8 --disable-usage-stats --dashboard-host=0.0.0.0 --dashboard-port=8265 @@ -167,6 +161,5 @@ ray job submit --address="http://127.0.0.1:8265" \ ${PERF_ARGS[@]} \ ${EVAL_ARGS[@]} \ ${SGLANG_ARGS[@]} \ - ${MISC_ARGS[@]} \ - ${PRECISE_ARGS[@]} + ${MISC_ARGS[@]} \ No newline at end of file diff --git a/examples/low_precision/run-qwen3-4b-fp8.sh b/examples/low_precision/run-qwen3-4b-fp8.sh index 61672f86c2..f376ceeee9 100644 --- a/examples/low_precision/run-qwen3-4b-fp8.sh +++ b/examples/low_precision/run-qwen3-4b-fp8.sh @@ -120,14 +120,6 @@ MISC_ARGS=( --attention-backend flash ) -PRECISE_ARGS=( - --transformer-impl transformer_engine - --bf16 - --fp8-format e4m3 - --fp8-recipe blockwise - --fp8-param-gather -) - # launch the master node of ray in container export MASTER_ADDR=${MASTER_ADDR:-"127.0.0.1"} @@ -159,5 +151,4 @@ ray job submit --address="http://127.0.0.1:8265" \ ${PERF_ARGS[@]} \ ${EVAL_ARGS[@]} \ ${SGLANG_ARGS[@]} \ - ${MISC_ARGS[@]} \ - ${PRECISE_ARGS[@]} \ No newline at end of file + ${MISC_ARGS[@]} \ No newline at end of file diff --git a/slime/backends/megatron_utils/megatron_to_hf/__init__.py b/slime/backends/megatron_utils/megatron_to_hf/__init__.py index ba5a286a37..84ff899aa5 100644 --- a/slime/backends/megatron_utils/megatron_to_hf/__init__.py +++ b/slime/backends/megatron_utils/megatron_to_hf/__init__.py @@ -3,8 +3,7 @@ from .glm4moe import convert_glm4moe_to_hf from .llama import convert_llama_to_hf from .mimo import convert_mimo_to_hf -from .processors.padding_remover import remove_padding -from .processors.quantizer import quantize_params +from .processors import quantize_params, remove_padding from .qwen2 import convert_qwen2_to_hf from .qwen3_next import convert_qwen3_next_to_hf from .qwen3moe import convert_qwen3moe_to_hf @@ -23,9 +22,6 @@ def convert_to_hf(args, model_name, name, param, quantization_config=None): converted_named_tensors = _convert_to_hf_core(args, model_name, name, param) - if not quantization_config: - return converted_named_tensors - return quantize_params(args, name, converted_named_tensors, quantization_config) diff --git a/slime/backends/megatron_utils/megatron_to_hf/processors/__init__.py b/slime/backends/megatron_utils/megatron_to_hf/processors/__init__.py index e69de29bb2..0141c3548c 100644 --- a/slime/backends/megatron_utils/megatron_to_hf/processors/__init__.py +++ b/slime/backends/megatron_utils/megatron_to_hf/processors/__init__.py @@ -0,0 +1,15 @@ +from .padding_remover import remove_padding +from .quantizer_compressed_tensors import quantize_params_compressed_tensors +from .quantizer_fp8 import quantize_params_fp8 + +__all__ = ["remove_padding", "quantize_param", "quantize_params_fp8", "quantize_params_compressed_tensors"] + + +def quantize_params(args, megatron_name, converted_named_params, quantization_config): + if quantization_config is None: + return converted_named_params + elif quantization_config["quant_method"] == "fp8": + return quantize_params_fp8(args, megatron_name, converted_named_params, quantization_config) + elif quantization_config["quant_method"] == "compressed-tensors": + # only int4 at the moment. + return quantize_params_compressed_tensors(converted_named_params, quantization_config) diff --git a/slime/utils/int4_kernel.py b/slime/backends/megatron_utils/megatron_to_hf/processors/quantizer_compressed_tensors.py similarity index 92% rename from slime/utils/int4_kernel.py rename to slime/backends/megatron_utils/megatron_to_hf/processors/quantizer_compressed_tensors.py index 8ee031bcc8..41712b33a8 100644 --- a/slime/utils/int4_kernel.py +++ b/slime/backends/megatron_utils/megatron_to_hf/processors/quantizer_compressed_tensors.py @@ -8,6 +8,9 @@ logger = logging.getLogger(__name__) +__all__ = ["quantize_params_compressed_tensors"] + + def pack_to_int32( value: torch.Tensor, num_bits: int, @@ -127,15 +130,11 @@ def int4_block_quantize(x: torch.Tensor, group_size: int = 128) -> tuple[torch.T return out, scale_out, zero_out -def _quantize_params_int4(converted_named_params, quantization_config): - - try: - w_cfg = quantization_config["config_groups"]["group_0"]["weights"] - group_size = w_cfg["group_size"] - is_symmetric = w_cfg["symmetric"] - ignore_rules = quantization_config.get("ignore", []) - except KeyError as e: - raise ValueError(f"Invalid quantization_config: missing {e}") from e +def quantize_params_compressed_tensors(converted_named_params, quantization_config): + w_cfg = quantization_config["config_groups"]["group_0"]["weights"] + group_size = w_cfg["group_size"] + is_symmetric = w_cfg["symmetric"] + ignore_rules = quantization_config.get("ignore", []) results = [] @@ -143,8 +142,6 @@ def _quantize_params_int4(converted_named_params, quantization_config): is_ignored = any((r.startswith("re:") and re.match(r[3:], name)) or r == name for r in ignore_rules) if is_ignored or not name.endswith(".weight") or param.dim() < 2: - if is_ignored: - logger.info(f"Ignoring parameter: {name}") results.append((name, param)) continue diff --git a/slime/backends/megatron_utils/megatron_to_hf/processors/quantizer.py b/slime/backends/megatron_utils/megatron_to_hf/processors/quantizer_fp8.py similarity index 90% rename from slime/backends/megatron_utils/megatron_to_hf/processors/quantizer.py rename to slime/backends/megatron_utils/megatron_to_hf/processors/quantizer_fp8.py index 9d02aa9369..7e2ad908de 100644 --- a/slime/backends/megatron_utils/megatron_to_hf/processors/quantizer.py +++ b/slime/backends/megatron_utils/megatron_to_hf/processors/quantizer_fp8.py @@ -4,20 +4,10 @@ from slime.utils.fp8_kernel import blockwise_cast_to_fp8_triton -from slime.utils.int4_kernel import _quantize_params_int4 - from ...sglang import quant_weight_ue8m0, should_deepgemm_weight_requant_ue8m0, transform_scale_ue8m0 -def quantize_params(args, megatron_name, converted_named_params, quantization_config): - if quantization_config is None: - return converted_named_params - - quant_method = quantization_config.get("quant_method") - - if args.int4_params_rollout and quant_method == "compressed-tensors": - return _quantize_params_int4(converted_named_params, quantization_config) - +def quantize_params_fp8(args, megatron_name, converted_named_params, quantization_config): assert quantization_config["quant_method"] == "fp8" assert quantization_config["fmt"] == "e4m3" assert quantization_config["activation_scheme"] == "dynamic" diff --git a/slime/backends/megatron_utils/update_weight/update_weight_from_distributed.py b/slime/backends/megatron_utils/update_weight/update_weight_from_distributed.py index 498fda525c..93680fe3a3 100644 --- a/slime/backends/megatron_utils/update_weight/update_weight_from_distributed.py +++ b/slime/backends/megatron_utils/update_weight/update_weight_from_distributed.py @@ -83,7 +83,7 @@ def update_weights(self) -> None: dist.barrier(group=get_gloo_group()) # int4/fp4 pre_process - if self.args.int4_params_rollout: + if self.quantization_config.get("quant_method") in ["compressed-tensors"]: ray.get( post_process_weights( restore_weights_before_load=True, @@ -128,7 +128,7 @@ def update_weights(self) -> None: dist.barrier(group=get_gloo_group()) # int4/fp4 post_process - if self.args.int4_params_rollout: + if self.quantization_config.get("quant_method") in ["compressed-tensors"]: ray.get( post_process_weights( restore_weights_before_load=False, diff --git a/slime/backends/megatron_utils/update_weight/update_weight_from_tensor.py b/slime/backends/megatron_utils/update_weight/update_weight_from_tensor.py index 32a1faa9b2..b5fad117a0 100644 --- a/slime/backends/megatron_utils/update_weight/update_weight_from_tensor.py +++ b/slime/backends/megatron_utils/update_weight/update_weight_from_tensor.py @@ -115,7 +115,7 @@ def update_weights(self) -> None: ray.get([engine.flush_cache.remote() for engine in self.rollout_engines]) dist.barrier(group=get_gloo_group()) - if self.args.int4_params_rollout: + if self.quantization_config.get("quant_method") in ["compressed-tensors"]: ray.get( post_process_weights( restore_weights_before_load=True, @@ -135,7 +135,7 @@ def update_weights(self) -> None: dist.barrier(group=get_gloo_group()) # int4/fp4 post_process - if self.args.int4_params_rollout: + if self.quantization_config.get("quant_method") in ["compressed-tensors"]: ray.get( post_process_weights( restore_weights_before_load=False, diff --git a/slime/utils/arguments.py b/slime/utils/arguments.py index 6e209666c3..33f0dc1969 100644 --- a/slime/utils/arguments.py +++ b/slime/utils/arguments.py @@ -431,11 +431,6 @@ def add_rollout_arguments(parser): nargs="+", help="Address and ports of the external engines.", ) - parser.add_argument( - "--int4-params-rollout", - action="store_true", - help="Use int4 params to rollout, only support in int4 qat rl", - ) return parser def add_fault_tolerance_arguments(parser): diff --git a/tools/convert_hf_to_hf_int4.py b/tools/convert_hf_to_hf_int4.py index 7860ce8f17..ba76a987f6 100644 --- a/tools/convert_hf_to_hf_int4.py +++ b/tools/convert_hf_to_hf_int4.py @@ -12,9 +12,9 @@ def parse_args(): parser = argparse.ArgumentParser() - parser.add_argument("--model-id", type=str, required=True, help="local BF16 path") + parser.add_argument("--input-dir", type=str, required=True, help="local BF16 path") parser.add_argument("--output-dir", type=str, required=True) - parser.add_argument("--local-data-path", type=str, required=True, help="dataset path") + parser.add_argument("--data-dir", type=str, required=True, help="dataset path") parser.add_argument("--quant-type", type=str, choices=["W4A16", "W8A16"], default="W4A16") parser.add_argument("--num-calibration-samples", type=int, default=256, help="sample nums") parser.add_argument("--max-sequence-length", type=int, default=2048)