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