"""INT8 (W8A8 dynamic-token) quantization of google/embeddinggemma-2 into a compressed-tensors checkpoint that vLLM loads as CompressedTensorsW8A8Int8. Pure-torch per-output-channel symmetric INT8 weight quant + config.json quantization_config with format "int-quantized". No calibration data needed: activations are quantized dynamically per token at runtime by vLLM, so the checkpoint only needs `weight` (int8) and `weight_scale` (fp32 [out,1]). """ import json import os import shutil import time import torch from safetensors import safe_open from transformers import AutoModel import sys SRC = sys.argv[1] if len(sys.argv) > 1 else "/models/embeddinggemma-2" DST = sys.argv[2] if len(sys.argv) > 2 else "/models/embeddinggemma-2-int8" EPS = 1e-10 QCFG = { "quant_method": "compressed-tensors", "activation_scheme": "dynamic", "format": "int-quantized", "global_schema": None, "config_groups": { "group_0": { "targets": ["Linear"], "weights": { "num_bits": 8, "type": "int", "strategy": "channel", "symmetric": True, "dynamic": False, "group_size": None, "actorder": None, "block_structure": None, "observer": "minmax", "observer_kwargs": {}, "scale_dtype": None, "zp_dtype": None, }, "input_activations": { "num_bits": 8, "type": "int", "strategy": "token", "symmetric": True, "dynamic": True, "group_size": None, "actorder": None, "block_structure": None, "observer": "minmax", "observer_kwargs": {}, "scale_dtype": None, "zp_dtype": None, }, "format": "int-quantized", } }, "ignore": [], } def log(*a): print(*a, flush=True) t0 = time.time() if os.path.exists(DST): log("removing existing", DST) shutil.rmtree(DST) log("loading bf16 model from", SRC) model = AutoModel.from_pretrained(SRC, dtype=torch.bfloat16) model.eval() n = 0 skipped = 0 with torch.no_grad(): for name, mod in model.named_modules(): if not isinstance(mod, torch.nn.Linear): continue w = mod.weight.detach().to(torch.float32) if w.ndim != 2: skipped += 1 continue absmax = w.abs().amax(dim=1, keepdim=True) scale = (absmax / 127.5).clamp_(min=EPS) q = torch.clamp(torch.round(w / scale), -128, 127) assert q.abs().max().item() <= 128 mod.weight.requires_grad_(False) mod.weight.data = q.to(torch.int8) for old in ("weight_scale", "weight_scale_inv"): if hasattr(mod, old): delattr(mod, old) mod.register_buffer("weight_scale", scale.to(torch.float32)) n += 1 log(f"quantized {n} linear modules ({skipped} non-2d skipped) in {time.time()-t0:.0f}s") # copy everything except the bf16 weight shard (save_pretrained rewrites # config.json + model.safetensors) os.makedirs(DST, exist_ok=True) for entry in os.listdir(SRC): if entry in ("model.safetensors", "config.json") or entry.endswith(".safetensors"): continue s, d = os.path.join(SRC, entry), os.path.join(DST, entry) if os.path.isdir(s): shutil.copytree(s, d) else: shutil.copy2(s, d) log("saving to", DST) model.save_pretrained(DST, safe_serialization=True) cfg_path = os.path.join(DST, "config.json") with open(cfg_path) as f: cfg = json.load(f) cfg["quantization_config"] = QCFG with open(cfg_path, "w") as f: json.dump(cfg, f, indent=2, sort_keys=True) # ---- verify what actually landed on disk shard = os.path.join(DST, "model.safetensors") n_int8 = n_scale = 0 samples = [] with safe_open(shard, framework="pt") as f: keys = list(f.keys()) for k in keys: if k.endswith("weight_scale"): n_scale += 1 meta = f.metadata() if hasattr(f, "metadata") else None for k in keys: sl = f.get_slice(k) if sl.get_dtype() == "I8" and k.endswith("weight"): n_int8 += 1 if len(samples) < 3: samples.append((k, sl.get_shape())) log(f"shard {os.path.getsize(shard)/1e6:.1f} MB, {len(keys)} tensors, " f"int8 weights={n_int8}, weight_scale={n_scale}") for k, s in samples: log(" int8 example:", k, s) total = sum( os.path.getsize(os.path.join(dp, fn)) for dp, _, fns in os.walk(DST) for fn in fns ) log(f"DONE in {time.time()-t0:.0f}s — total size: {total/1e6:.1f} MB")