LaST-Net / extract_state.py
korallll's picture
Wrapper code (speech-spoof-bench)
f23135c verified
Raw History Blame Contribute Delete
1.51 kB
# Extract the model state dict from LaST-Net best.pt (weights_only=True + explicit numpy allow-list for the RNG-state metadata)
import sys, json, hashlib, torch, numpy as np, codecs
from safetensors.torch import save_file
F, OUT = sys.argv[1], sys.argv[2]
try:
ck = torch.load(F, map_location="cpu", weights_only=True); how = "weights_only=True"
except Exception as e:
print("plain weights_only failed:", str(e)[:300])
torch.serialization.add_safe_globals([np.core.multiarray._reconstruct, np.ndarray, np.dtype, codecs.encode] + [type(np.dtype(t)) for t in (np.uint32, np.float64, np.int64, np.float32)])
ck = torch.load(F, map_location="cpu", weights_only=True); how = "weights_only=True + safe_globals(numpy _reconstruct/ndarray/dtype, _codecs.encode, numpy dtype classes uint32/float64/int64/float32)"
print("load:", how)
print("top keys:", list(ck))
for k, v in ck.items():
if k not in ("model", "optimizer"):
s = repr(v); print(" ", k, type(v).__name__, s[:400])
sd = ck["model"]
print("n tensors", len(sd), "initialization", ck.get("initialization"), "epoch", ck.get("epoch"), "best", ck.get("best_mean_dev_eer"))
dt = {str(v.dtype) for v in sd.values()}; print("dtypes", dt)
sd = {k: v.contiguous().clone() for k, v in sd.items()}
save_file(sd, OUT, metadata={"source": "HF JunXueTech/LaST-Net@7b18ff0abff078c60745aaaaf5165e3f9542fa1b best.pt['model']",
"epoch": str(ck.get("epoch")), "train_args": json.dumps(ck.get("args"), default=str)})