shreyask commited on
Commit
f6077fc
Β·
verified Β·
1 Parent(s): fffa30b

Upload verify_parity.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. verify_parity.py +162 -0
verify_parity.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PyTorch port vs onnxruntime β€” assert logit drift < 1e-3 (Task 7 + 8 + 9 home)."""
2
+ from pathlib import Path
3
+ import numpy as np
4
+ import torch
5
+ import onnxruntime as ort
6
+
7
+ from needle_torch import NeedleModel, TransformerConfig
8
+
9
+ ART = Path(__file__).resolve().parent / "artifacts"
10
+
11
+ PROD_CONFIG = TransformerConfig(
12
+ vocab_size=8192, d_model=512, num_heads=8, num_kv_heads=4,
13
+ num_encoder_layers=12, num_decoder_layers=8,
14
+ max_seq_len=1024, no_feedforward=True,
15
+ )
16
+
17
+
18
+ def load_pt_model():
19
+ m = NeedleModel(PROD_CONFIG)
20
+ m.train(False)
21
+ state = torch.load(ART / "needle_torch.pt", map_location="cpu", weights_only=True)
22
+ m.load_state_dict(state, strict=True)
23
+ return m
24
+
25
+
26
+ def verify_encoder():
27
+ pt_model = load_pt_model()
28
+ sess = ort.InferenceSession(str(ART / "encoder.onnx"), providers=["CPUExecutionProvider"])
29
+
30
+ rng = np.random.default_rng(0)
31
+ ids_np = rng.integers(low=0, high=8000, size=(1, 24)).astype(np.int64)
32
+
33
+ with torch.no_grad():
34
+ pt_out = pt_model.encoder(torch.from_numpy(ids_np)).cpu().numpy()
35
+ ort_out = sess.run(None, {"input_ids": ids_np})[0]
36
+
37
+ diff = float(np.max(np.abs(pt_out - ort_out)))
38
+ mean = float(np.mean(np.abs(pt_out - ort_out)))
39
+ print(f"encoder parity: max-abs-diff={diff:.6f}, mean-abs-diff={mean:.6f}")
40
+ assert diff < 1e-3, f"encoder parity failed: {diff} >= 1e-3"
41
+ print("encoder parity OK")
42
+
43
+
44
+ def verify_decoder_step():
45
+ """Single decoder step at past_seq=4 β€” non-trivial past_kv to catch caching bugs."""
46
+ pt_model = load_pt_model()
47
+ dec_sess = ort.InferenceSession(str(ART / "decoder_step.onnx"), providers=["CPUExecutionProvider"])
48
+
49
+ rng = np.random.default_rng(1)
50
+ # Encoder output (just random β€” both runtimes see the same)
51
+ encoder_out = rng.standard_normal((1, 16, PROD_CONFIG.d_model)).astype(np.float32)
52
+ dec_id = np.array([[1]], dtype=np.int64) # EOS-prefix
53
+ head_dim = PROD_CONFIG.d_model // PROD_CONFIG.num_heads
54
+ past_kv = rng.standard_normal((
55
+ PROD_CONFIG.num_decoder_layers, 2, 1, PROD_CONFIG.num_kv_heads, 4, head_dim
56
+ )).astype(np.float32)
57
+
58
+ with torch.no_grad():
59
+ pt_logits, pt_present = pt_model.decoder.step(
60
+ torch.from_numpy(dec_id),
61
+ torch.from_numpy(encoder_out),
62
+ torch.from_numpy(past_kv),
63
+ )
64
+ pt_logits_np = pt_logits.cpu().numpy()
65
+ pt_present_np = pt_present.cpu().numpy()
66
+
67
+ ort_logits, ort_present = dec_sess.run(None, {
68
+ "decoder_input_ids": dec_id,
69
+ "encoder_out": encoder_out,
70
+ "past_self_kv": past_kv,
71
+ })
72
+
73
+ diff_logits = float(np.max(np.abs(pt_logits_np - ort_logits)))
74
+ diff_present = float(np.max(np.abs(pt_present_np - ort_present)))
75
+ print(f"decoder step parity: logits max-abs-diff={diff_logits:.6f}, present_kv max-abs-diff={diff_present:.6f}")
76
+ assert diff_logits < 1e-3, f"decoder logits drift: {diff_logits}"
77
+ assert diff_present < 1e-3, f"decoder kv drift: {diff_present}"
78
+ print("decoder step parity OK")
79
+
80
+
81
+ def verify_end_to_end(ckpt_repo="Cactus-Compute/needle", ckpt_file="needle.pkl"):
82
+ """Native Cactus generate() vs hand-rolled (encoder + decoder-step loop) via ONNX.
83
+
84
+ The two paths use different decode schemes (Cactus re-runs the full decoder
85
+ each step; ours uses a step-based KV-cache loop), but with greedy argmax + the
86
+ per-step parity established in Tasks 2D + 7 + 8, the produced token sequences
87
+ must match.
88
+ """
89
+ import sys
90
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "external" / "needle"))
91
+ from huggingface_hub import hf_hub_download
92
+
93
+ from needle.model.architecture import SimpleAttentionNetwork, TransformerConfig as FlaxConfig
94
+ from needle.model.run import generate as cactus_generate, _build_encoder_input, load_checkpoint
95
+ from needle.dataset.tokenizer import get_tokenizer
96
+
97
+ # ── Native Cactus generate (constrained=False, deterministic argmax) ──
98
+ ckpt_path = hf_hub_download(repo_id=ckpt_repo, filename=ckpt_file)
99
+ flax_params, flax_cfg = load_checkpoint(ckpt_path)
100
+ flax_model = SimpleAttentionNetwork(flax_cfg)
101
+ tokenizer = get_tokenizer()
102
+
103
+ query = "set a 5 min timer"
104
+ tools = '[{"name": "set_timer", "description": "Set a timer.", "parameters": {"time_human": {"type": "string", "description": "duration"}}}]'
105
+
106
+ native_text = cactus_generate(
107
+ flax_model, flax_params, tokenizer, query, tools=tools,
108
+ max_gen_len=64, stream=False, normalize=False, constrained=False,
109
+ )
110
+ print(f"native generate output text: {native_text!r}")
111
+
112
+ # ── Hand-rolled ONNX KV-cache loop ──
113
+ enc_sess = ort.InferenceSession(str(ART / "encoder.onnx"), providers=["CPUExecutionProvider"])
114
+ dec_sess = ort.InferenceSession(str(ART / "decoder_step.onnx"), providers=["CPUExecutionProvider"])
115
+
116
+ enc_tokens = _build_encoder_input(tokenizer, query, tools, max_enc_len=1024)
117
+ enc_input = np.array([enc_tokens], dtype=np.int64)
118
+ encoder_out = enc_sess.run(None, {"input_ids": enc_input})[0]
119
+
120
+ head_dim = PROD_CONFIG.d_model // PROD_CONFIG.num_heads
121
+ past_kv = np.zeros((
122
+ PROD_CONFIG.num_decoder_layers, 2, 1, PROD_CONFIG.num_kv_heads, 0, head_dim
123
+ ), dtype=np.float32)
124
+
125
+ eos_id = tokenizer.eos_token_id
126
+ next_id = eos_id # decoder seeded with EOS per Cactus convention
127
+ ort_generated = []
128
+ for _ in range(64):
129
+ logits, past_kv = dec_sess.run(None, {
130
+ "decoder_input_ids": np.array([[next_id]], dtype=np.int64),
131
+ "encoder_out": encoder_out,
132
+ "past_self_kv": past_kv,
133
+ })
134
+ next_id = int(np.argmax(logits[0, 0]))
135
+ if next_id == eos_id:
136
+ break
137
+ ort_generated.append(next_id)
138
+
139
+ ort_text = tokenizer.decode(ort_generated)
140
+ if ort_text.startswith("<tool_call>"):
141
+ ort_text = ort_text[len("<tool_call>"):]
142
+ print(f"ort generate output text: {ort_text!r}")
143
+
144
+ assert native_text == ort_text, (
145
+ f"end-to-end output text differs!\n"
146
+ f" native: {native_text!r}\n"
147
+ f" ort: {ort_text!r}"
148
+ )
149
+ print("end-to-end parity OK β€” Cactus native == ONNX hand-rolled loop")
150
+
151
+
152
+ if __name__ == "__main__":
153
+ verify_encoder()
154
+ verify_decoder_step()
155
+ import argparse
156
+ p = argparse.ArgumentParser()
157
+ p.add_argument("--ckpt-repo", default="Cactus-Compute/needle",
158
+ help="HF repo for the upstream Flax checkpoint (default: Cactus-Compute/needle)")
159
+ p.add_argument("--ckpt-file", default="needle.pkl",
160
+ help="Filename within the repo (default: needle.pkl)")
161
+ args, _ = p.parse_known_args()
162
+ verify_end_to_end(args.ckpt_repo, args.ckpt_file)