"""Load model-only Standard safetensors into an initialized native EP1 GPT. The caller constructs the matching native Megatron model from the published architecture. This is an explicit research-bundle loader, not Transformers AutoModel registration. No optimizer, tokenizer, or training state is needed. """ from __future__ import annotations import hashlib import json from pathlib import Path FORMAT = "mbt-native-standard-global-v1" LAYER_NAMES = ( "self_attention.linear_qkv.layer_norm_weight", "self_attention.linear_qkv.weight", "self_attention.q_layernorm.weight", "self_attention.k_layernorm.weight", "self_attention.linear_proj.weight", "pre_mlp_layernorm.weight", "mlp.router.weight", "mlp.router.expert_bias", "mlp.fc1_latent_proj.weight", "mlp.fc2_latent_proj.weight", "mlp.experts.experts.linear_fc1.weight", "mlp.experts.experts.linear_fc2.weight", ) def sha256(path): digest = hashlib.sha256() with Path(path).open("rb") as stream: for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): digest.update(block) return digest.hexdigest() def tensor_shapes(architecture): a = architecture if a.get("parallel_streams") or a.get("implementation") != "native_standard_gpt_no_forward_override": raise ValueError("Only the original sequential Standard architecture is supported") d, h, m, f, e, layers = (a[key] for key in ( "hidden_size", "kv_channels", "moe_latent_size", "moe_ffn_hidden_size", "num_moe_experts", "num_layers")) shapes = ((d,), (3*d, d), (h,), (h,), (d, d), (d,), (e, d), (e,), (m, d), (d, m), (e, 2*f, m), (e, m, f)) result = {"embedding.word_embeddings.weight": (a["vocabulary"], d), "decoder.final_layernorm.weight": (d,)} result.update({"decoder.layers." + name: (layers, *shape) for name, shape in zip(LAYER_NAMES, shapes, strict=True)}) return result def resolve_attribute(owner, name): for part in name.split("."): owner = getattr(owner, part) return owner def assign_to_native(model, values, architecture): """Copy every global tensor to native parameters and persistent QB buffers. Grouped Q/gate/K/V ordering, layer ordering, expert ordering and original BF16/FP32 precision are preserved. All model parameters and persistent buffers must be covered exactly once, allowing only tied aliases. """ import torch expected = tensor_shapes(architecture) if set(values) != set(expected): raise ValueError("Global model tensor keys differ from the architecture") covered = set() def copy(name, value): target = resolve_attribute(model, name) if id(target) in covered: raise ValueError("Duplicate native destination: " + name) dtype = torch.float32 if name.endswith("expert_bias") else torch.bfloat16 if tuple(target.shape) != tuple(value.shape) or target.dtype != value.dtype or target.dtype != dtype: raise ValueError("Native shape/dtype mismatch: " + name) target.copy_(value) covered.add(id(target)) with torch.inference_mode(): for name, value in values.items(): dtype = torch.float32 if name.endswith("expert_bias") else torch.bfloat16 if tuple(value.shape) != expected[name] or value.dtype != dtype or not bool(value.isfinite().all()): raise ValueError("Invalid tensor: " + name) if not name.startswith("decoder.layers."): copy(name, value) continue suffix = name.removeprefix("decoder.layers.") for layer in range(architecture["num_layers"]): base = f"decoder.layers.{layer}." if suffix.startswith("mlp.experts.experts."): fc = suffix.split(".")[-2] group = resolve_attribute(model, base + "mlp.experts." + fc) if getattr(group, "single_grouped_weight", False): copy(base + "mlp.experts." + fc + ".weight", value[layer]) else: for expert in range(architecture["num_moe_experts"]): copy(base + f"mlp.experts.{fc}.weight{expert}", value[layer, expert]) else: copy(base + suffix, value[layer]) required = dict(model.named_parameters(remove_duplicate=False)) for name, module in model.named_modules(): for key, value in module._buffers.items(): if value is not None and key not in module._non_persistent_buffers_set: required[f"{name}.{key}" if name else key] = value missing = [name for name, value in required.items() if id(value) not in covered] if missing: raise ValueError("Unmapped native model state: " + repr(missing)) model.eval() return {"mapped_native_tensors": len(covered), "global_tensors": len(values), "optimizer_loaded": False} def load_into_native(model, bundle, architecture): """Verify checksums, then load into a matching already-constructed model.""" from safetensors.torch import load_file directory = Path(bundle) config = json.loads((directory / "config.json").read_text()) manifest = json.loads((directory / "manifest.json").read_text()) if config.get("bundle_format") != FORMAT or manifest.get("bundle_format") != FORMAT: raise ValueError("Unsupported bundle format") if config["architecture"] != architecture: raise ValueError("Native constructor architecture differs from this bundle") for filename, key in (("config.json", "config_sha256"), ("model.safetensors", "weights_sha256")): if sha256(directory / filename) != manifest[key]: raise ValueError("Bundle checksum mismatch: " + filename) values = load_file(str(directory / "model.safetensors"), device="cpu") return assign_to_native(model, values, architecture)