|
| 1 | +import argparse |
| 2 | +from typing import Dict |
| 3 | + |
| 4 | +import os |
| 5 | +from safetensors import safe_open |
| 6 | +import torch |
| 7 | + |
| 8 | +from torchtune.models.convert_weights import get_mapped_key |
| 9 | + |
| 10 | +# Standard _FROM_META weight mapping of Meta weights to TorchTune + additional bias weight mappings. |
| 11 | +_QWEN_3_FROM_META = { |
| 12 | + "tok_embeddings.weight": "model.embed_tokens.weight", |
| 13 | + "norm.weight": "model.norm.weight", |
| 14 | + "layers.{}.attention.wk.weight": "model.layers.{}.self_attn.k_proj.weight", |
| 15 | + "layers.{}.attention.k_norm_fn.weight": "model.layers.{}.self_attn.k_norm.weight", |
| 16 | + "layers.{}.attention.wq.weight": "model.layers.{}.self_attn.q_proj.weight", |
| 17 | + "layers.{}.attention.q_norm_fn.weight": "model.layers.{}.self_attn.q_norm.weight", |
| 18 | + "layers.{}.attention.wv.weight": "model.layers.{}.self_attn.v_proj.weight", |
| 19 | + "layers.{}.attention.wo.weight": "model.layers.{}.self_attn.o_proj.weight", |
| 20 | + "layers.{}.attention_norm.weight": "model.layers.{}.input_layernorm.weight", |
| 21 | + "layers.{}.ffn_norm.weight": "model.layers.{}.post_attention_layernorm.weight", |
| 22 | + # Note: gate_proj and up_proj are reversed, usually w1 is the up_proj, |
| 23 | + # w2 is the gate_proj, and activation is applied on the up_proj, but since |
| 24 | + # Qwen3 applies activation on the gate_proj, we just swap the gate_proj |
| 25 | + # and up_proj in the checkpoint itself as a hack. |
| 26 | + "layers.{}.feed_forward.w1.weight": "model.layers.{}.mlp.gate_proj.weight", |
| 27 | + "layers.{}.feed_forward.w2.weight": "model.layers.{}.mlp.down_proj.weight", |
| 28 | + "layers.{}.feed_forward.w3.weight": "model.layers.{}.mlp.up_proj.weight", |
| 29 | +} |
| 30 | + |
| 31 | + |
| 32 | +def qwen_3_tune_to_meta(state_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: |
| 33 | + """ |
| 34 | + Convert a state dict from torchtune's format to Meta's format. This function |
| 35 | + doesn't handle any sharding or splitting of state dicts. It follows the |
| 36 | + state_dict IN -> state_dict OUT pattern. |
| 37 | +
|
| 38 | + Args: |
| 39 | + state_dict (Dict[str, torch.Tensor]): State dict in torchtune's format. |
| 40 | +
|
| 41 | + Returns: |
| 42 | + Dict[str, torch.Tensor]: State dict in Meta's format. |
| 43 | + """ |
| 44 | + converted_state_dict = {} |
| 45 | + inverted_mapping_dict = {v: k for k, v in _QWEN_3_FROM_META.items()} |
| 46 | + |
| 47 | + for key, value in state_dict.items(): |
| 48 | + # Tied embeddings for 0.6b and 4b models. |
| 49 | + if key == "lm_head.weight": |
| 50 | + continue |
| 51 | + new_key = get_mapped_key(key, inverted_mapping_dict) |
| 52 | + converted_state_dict[new_key] = value |
| 53 | + |
| 54 | + converted_state_dict["output.weight"] = converted_state_dict[ |
| 55 | + "tok_embeddings.weight" |
| 56 | + ] |
| 57 | + |
| 58 | + return converted_state_dict |
| 59 | + |
| 60 | + |
| 61 | +def convert_weights(input_dir: str, output_file: str) -> None: |
| 62 | + print("Loading checkpoint...") |
| 63 | + sd = {} |
| 64 | + with safe_open(os.path.join(input_dir, "model.safetensors"), framework="pt", device="cpu") as f: |
| 65 | + for key in f.keys(): |
| 66 | + sd[key] = f.get_tensor(key) |
| 67 | + |
| 68 | + print("Converting checkpoint...") |
| 69 | + sd = qwen_3_tune_to_meta(sd) |
| 70 | + print("Saving checkpoint...") |
| 71 | + torch.save(sd, output_file) |
| 72 | + print("Done.") |
| 73 | + |
| 74 | + |
| 75 | +def main(): |
| 76 | + parser = argparse.ArgumentParser( |
| 77 | + description="Convert Qwen3 weights to Meta format." |
| 78 | + ) |
| 79 | + parser.add_argument( |
| 80 | + "input_dir", |
| 81 | + type=str, |
| 82 | + help="Path to directory containing checkpoint files", |
| 83 | + ) |
| 84 | + parser.add_argument("output", type=str, help="Path to the output checkpoint") |
| 85 | + |
| 86 | + args = parser.parse_args() |
| 87 | + convert_weights(args.input_dir, args.output) |
| 88 | + |
| 89 | + |
| 90 | +if __name__ == "__main__": |
| 91 | + main() |
0 commit comments