geudrik/clairic-sm120-work / src_v2 /quantization /quantize_fp8_block128.py
geudrik's picture
download
raw
9.88 kB
"""Block-128 Dynamic FP8 (W8A8 E4M3) quantizer for Cloudflare/clairic on SM120.
Produces an SGLang / vLLM / Transformers compatible Block-128 FP8 checkpoint
matching `Qwen/Qwen3.8-27B-FP8` module boundaries while preserving:
- `lm_head`, `embed_tokens` in BF16 (exact lexical confidence, `p_null`, and `ClairicHead.read_slots`)
- `model.visual.*` (27-layer ViT + merger) in BF16 (exact OCR / receipt / multi-page PO fidelity)
- Gated DeltaNet recurrent/gating weights (`in_proj_a`, `in_proj_b`, `in_proj_ba`, `conv1d`, `A_log`, `dt_bias`, `norm`) in BF16/FP32
- All RMSNorms, QK-norms, `mtp.{fc,norm,pre_fc_norm_*}`, and `clair_head.safetensors` (FP32)
"""
from __future__ import annotations
import argparse
import json
import shutil
import time
from pathlib import Path
from typing import Any
import torch
from safetensors import safe_open
from safetensors.torch import save_file
BLOCK_SIZE = 128
FP8_DTYPE = torch.float8_e4m3fn
FP8_MAX = float(torch.finfo(FP8_DTYPE).max) # 448.0
CONVERTED_SUFFIXES = (
".mlp.gate_proj.weight",
".mlp.up_proj.weight",
".mlp.down_proj.weight",
".linear_attn.in_proj_qkv.weight",
".linear_attn.in_proj_z.weight",
".linear_attn.out_proj.weight",
".self_attn.q_proj.weight",
".self_attn.k_proj.weight",
".self_attn.v_proj.weight",
".self_attn.o_proj.weight",
)
def should_quantize_tensor(key: str, shape: tuple[int, ...]) -> bool:
if len(shape) != 2:
return False
if shape[0] % BLOCK_SIZE != 0 or shape[1] % BLOCK_SIZE != 0:
return False
if not (key.startswith("model.language_model.layers.") or key.startswith("mtp.layers.")):
return False
return key.endswith(CONVERTED_SUFFIXES)
def build_modules_to_not_convert(text_cfg: dict[str, Any], vis_cfg: dict[str, Any]) -> list[str]:
num_layers = int(text_cfg.get("num_hidden_layers", 64))
vis_depth = int(vis_cfg.get("depth", 27))
deepstack_indexes = list(vis_cfg.get("deepstack_visual_indexes", []))
items: list[str] = [
"lm_head",
"model.embed_tokens",
"model.language_model.embed_tokens",
"model.visual",
"visual",
"model.visual.patch_embed.proj",
"model.visual.pos_embed",
"model.visual.merger.norm",
"model.visual.merger.linear_fc1",
"model.visual.merger.linear_fc2",
"visual.patch_embed.proj",
"visual.pos_embed",
"visual.merger.norm",
"visual.merger.linear_fc1",
"visual.merger.linear_fc2",
"mtp.fc",
"mtp.norm",
"mtp.pre_fc_norm_embedding",
"mtp.pre_fc_norm_hidden",
]
for i in range(vis_depth):
for prefix in ("model.visual", "visual"):
items.extend(
[
f"{prefix}.blocks.{i}.attn.qkv",
f"{prefix}.blocks.{i}.attn.qkv_proj",
f"{prefix}.blocks.{i}.attn.proj",
f"{prefix}.blocks.{i}.mlp.linear_fc1",
f"{prefix}.blocks.{i}.mlp.linear_fc2",
]
)
for idx in range(len(deepstack_indexes)):
for prefix in ("model.visual", "visual"):
items.extend(
[
f"{prefix}.deepstack_merger_list.{idx}.norm",
f"{prefix}.deepstack_merger_list.{idx}.linear_fc1",
f"{prefix}.deepstack_merger_list.{idx}.linear_fc2",
]
)
for layer_idx in range(num_layers):
p = f"model.language_model.layers.{layer_idx}"
items.extend(
[
f"{p}.input_layernorm",
f"{p}.post_attention_layernorm",
f"{p}.mlp.gate",
f"{p}.mlp.shared_expert_gate",
f"{p}.linear_attn.A_log",
f"{p}.linear_attn.conv1d",
f"{p}.linear_attn.dt_bias",
f"{p}.linear_attn.in_proj_a",
f"{p}.linear_attn.in_proj_b",
f"{p}.linear_attn.in_proj_ba",
f"{p}.linear_attn.norm",
f"{p}.self_attn.q_norm",
f"{p}.self_attn.k_norm",
]
)
for mtp_idx in range(max(1, int(text_cfg.get("mtp_num_hidden_layers", 0)))):
mp = f"mtp.layers.{mtp_idx}"
items.extend(
[
f"{mp}.input_layernorm",
f"{mp}.post_attention_layernorm",
f"{mp}.mlp.gate",
f"{mp}.mlp.shared_expert_gate",
f"{mp}.self_attn.q_norm",
f"{mp}.self_attn.k_norm",
]
)
# Deduplicate while preserving order
return list(dict.fromkeys(items))
@torch.no_grad()
def quantize_weight_block128(
weight: torch.Tensor,
scale_dtype: torch.dtype = torch.bfloat16,
) -> tuple[torch.Tensor, torch.Tensor]:
out_f, in_f = weight.shape
blocks = weight.float().view(out_f // BLOCK_SIZE, BLOCK_SIZE, in_f // BLOCK_SIZE, BLOCK_SIZE)
amax = blocks.abs().amax(dim=(1, 3))
# Compute scale in BF16 (matching Qwen/Qwen3.8-27B-FP8) or FP32 with positive clamp
scale_f32 = torch.clamp(amax / FP8_MAX, min=1e-12)
scale_out = scale_f32.to(scale_dtype)
denom = scale_out.float()[:, None, :, None]
q = torch.clamp(blocks / denom, min=-FP8_MAX, max=FP8_MAX).to(FP8_DTYPE)
return q.reshape(out_f, in_f).contiguous(), scale_out.contiguous()
def copy_clairic_sidecars(src_dir: Path, dst_dir: Path) -> None:
for item in src_dir.iterdir():
if item.name in ("config.json", "model.safetensors.index.json"):
continue
if item.name.startswith("model-") and item.name.endswith(".safetensors"):
continue
if item.name == "__pycache__":
continue
target = dst_dir / item.name
if item.is_dir():
if target.exists():
shutil.rmtree(target)
shutil.copytree(item, target, ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
else:
shutil.copy2(item, target)
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--src-dir", default="/tmp/clairic")
ap.add_argument("--dst-dir", default="/tmp/clairic-fp8")
ap.add_argument("--scale-dtype", choices=["bfloat16", "float32"], default="bfloat16")
ap.add_argument("--enable-mtp-layer", action="store_true")
args = ap.parse_args()
src_dir = Path(args.src_dir).resolve()
dst_dir = Path(args.dst_dir).resolve()
dst_dir.mkdir(parents=True, exist_ok=True)
scale_dtype = torch.bfloat16 if args.scale_dtype == "bfloat16" else torch.float32
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
t0 = time.perf_counter()
cfg = json.loads((src_dir / "config.json").read_text())
src_index = json.loads((src_dir / "model.safetensors.index.json").read_text())
src_weight_map: dict[str, str] = src_index["weight_map"]
shards = sorted(set(src_weight_map.values()))
new_weight_map: dict[str, str] = {}
total_bytes = 0
quantized_count = 0
kept_count = 0
print(
f"Quantizing {len(shards)} shards from {src_dir} -> {dst_dir} on {device} (scale_dtype={args.scale_dtype})...",
flush=True,
)
for shard_idx, shard_name in enumerate(shards, start=1):
ts = time.perf_counter()
out_tensors: dict[str, torch.Tensor] = {}
with safe_open(src_dir / shard_name, framework="pt", device=str(device)) as f:
for key in f.keys():
t = f.get_tensor(key)
if should_quantize_tensor(key, tuple(t.shape)):
q_w, q_scale = quantize_weight_block128(t, scale_dtype=scale_dtype)
scale_key = f"{key}_scale_inv"
out_tensors[key] = q_w.cpu()
out_tensors[scale_key] = q_scale.cpu()
new_weight_map[key] = shard_name
new_weight_map[scale_key] = shard_name
total_bytes += q_w.numel() * q_w.element_size() + q_scale.numel() * q_scale.element_size()
quantized_count += 1
else:
t_cpu = t.cpu()
out_tensors[key] = t_cpu
new_weight_map[key] = shard_name
total_bytes += t_cpu.numel() * t_cpu.element_size()
kept_count += 1
del t
save_file(out_tensors, dst_dir / shard_name, metadata={"format": "pt"})
out_tensors.clear()
if device.type == "cuda":
torch.cuda.empty_cache()
print(
f" [{shard_idx:2d}/{len(shards)}] {shard_name} done in {time.perf_counter()-ts:.2f}s | quantized_so_far={quantized_count}",
flush=True,
)
text_cfg = cfg.get("text_config", cfg)
vis_cfg = cfg.get("vision_config", {})
if args.enable_mtp_layer:
text_cfg["mtp_num_hidden_layers"] = 1
cfg["quantization_config"] = {
"activation_scheme": "dynamic",
"fmt": "e4m3",
"quant_method": "fp8",
"weight_block_size": [BLOCK_SIZE, BLOCK_SIZE],
"modules_to_not_convert": build_modules_to_not_convert(text_cfg, vis_cfg),
}
(dst_dir / "config.json").write_text(json.dumps(cfg, indent=2) + "\n")
(dst_dir / "model.safetensors.index.json").write_text(
json.dumps(
{
"metadata": {"total_size": total_bytes},
"weight_map": dict(sorted(new_weight_map.items())),
},
indent=2,
)
+ "\n"
)
copy_clairic_sidecars(src_dir, dst_dir)
elapsed = time.perf_counter() - t0
print(
f"Done in {elapsed:.1f}s! quantized_modules={quantized_count}, kept_tensors={kept_count}, "
f"new_total_gib={total_bytes / (1024**3):.2f} GiB",
flush=True,
)
if __name__ == "__main__":
main()

Xet Storage Details

Size:
9.88 kB
·
Xet hash:
7913e8927b930aefc86d4b393d2bb8e1848191bb3b5cd701afd10824148d437f

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.