a8nova's picture
nnopt port: YOLO11n-MLX
56fa795 verified
Raw History Blame Contribute Delete
6.26 kB
"""Convert the ultralytics YOLO11n checkpoint (.pt) into fused fp32 weights (.npz) without torch.
The .pt is a torch zip archive whose data.pkl pickles the whole DetectionModel. We unpickle it with stub classes
(no ultralytics/torch import), rebuild every tensor from the raw storages with numpy, walk the nn.Module tree
(_parameters/_buffers/_modules) to get a state_dict, then fold each BatchNorm into its conv exactly like
utils/torch_utils.py fuse_conv_and_bn (BaseModel.fuse, done by the reference at predict time).
Usage: python convert.py yolo11n.pt out.npz
"""
import collections
import pickle
import sys
import zipfile
import numpy as np
_STORAGE_DTYPES = {
"HalfStorage": np.float16, "FloatStorage": np.float32, "DoubleStorage": np.float64,
"LongStorage": np.int64, "IntStorage": np.int32, "ShortStorage": np.int16,
"CharStorage": np.int8, "ByteStorage": np.uint8, "BoolStorage": np.bool_,
"BFloat16Storage": None,
}
class _Stub:
"""Stands in for any pickled class we do not need (ultralytics modules, torch.nn layers, devices...)."""
def __init__(self, *args, **kwargs):
self._args = args
def __setstate__(self, state):
if isinstance(state, dict):
self.__dict__.update(state)
else:
self._state = state
def __call__(self, *args, **kwargs): # e.g. a stubbed function used in REDUCE
return _Stub(*args)
class _Storage:
def __init__(self, dtype, data):
self.dtype, self.data = dtype, data
def _rebuild_tensor_v2(storage, offset, size, stride, *args, **kwargs):
arr = np.frombuffer(storage.data, dtype=storage.dtype)
if len(size) == 0:
return arr[offset].copy()
item = arr.itemsize
return np.lib.stride_tricks.as_strided(
arr[offset:], shape=tuple(size), strides=tuple(s * item for s in stride)
).copy()
def _rebuild_parameter(data, *args, **kwargs):
return data
class _Unpickler(pickle.Unpickler):
def __init__(self, f, zf, prefix):
super().__init__(f)
self.zf, self.prefix, self.cache = zf, prefix, {}
def find_class(self, module, name):
if module == "torch._utils" and name in ("_rebuild_tensor_v2", "_rebuild_tensor"):
return _rebuild_tensor_v2
if module == "torch._utils" and name in ("_rebuild_parameter", "_rebuild_parameter_with_state"):
return _rebuild_parameter
if module == "collections" and name == "OrderedDict":
return collections.OrderedDict
if module == "torch" and name in _STORAGE_DTYPES:
return name # storage type tag, resolved in persistent_load
return type(name, (_Stub,), {})
def persistent_load(self, pid):
kind, stype, key, _location, _numel = pid[:5]
assert kind == "storage", pid
if key not in self.cache:
dtype = _STORAGE_DTYPES[stype if isinstance(stype, str) else type(stype).__name__]
if dtype is None:
raise ValueError(f"unsupported storage {stype}")
self.cache[key] = _Storage(dtype, self.zf.read(f"{self.prefix}/data/{key}"))
return self.cache[key]
def load_checkpoint(path):
with zipfile.ZipFile(path) as zf:
pkl = [n for n in zf.namelist() if n.endswith("/data.pkl")][0]
prefix = pkl[: -len("/data.pkl")]
with zf.open(pkl) as f:
return _Unpickler(f, zf, prefix).load()
def state_dict(module, prefix=""):
out = collections.OrderedDict()
d = module.__dict__
for k, v in d.get("_parameters", {}).items():
if v is not None:
out[prefix + k] = v
for k, v in d.get("_buffers", {}).items():
if v is not None:
out[prefix + k] = v
for k, m in d.get("_modules", {}).items():
if m is not None:
out.update(state_dict(m, prefix + k + "."))
return out
def identity_act_convs(module, prefix=""):
"""Prefixes of Conv modules whose pickled `act` is nn.Identity (the checkpoint's act objects, not the class
defaults, decide the activation: e.g. this v8.3.0 checkpoint keeps SiLU on SPPF.cv1)."""
out = []
mods = module.__dict__.get("_modules", {})
if "conv" in mods and "act" in mods and type(mods["act"]).__name__ != "SiLU":
assert type(mods["act"]).__name__ == "Identity", (prefix, type(mods["act"]).__name__)
out.append(prefix)
for k, m in mods.items():
if m is not None:
out += identity_act_convs(m, prefix + k + ".")
return out
def fuse(sd):
"""Fold BN into the preceding conv: utils/torch_utils.py fuse_conv_and_bn (fuse_conv_bn_weights), in fp32."""
fused, used = collections.OrderedDict(), set()
for k in sd:
if k.endswith(".conv.weight") and k[: -len("conv.weight")] + "bn.weight" in sd:
p = k[: -len("conv.weight")]
w = sd[k].astype(np.float32)
gamma, beta = sd[p + "bn.weight"].astype(np.float32), sd[p + "bn.bias"].astype(np.float32)
mean, var = sd[p + "bn.running_mean"].astype(np.float32), sd[p + "bn.running_var"].astype(np.float32)
scale = gamma / np.sqrt(var + 1e-3) # bn.eps = 0.001 for every BN in this checkpoint
fused[p + "conv.weight"] = w * scale[:, None, None, None]
fused[p + "conv.bias"] = beta - mean * scale
used.update(p + s for s in ("conv.weight", "bn.weight", "bn.bias", "bn.running_mean",
"bn.running_var", "bn.num_batches_tracked"))
for k, v in sd.items(): # plain nn.Conv2d with bias (Detect cv2/cv3 last layers) and the DFL conv
if k not in used:
fused[k] = v.astype(np.float32)
return fused
def main():
src, dst = sys.argv[1], sys.argv[2]
ck = load_checkpoint(src)
model = ck["model"]
sd = state_dict(model)
fused = fuse(sd)
stride = np.asarray(model.__dict__.get("stride"), dtype=np.float32)
fused["__stride__"] = stride
ident = identity_act_convs(model)
fused["__identity_act__"] = np.asarray(ident)
np.savez(dst, **fused)
print(f"{src}: {len(sd)} tensors -> {len(fused) - 2} fused tensors, stride {stride.tolist()}, "
f"identity-act convs {ident} -> {dst}")
if __name__ == "__main__":
main()