tiny-ear-asr / code /tinyear /dequant.py
sanjithrj's picture
Tiny Ear ASR 19M: weights, ONNX, Core ML, ExecuTorch, TFLite
928abc1 verified
Raw History Blame Contribute Delete
1.3 kB
"""Load the FP8 / FP4 safetensors files back into normal float tensors (weight-only quantization; compute stays FP32/FP16)."""
import torch
from safetensors.torch import load_file
FP4 = torch.tensor([0, .5, 1, 1.5, 2, 3, 4, 6])
def load_quantized(path, shapes):
"""shapes: {param name: original shape} from a normal model's state_dict (the packed files do not store them)."""
raw, out = load_file(path), {}
for k, v in raw.items():
if k.endswith(".fp8"):
n = k[:-4]; out[n] = (v.float() * raw[n + ".scale"].float()).reshape(shapes[n])
elif k.endswith(".fp4"):
n = k[:-4]; code = torch.stack([v & 15, v >> 4], -1).reshape(v.shape[0], -1) # low nibble first
s = raw[n + ".blockscale"].float() * raw[n + ".tensorscale"].float()
blk = code.shape[1] // s.shape[1]; c = code.reshape(code.shape[0], -1, blk)
val = FP4[(c & 7).long()] * torch.where((c >> 3) == 1, -1.0, 1.0) * s.unsqueeze(-1)
size = 1
for d in shapes[n][1:]: size *= d
out[n] = val.reshape(code.shape[0], -1)[:, :size].reshape(shapes[n])
elif not (k.endswith(".scale") or k.endswith(".blockscale") or k.endswith(".tensorscale")):
out[k] = v.float() if v.is_floating_point() else v
return out