ajh-code commited on
Commit
371a6d9
·
verified ·
1 Parent(s): 892585b

Add runtime/standard_transformer.py

Browse files
Files changed (1) hide show
  1. runtime/standard_transformer.py +262 -0
runtime/standard_transformer.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Load a complete sharded Mage-Flow NVFP4 transformer component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from contextlib import ExitStack
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+ from safetensors import safe_open
14
+
15
+ from packed_artifact import (
16
+ assign_tensor_by_name,
17
+ build_target_specs,
18
+ instantiate_mage_transformer_on_meta,
19
+ materialize_mage_rope_tensor_attributes,
20
+ set_child_module,
21
+ unregistered_meta_tensor_attribute_names,
22
+ )
23
+ from torch_ops_native import (
24
+ PackedNvfp4LinearNativeOp,
25
+ initialize_native_sm120_op,
26
+ )
27
+
28
+
29
+ class StandardCheckpointError(RuntimeError):
30
+ pass
31
+
32
+
33
+ def fail(message: str) -> None:
34
+ raise StandardCheckpointError(message)
35
+
36
+
37
+ def read_object(path: Path) -> dict[str, Any]:
38
+ try:
39
+ value = json.loads(path.read_text(encoding="utf-8"))
40
+ except (OSError, json.JSONDecodeError) as exc:
41
+ fail(f"cannot read JSON object {path}: {exc}")
42
+ if not isinstance(value, dict):
43
+ fail(f"expected a JSON object: {path}")
44
+ return value
45
+
46
+
47
+ def _component_path(component_dir: Path, relative: str) -> Path:
48
+ path = (component_dir / relative).resolve()
49
+ if not path.is_relative_to(component_dir):
50
+ fail(f"checkpoint index path escapes transformer component: {relative}")
51
+ if not path.is_file():
52
+ fail(f"checkpoint shard is missing: {relative}")
53
+ return path
54
+
55
+
56
+ def _quantized_keys(module_key: str) -> dict[str, str]:
57
+ return {
58
+ "packed_weight": f"{module_key}.packed_weight",
59
+ "weight_scales": f"{module_key}.weight_scales",
60
+ "weight_scale": f"{module_key}.weight_scale",
61
+ "bias": f"{module_key}.bias",
62
+ }
63
+
64
+
65
+ def _target_specs_for_config(depth: int, quant_config: dict[str, Any]) -> list[Any]:
66
+ all_specs = {spec.module_key: spec for spec in build_target_specs(depth)}
67
+ targets = quant_config.get("targets")
68
+ if not isinstance(targets, list) or not all(isinstance(name, str) for name in targets):
69
+ fail("transformer config has no valid target list")
70
+ if len(set(targets)) != len(targets):
71
+ fail("transformer target list contains duplicates")
72
+ missing = [name for name in targets if name not in all_specs]
73
+ if missing:
74
+ fail(f"transformer target list contains an unknown module: {missing[0]}")
75
+ declared_count = quant_config.get("target_count")
76
+ if declared_count != len(targets):
77
+ fail(
78
+ "transformer quantization target count mismatch: "
79
+ f"{declared_count!r} != {len(targets)}"
80
+ )
81
+ return [all_specs[name] for name in targets]
82
+
83
+
84
+ def _apply_runtime_defaults(quant_config: dict[str, Any]) -> dict[str, str]:
85
+ defaults = quant_config.get("native_runtime_defaults")
86
+ if not isinstance(defaults, dict):
87
+ return {}
88
+ applied: dict[str, str] = {}
89
+ mapping = {
90
+ "up_activation_scale_multiplier": "MAGE_NVFP4_UP_ACTIVATION_SCALE_MULTIPLIER",
91
+ "down_activation_scale_multiplier": "MAGE_NVFP4_DOWN_ACTIVATION_SCALE_MULTIPLIER",
92
+ "activation_scale_search": "MAGE_NVFP4_ACTIVATION_SCALE_SEARCH",
93
+ }
94
+ for key, env_name in mapping.items():
95
+ value = defaults.get(key)
96
+ if value is None:
97
+ continue
98
+ os.environ.setdefault(env_name, str(value))
99
+ applied[env_name] = os.environ[env_name]
100
+ return applied
101
+
102
+
103
+ def load_standard_native_transformer(
104
+ repo_root: str | Path,
105
+ device: torch.device,
106
+ ) -> tuple[nn.Module, dict[str, Any]]:
107
+ """Load a complete standard-layout component without a BF16 base download."""
108
+
109
+ repo_root = Path(repo_root).resolve()
110
+ component_dir = (repo_root / "transformer").resolve()
111
+ if not component_dir.is_relative_to(repo_root) or not component_dir.is_dir():
112
+ fail("repository has no transformer component")
113
+ if device.type != "cuda":
114
+ fail("the native resident transformer requires a CUDA destination")
115
+
116
+ config = read_object(component_dir / "config.json")
117
+ quant_config = config.get("quantization_config")
118
+ if not isinstance(quant_config, dict):
119
+ fail("transformer config has no quantization_config")
120
+ if quant_config.get("quant_method") != "mage_flow_nvfp4":
121
+ fail(
122
+ "unexpected transformer quantization method: "
123
+ f"{quant_config.get('quant_method')!r}"
124
+ )
125
+ if quant_config.get("quant_algo") != "NVFP4":
126
+ fail("transformer config does not declare NVFP4")
127
+
128
+ runtime_defaults = _apply_runtime_defaults(quant_config)
129
+ if not initialize_native_sm120_op(allow_python_schema_fallback=False):
130
+ fail("compiled native SM120 torch op did not load")
131
+
132
+ depth = int(config.get("depth", 0))
133
+ target_specs = _target_specs_for_config(depth, quant_config)
134
+ expected_targets = [spec.module_key for spec in target_specs]
135
+
136
+ metadata = read_object(component_dir / "nvfp4_metadata.json")
137
+ if metadata.get("artifact_kind") != (
138
+ "mage_flow_transformer_mlp_nvfp4_resident_v1"
139
+ ):
140
+ fail("unexpected transformer NVFP4 metadata kind")
141
+ non_target_keys = metadata.get("non_target_keys")
142
+ if not isinstance(non_target_keys, list) or not all(
143
+ isinstance(key, str) for key in non_target_keys
144
+ ):
145
+ fail("transformer NVFP4 metadata has no non-target key list")
146
+ recorded_targets = metadata.get("targets")
147
+ if not isinstance(recorded_targets, list) or not all(
148
+ isinstance(entry, dict) for entry in recorded_targets
149
+ ):
150
+ fail("transformer NVFP4 metadata has no valid targets list")
151
+ recorded_modules = [entry.get("module_key") for entry in recorded_targets]
152
+ if recorded_modules != expected_targets:
153
+ fail("transformer config targets do not match NVFP4 metadata targets")
154
+
155
+ index = read_object(
156
+ component_dir / "diffusion_pytorch_model.safetensors.index.json"
157
+ )
158
+ weight_map = index.get("weight_map")
159
+ if not isinstance(weight_map, dict) or not all(
160
+ isinstance(key, str) and isinstance(value, str)
161
+ for key, value in weight_map.items()
162
+ ):
163
+ fail("transformer checkpoint has no valid weight map")
164
+
165
+ quantized_keys = {
166
+ key
167
+ for spec in target_specs
168
+ for key in _quantized_keys(spec.module_key).values()
169
+ }
170
+ expected_keys = set(non_target_keys) | quantized_keys
171
+ actual_keys = set(weight_map)
172
+ if actual_keys != expected_keys:
173
+ missing = sorted(expected_keys - actual_keys)
174
+ unexpected = sorted(actual_keys - expected_keys)
175
+ fail(
176
+ "transformer checkpoint key coverage mismatch; "
177
+ f"missing={missing[:1]}, unexpected={unexpected[:1]}"
178
+ )
179
+ original_target_weights = {spec.weight_key for spec in target_specs}
180
+ leaked = sorted(actual_keys & original_target_weights)
181
+ if leaked:
182
+ fail(f"BF16 target weight leaked into quantized checkpoint: {leaked[0]}")
183
+
184
+ shard_names = sorted(set(weight_map.values()))
185
+ with ExitStack() as stack:
186
+ handles = {
187
+ name: stack.enter_context(
188
+ safe_open(
189
+ _component_path(component_dir, name),
190
+ framework="pt",
191
+ device="cpu",
192
+ )
193
+ )
194
+ for name in shard_names
195
+ }
196
+
197
+ def tensor(key: str) -> torch.Tensor:
198
+ try:
199
+ handle = handles[weight_map[key]]
200
+ except KeyError:
201
+ fail(f"tensor is absent from checkpoint index: {key}")
202
+ if key not in handle.keys():
203
+ fail(f"tensor is absent from its declared shard: {key}")
204
+ return handle.get_tensor(key)
205
+
206
+ model = instantiate_mage_transformer_on_meta(repo_root)
207
+ for spec in target_specs:
208
+ original = model.get_submodule(spec.module_key)
209
+ if not isinstance(original, nn.Linear):
210
+ fail(
211
+ f"expected target {spec.module_key} to be nn.Linear, "
212
+ f"found {type(original).__name__}"
213
+ )
214
+ keys = _quantized_keys(spec.module_key)
215
+ replacement = PackedNvfp4LinearNativeOp(
216
+ in_features=int(original.in_features),
217
+ out_features=int(original.out_features),
218
+ packed_weight=tensor(keys["packed_weight"]).to(device),
219
+ weight_scales=tensor(keys["weight_scales"]).to(device),
220
+ weight_scale=tensor(keys["weight_scale"]).to(device),
221
+ bias=tensor(keys["bias"]).to(device),
222
+ )
223
+ set_child_module(model, spec.module_key, replacement)
224
+
225
+ loaded_non_targets: list[str] = []
226
+ for key in non_target_keys:
227
+ assign_tensor_by_name(model, key, tensor(key).to(device))
228
+ loaded_non_targets.append(key)
229
+
230
+ materialized = materialize_mage_rope_tensor_attributes(model)
231
+ meta_parameters = [
232
+ name for name, value in model.named_parameters() if value.is_meta
233
+ ]
234
+ meta_buffers = [
235
+ name for name, value in model.named_buffers() if value.is_meta
236
+ ]
237
+ unregistered_meta = unregistered_meta_tensor_attribute_names(model)
238
+ if meta_parameters or meta_buffers or unregistered_meta:
239
+ fail(
240
+ "standard transformer loader left unresolved meta tensors: "
241
+ f"{(meta_parameters + meta_buffers + unregistered_meta)[:4]}"
242
+ )
243
+
244
+ report = {
245
+ "layout": "huggingface_sharded_component",
246
+ "checkpoint_shard_count": len(shard_names),
247
+ "checkpoint_tensor_count": len(actual_keys),
248
+ "loaded_non_target_tensor_count": len(loaded_non_targets),
249
+ "loaded_quantized_projection_count": len(target_specs),
250
+ "bf16_target_weight_reads": 0,
251
+ "meta_parameter_names": meta_parameters,
252
+ "meta_buffer_names": meta_buffers,
253
+ "materialized_unregistered_tensor_attribute_names": materialized,
254
+ "runtime_defaults_applied": runtime_defaults,
255
+ }
256
+ return model.eval().requires_grad_(False), report
257
+
258
+
259
+ __all__ = [
260
+ "StandardCheckpointError",
261
+ "load_standard_native_transformer",
262
+ ]