(
safetensors_path: str,
output_file: str,
model_name: Optional[str] = None,
)
| 47 | return rearrange(w, '(h l d) i -> (h d l) i', h=config.n_local_heads, l=2) |
| 48 | |
| 49 | def 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 | |
| 95 | if __name__ == "__main__": |
| 96 | import argparse |
no test coverage detected