"""ONNX export of Dew as a one-word step model. Inputs : input_ids [B] int64, position [1] int64, then every state tensor from init_state() Outputs: logits [B, vocab], then the new state tensors (same order, names prefixed "new_") DeltaNet memories and convolution buffers have a fixed size; attention keys/values/keep grow by one word per step (dynamic axis "p"). Start from zero-length attention state (see initial_state_numpy) and feed each step's outputs back in. """ from __future__ import annotations from pathlib import Path import numpy as np import torch import torch.nn as nn class _Step(nn.Module): def __init__(self, lm): super().__init__() self.lm = lm def forward(self, input_ids, position, *state): logits, new = self.lm.step(input_ids, position, list(state)) return (logits, *new) def initial_state_numpy(lm, batch: int = 1): return [t.cpu().numpy() for t in lm.init_state(batch, device=torch.device("cpu"))] def export_onnx(lm, out_dir, name: str = "dew", int8: bool = True, opset: int = 17) -> dict: lm = lm.float().eval().cpu() out_dir = Path(out_dir) out_dir.mkdir(parents=True, exist_ok=True) kinds = lm.model.state_kinds() # trace with two words already in the attention memory, so its length is a real dynamic axis state = lm.init_state(1, device=torch.device("cpu")) with torch.no_grad(): for t, tok in enumerate((1, 2)): _, state = lm.step(torch.tensor([tok]), torch.tensor([t]), state) ids, pos = torch.tensor([3]), torch.tensor([2]) in_names = ["input_ids", "position"] + kinds out_names = ["logits"] + [f"new_{k}" for k in kinds] dyn = {"input_ids": {0: "batch"}, "logits": {0: "batch"}} for i, k in enumerate(kinds): ax = {0: "batch"} if k.endswith(("_keys", "_values")): ax[2] = f"p{i}" elif k.endswith("_keep"): ax[1] = f"p{i}" dyn[k] = ax dyn[f"new_{k}"] = {a: (v + "n" if v.startswith("p") else v) for a, v in ax.items()} f = out_dir / f"{name}.onnx" with torch.no_grad(): torch.onnx.export(_Step(lm), (ids, pos, *state), str(f), input_names=in_names, output_names=out_names, dynamic_axes=dyn, opset_version=opset, dynamo=False) res = {"onnx": str(f), "onnx_mb": f.stat().st_size / 1e6} if int8: from onnxruntime.quantization import QuantType, quantize_dynamic q = out_dir / f"{name}.int8.onnx" quantize_dynamic(str(f), str(q), weight_type=QuantType.QInt8) res.update(int8=str(q), int8_mb=q.stat().st_size / 1e6) return res def verify_onnx(lm, onnx_path, n_words: int = 24, seed: int = 0) -> float: """Feed the same words to ONNX (step by step) and to the PyTorch full-sequence forward. Returns the largest absolute logit difference.""" import onnxruntime as ort lm = lm.float().eval().cpu() g = torch.Generator().manual_seed(seed) ids = torch.randint(0, lm.config.vocab_size, (1, n_words), generator=g) with torch.no_grad(): ref = lm(ids).logits[0].numpy() sess = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"]) names = [i.name for i in sess.get_inputs()] state = initial_state_numpy(lm) worst = 0.0 for t in range(n_words): feeds = {"input_ids": ids[:, t].numpy(), "position": np.array([t], dtype=np.int64)} feeds.update({n: s for n, s in zip(names[2:], state)}) out = sess.run(None, feeds) worst = max(worst, float(np.abs(out[0][0] - ref[t]).max())) state = out[1:] return worst