1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Copy the first decoder layers of an indexed Qwen3 checkpoint for acceptance."""
16
17import argparse
18import hashlib
19import json
20from pathlib import Path
21import re
22import shutil
23
24from safetensors import safe_open
25from safetensors.torch import save_file
26
27from rl.unified_execution.models import get_model_family
28
29
30def _file_digest(path: Path) -> str:
31 """Hash files without retaining checkpoint bytes in Python memory."""
32 digest = hashlib.sha256()
33 with path.open("rb") as stream:
34 for block in iter(lambda: stream.read(8 * 1024 * 1024), b""):
35 digest.update(block)
36 return digest.hexdigest()
37
38
39def prepare_checkpoint(source: Path, output: Path, layers: int) -> dict:
40 """Retain original tensor values and experts, changing only decoder depth.
41
42 Args:
43 source: Original directory with an indexed safetensors checkpoint.
44 output: New directory; existing directories are never overwritten.
45 layers: Positive number of initial decoder layers to retain.
46
47 Returns:
48 Source identity and exported shard hashes for numerical acceptance.
49 """
50 config = json.loads((source / "config.json").read_text(encoding="utf-8"))
51 get_model_family(config["model_type"])
52 if isinstance(layers, bool) or not isinstance(layers, int) or not 1 <= layers <= config["num_hidden_layers"]:
53 raise ValueError("layers must retain between one and the original number of decoder layers")
54 index = json.loads((source / "model.safetensors.index.json").read_text(encoding="utf-8"))
55 groups = {}
56 for name, filename in index["weight_map"].items():
57 match = re.match(r"model\.layers\.(\d+)\.", name)
58 if match is None or int(match[1]) < layers:
59 groups.setdefault(filename, []).append(name)
60 output.mkdir(parents=True, exist_ok=False)
61 config["num_hidden_layers"] = layers
62 if "max_window_layers" in config:
63 config["max_window_layers"] = min(config["max_window_layers"], layers)
64 if isinstance(config.get("layer_types"), list):
65 config["layer_types"] = config["layer_types"][:layers]
66 if isinstance(config.get("mlp_only_layers"), list):
67 config["mlp_only_layers"] = [index for index in config["mlp_only_layers"] if index < layers]
68 (output / "config.json").write_text(json.dumps(config, indent=2), encoding="utf-8")
69 for path in source.iterdir():
70 if path.is_file() and path.name.startswith(("tokenizer", "vocab", "merges", "generation_config",
71 "special_tokens", "chat_template")):
72 shutil.copy2(path, output / path.name)
73 manifest = {"source": str(source.resolve()), "layers": layers,
74 "source_config_sha256": _file_digest(source / "config.json"),
75 "source_index_sha256": _file_digest(source / "model.safetensors.index.json"), "shards": []}
76 exported = {"metadata": {"total_size": 0}, "weight_map": {}}
77 for number, (filename, names) in enumerate(sorted(groups.items()), 1):
78 with safe_open(source / filename, framework="pt", device="cpu") as checkpoint:
79 weights = {name: checkpoint.get_tensor(name) for name in names}
80 target = f"model-{number:05d}-of-{len(groups):05d}.safetensors"
81 save_file(weights, output / target, metadata={"format": "pt"})
82 exported["weight_map"].update({name: target for name in names})
83 exported["metadata"]["total_size"] += sum(value.numel() * value.element_size() for value in weights.values())
84 manifest["shards"].append({"source_file": filename, "output_file": target,
85 "tensors": len(names), "sha256": _file_digest(output / target)})
86 del weights
87 (output / "model.safetensors.index.json").write_text(json.dumps(exported, indent=2), encoding="utf-8")
88 manifest["output_config_sha256"] = _file_digest(output / "config.json")
89 manifest["output_index_sha256"] = _file_digest(output / "model.safetensors.index.json")
90 (output / "crop_manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
91 return manifest
92
93
94def verify_checkpoint(source: Path, output: Path, layers: int) -> None:
95 """Verify a reusable crop against source metadata and every exported tensor shard."""
96 manifest = json.loads((output / "crop_manifest.json").read_text(encoding="utf-8"))
97 if manifest["layers"] != layers:
98 raise ValueError("Existing checkpoint has a different decoder depth")
99 paths = ((source / "config.json", "source_config_sha256"),
100 (source / "model.safetensors.index.json", "source_index_sha256"),
101 (output / "config.json", "output_config_sha256"),
102 (output / "model.safetensors.index.json", "output_index_sha256"))
103 for path, key in paths:
104 if _file_digest(path) != manifest[key]:
105 raise ValueError(f"Checkpoint metadata differs from crop manifest: {path}")
106 for shard in manifest["shards"]:
107 if _file_digest(output / shard["output_file"]) != shard["sha256"]:
108 raise ValueError(f"Cropped checkpoint shard checksum failed: {shard['output_file']}")
109
110
111def main() -> None:
112 """Prepare a separate artifact without modifying the pretrained source."""
113 parser = argparse.ArgumentParser(description=__doc__)
114 parser.add_argument("--source", type=Path, required=True)
115 parser.add_argument("--output", type=Path, required=True)
116 parser.add_argument("--layers", type=int, default=4)
117 parser.add_argument("--reuse", action="store_true", help="Verify and reuse an existing crop")
118 args = parser.parse_args()
119 if args.reuse and args.output.exists():
120 verify_checkpoint(args.source, args.output, args.layers)
121 else:
122 prepare_checkpoint(args.source, args.output, args.layers)
123
124
125if __name__ == "__main__":
126 main()