MCPcopy Create free account
hub / github.com/microsoft/BitNet / convert_back

Function convert_back

gpu/convert_safetensors.py:49–93  ·  view source on GitHub ↗
(
    safetensors_path: str,
    output_file: str,
    model_name: Optional[str] = None,
)

Source from the content-addressed store, hash-verified

47 return rearrange(w, '(h l d) i -> (h d l) i', h=config.n_local_heads, l=2)
48
49def convert_back(
50 safetensors_path: str,
51 output_file: str,
52 model_name: Optional[str] = None,
53):
54 st_dict = load_file(safetensors_path)
55
56 cfg = ModelArgs.from_name(model_name)
57 print(f"Using model configurations: {cfg}")
58
59 recovered: dict = {}
60
61 for layer in range(cfg.n_layer):
62 base = f"model.layers.{layer}."
63
64 wq = st_dict[f"{base}self_attn.q_proj.weight"]
65 wk = st_dict[f"{base}self_attn.k_proj.weight"]
66 wv = st_dict[f"{base}self_attn.v_proj.weight"]
67
68 wq = invert_convert_q(wq, cfg)
69 wk = invert_convert_k(wk, cfg)
70
71 wqkv = torch.cat([wq, wk, wv], dim=0)
72 recovered[f"layers.{layer}.attention.wqkv.weight"] = wqkv
73
74 recovered[f"layers.{layer}.attention.wo.weight"] = st_dict[f"{base}self_attn.o_proj.weight"]
75
76 recovered[f"layers.{layer}.attention_norm.weight"] = st_dict[f"{base}input_layernorm.weight"]
77 recovered[f"layers.{layer}.ffn_norm.weight"] = st_dict[f"{base}post_attention_layernorm.weight"]
78 recovered[f"layers.{layer}.attention.attn_sub_norm.weight"] = st_dict[f"{base}self_attn.attn_sub_norm.weight"]
79 recovered[f"layers.{layer}.feed_forward.ffn_sub_norm.weight"] = st_dict[f"{base}mlp.ffn_sub_norm.weight"]
80
81 gate = st_dict[f"{base}mlp.gate_proj.weight"]
82 up = st_dict[f"{base}mlp.up_proj.weight"]
83 w13 = torch.cat([gate, up], dim=0)
84 recovered[f"layers.{layer}.feed_forward.w13.weight"] = w13
85
86 recovered[f"layers.{layer}.feed_forward.w2.weight"] = st_dict[f"{base}mlp.down_proj.weight"]
87
88 recovered["tok_embeddings.weight"] = st_dict["model.embed_tokens.weight"]
89 recovered["output.weight"] = st_dict["model.embed_tokens.weight"]
90 recovered["norm.weight"] = st_dict["model.norm.weight"]
91
92 print(f"Saving to {output_file}")
93 torch.save(recovered, output_file)
94
95if __name__ == "__main__":
96 import argparse

Callers 1

Calls 3

invert_convert_qFunction · 0.85
invert_convert_kFunction · 0.85
from_nameMethod · 0.80

Tested by

no test coverage detected