Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 5 additions & 12 deletions examples/low_precision/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,27 +85,20 @@ 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)

Next, use the `tools/convert_hf_to_hf_int4.py` script to convert BF16 weights to INT4 format. Ensure that the `--hf-checkpoint` parameter points to a directory where `config.json` contains the correct `quantization_config`. Slime will automatically utilize INT4 quantization during weight updates.

```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.

Expand Down
9 changes: 1 addition & 8 deletions examples/low_precision/run-kimi-k2-Thinking-int4.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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\": {
Expand Down Expand Up @@ -192,5 +186,4 @@ ray job submit --address="http://127.0.0.1:8265" \
${PERF_ARGS[@]} \
${EVAL_ARGS[@]} \
${SGLANG_ARGS[@]} \
${MISC_ARGS[@]} \
${PRECISE_ARGS[@]}
${MISC_ARGS[@]}
9 changes: 1 addition & 8 deletions examples/low_precision/run-moonlight-16B-A3B-int4.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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[@]}
9 changes: 1 addition & 8 deletions examples/low_precision/run-qwen3-235B-A22B-int4.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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\": {
Expand Down Expand Up @@ -174,5 +168,4 @@ ray job submit --address="http://127.0.0.1:8265" \
${PERF_ARGS[@]} \
${EVAL_ARGS[@]} \
${SGLANG_ARGS[@]} \
${MISC_ARGS[@]} \
${PRECISE_ARGS[@]}
${MISC_ARGS[@]}
9 changes: 1 addition & 8 deletions examples/low_precision/run-qwen3-30B-A3B-int4.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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[@]}

11 changes: 1 addition & 10 deletions examples/low_precision/run-qwen3-4b-fp8.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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"}
Expand Down Expand Up @@ -159,5 +151,4 @@ ray job submit --address="http://127.0.0.1:8265" \
${PERF_ARGS[@]} \
${EVAL_ARGS[@]} \
${SGLANG_ARGS[@]} \
${MISC_ARGS[@]} \
${PRECISE_ARGS[@]}
${MISC_ARGS[@]}
6 changes: 1 addition & 5 deletions slime/backends/megatron_utils/megatron_to_hf/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)


Expand Down
Original file line number Diff line number Diff line change
@@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
logger = logging.getLogger(__name__)


__all__ = ["quantize_params_compressed_tensors"]


def pack_to_int32(
value: torch.Tensor,
num_bits: int,
Expand Down Expand Up @@ -127,24 +130,18 @@ 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 = []

for name, param in converted_named_params:
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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down
5 changes: 0 additions & 5 deletions slime/utils/arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
4 changes: 2 additions & 2 deletions tools/convert_hf_to_hf_int4.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading