"""Rebuild approximate bf16 weights from the int8 shards. python dequantize.py # list layers and their base tensor names python dequantize.py # print the reconstructed weight's shape and stats W[out, in] = w8[in, out] * scale[out] * recip[in] """ import json, sys from safetensors import safe_open FIRST = 56 SLOTS = [(("linear_attn.in_proj_qkv", "linear_attn.in_proj_z"), ("self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj")), (("linear_attn.out_proj",), ("self_attn.o_proj",)), (("mlp.gate_proj", "mlp.up_proj"),) * 2, (("mlp.down_proj",),) * 2] def base_names(name, full_attention): block, slot = divmod(int(name.split("_")[0]) - FIRST, 4) return [f"model.language_model.layers.{block}.{t}.weight" for t in SLOTS[slot][1 if full_attention else 0]] def weight(repo, name): meta = json.load(open(f"{repo}/int8_manifest.json"))["layers"][name] with safe_open(f"{repo}/{meta['shard']}", framework="pt") as f: w = f.get_tensor(name + ".w8").float().t() * f.get_tensor(name + ".scale")[:, None] if meta["smoothed"]: w = w * f.get_tensor(name + ".recip")[None, :] return w # rows are the stacked base tensors, in the order base_names() lists them if __name__ == "__main__": repo = sys.argv[1] layers = json.load(open(f"{repo}/int8_manifest.json"))["layers"] if len(sys.argv) > 2: w = weight(repo, sys.argv[2]) print(sys.argv[2], tuple(w.shape), "absmax", float(w.abs().max())) else: for name, meta in sorted(layers.items()): # every 4th block is full attention; its input projection is 14336 wide, linear attention's 16384 block = (int(name.split("_")[0]) - FIRST) // 4 print(name, base_names(name, full_attention=block % 4 == 3))