"""Check a .gigaam file against the original checkpoint, tensor by tensor.""" from __future__ import annotations import argparse import sys from pathlib import Path import numpy as np from safetensors.numpy import load_file ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(Path(__file__).resolve().parent)) import gigaam_bin # noqa: E402 WEIGHT_RMS = 0.3 def onnx_gates(value): """torch LSTM rows (i, f, g, o) reordered to ONNX (i, o, f, c).""" i, f, g, o = np.split(value, 4) return np.concatenate((i, o, f, g)) def expected(state): """Checkpoint tensors under the names and layouts the converter emits.""" out = {} for key, value in state.items(): value = value.astype(np.float32) name = key.removeprefix("model.") if name.startswith("encoder.encoder_embed."): out["frontend." + name.split(".", 2)[2]] = ( value[:, :, 0, 0] if "pointwise" in name and value.ndim == 4 else value ) elif name.startswith("encoder.encoder.encoders."): name = name.removeprefix("encoder.encoder.") if ".rope_bank." in name: continue if name.endswith("proj.weight") and name.count(".") == 3: value = value * (value.shape[1] ** -0.5 / WEIGHT_RMS) if name.endswith("depthwise_conv.weight"): value = value[:, 0, :] out[name] = value elif name == "encoder.encoder.out_norm.scale": out["out_norm.scale"] = value.reshape(1) elif name == "encoder.encoder.out_norm.eps": out["out_norm.eps_sq"] = (value * value).reshape(1) elif name.startswith("heads."): head, part, rest = name.split(".", 3)[1:] base = f"heads.{head}." if rest == "embed.weight": out[base + rest] = value elif rest.startswith("lstm.weight_ih"): out[base + "lstm.W"] = onnx_gates(value) elif rest.startswith("lstm.weight_hh"): out[base + "lstm.R"] = onnx_gates(value) elif rest.startswith("lstm.bias"): out.setdefault(base + "lstm.B", {})[rest] = onnx_gates(value) else: out[base + "joint." + rest.replace("joint_net.1", "out")] = value for name, value in list(out.items()): if isinstance(value, dict): out[name] = np.concatenate((value["lstm.bias_ih_l0"], value["lstm.bias_hh_l0"])) return out def check(bin_path, checkpoint): actual = gigaam_bin.read(bin_path) wanted = expected(load_file(str(checkpoint))) worst, missing = 0.0, [] for name, value in wanted.items(): if name not in actual: missing.append(name) continue got = np.asarray(actual[name], dtype=np.float32) if got.shape != value.shape: raise SystemExit(f"{name}: shape {got.shape} != {value.shape}") scale = max(float(np.abs(value).max()), 1e-12) worst = max(worst, float(np.abs(got - value).max()) / scale) extra = [ name for name in actual if name not in wanted and not name.startswith(("config.", "mel.", "tokenizer.")) ] return worst, missing, extra, len(wanted) def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--bin", default=str(ROOT / "build" / "gigaam-v4-rnnt.gigaam")) parser.add_argument("--checkpoint", default=str(ROOT / "model" / "model.safetensors")) args = parser.parse_args(argv) worst, missing, extra, count = check(args.bin, args.checkpoint) print(f"compared {count} tensors, worst relative error {worst:.2e}") print(f"missing from bin: {missing}\nunexplained in bin: {extra}") if missing or extra or worst > 1e-5: raise SystemExit(1) print("OK") if __name__ == "__main__": main()