"""Extract a YOLO11 checkpoint (ultralytics .pt) into a module-tree JSON + BN-fused fp32 weights (.npz). Runs on the build host with only torch + numpy: ultralytics classes are unpickled into inert stand-ins (no ultralytics import needed), and we read their attributes and child modules directly. usage: python export_weights.py yolo11n.pt OUT_DIR """ import json, os, pickle, sys, types import numpy as np import torch class _Stub: """Inert stand-in for any non-torch class in the pickle (ultralytics modules, namespaces...).""" def __init__(self, *a, **k): pass def __setstate__(self, state): if isinstance(state, tuple) and len(state) == 2: # (dict, slots) state = {**(state[0] or {}), **(state[1] or {})} if isinstance(state, dict): self.__dict__.update(state) _stub_types = {} class _Unpickler(pickle.Unpickler): def find_class(self, module, name): if module.startswith(("torch", "collections", "numpy", "builtins", "copyreg", "_codecs")) or module in ( "__builtin__", ): return super().find_class(module, name) key = f"{module}.{name}" if key not in _stub_types: _stub_types[key] = type(name, (_Stub,), {"_qualname": key}) return _stub_types[key] _pm = types.ModuleType("stub_pickle") _pm.Unpickler = _Unpickler _pm.load = lambda f, **kw: _Unpickler(f, **kw).load() _pm.__name__ = "pickle" def tname(m): return getattr(m, "_qualname", type(m).__module__ + "." + type(m).__name__).split(".")[-1] def children(m): return m.__dict__.get("_modules", {}) or {} def params(m): d = {} for k, v in (m.__dict__.get("_parameters", {}) or {}).items(): if v is not None: d[k] = v.detach().float() for k, v in (m.__dict__.get("_buffers", {}) or {}).items(): if v is not None: d[k] = v.detach().float() return d ATTRS = ("f", "i", "c", "add", "n", "num_heads", "head_dim", "key_dim", "scale", "nc", "nl", "reg_max", "no", "c1", "d", "dimension", "scale_factor", "mode", "kernel_size", "stride", "padding", "dilation", "groups", "in_channels", "out_channels", "eps", "end2end", "_end2end", "legacy", "xyxy") def jsonable(v): if isinstance(v, torch.Tensor): return v.tolist() if isinstance(v, (list, tuple)): return [jsonable(x) for x in v] if isinstance(v, (bool, int, float, str)) or v is None: return v return None def walk(m, path, weights, used): t = tname(m) node = {"type": t, "path": path} for a in ATTRS: if a in m.__dict__: node[a] = jsonable(m.__dict__[a]) ch = children(m) if "conv" in ch and "bn" in ch: # Conv / DWConv: Conv2d + BatchNorm2d (+act): fold BN into conv (ultralytics fuse_conv_and_bn) conv, bn = ch["conv"], ch["bn"] p, q = params(conv), params(bn) w = p["weight"] std = torch.sqrt(q["running_var"] + bn.eps) g = q["weight"] / std wf = w * g.view(-1, 1, 1, 1) bf = q["bias"] - q["running_mean"] * g + (p["bias"] * g if "bias" in p else 0) weights[path + ".w"] = wf.numpy().astype(np.float32) weights[path + ".b"] = bf.numpy().astype(np.float32) used.update(f"{path}.conv.{k}" for k in p) used.update(f"{path}.bn.{k}" for k in q) node.update(k=list(conv.kernel_size), s=list(conv.stride), p=list(conv.padding), g=conv.groups, cin=conv.in_channels, cout=conv.out_channels, act=tname(ch["act"]) if "act" in ch else "Identity") return node if t == "Conv2d": p = params(m) weights[path + ".w"] = p["weight"].numpy().astype(np.float32) if "bias" in p: weights[path + ".b"] = p["bias"].numpy().astype(np.float32) used.update(f"{path}.{k}" for k in p) node.update(k=list(m.kernel_size), s=list(m.stride), p=list(m.padding), g=m.groups, cin=m.in_channels, cout=m.out_channels) return node for k, v in params(m).items(): # e.g. Detect.stride buffers are attributes, not params; record any stray tensors weights[f"{path}.{k}"] = v.numpy() used.add(f"{path}.{k}") node["children"] = {k: walk(v, f"{path}.{k}", weights, used) for k, v in ch.items() if v is not None} return node def all_keys(m, path, out): for k, v in params(m).items(): out[f"{path}.{k}"] = tuple(v.shape) for k, v in children(m).items(): if v is not None: all_keys(v, f"{path}.{k}", out) def main(): src, out = sys.argv[1], sys.argv[2] os.makedirs(out, exist_ok=True) ckpt = torch.load(src, map_location="cpu", pickle_module=_pm, weights_only=False) model = ckpt.get("ema") or ckpt["model"] weights, used = {}, set() top = children(model)["model"] layers = [walk(l, f"model.{i}", weights, used) for i, l in children(top).items()] det = model.__dict__ keys = {} all_keys(top, "model", keys) names = det.get("names") meta = { "layers": layers, "stride": jsonable(det.get("stride")), "names": {int(k): v for k, v in names.items()} if isinstance(names, dict) else names, "yaml": det.get("yaml") if isinstance(det.get("yaml"), dict) else None, "keys_total": len(keys), "keys_used": len(used & set(keys)), "keys_unused": sorted(set(keys) - used), } with open(os.path.join(out, "model.json"), "w") as f: json.dump(meta, f, indent=1, default=lambda o: None) np.savez(os.path.join(out, "weights.npz"), **weights) with open(os.path.join(out, "keys.txt"), "w") as f: for k, s in keys.items(): f.write(f"{k}\t{list(s)}\t{'used' if k in used else 'UNUSED'}\n") print(f"keys: {len(keys)} total, {meta['keys_used']} used; unused: {meta['keys_unused'][:10]}") print(f"fused tensors: {len(weights)}, params: {sum(v.size for v in weights.values())}") if __name__ == "__main__": main()