zziang commited on
Commit
a11bd05
·
verified ·
1 Parent(s): db88d9c

fix lm cache order and additive mask; probe audio VAE

Browse files
Files changed (1) hide show
  1. kaggle/export_browser.py +50 -10
kaggle/export_browser.py CHANGED
@@ -80,30 +80,33 @@ def stage_lm(mm, torch) -> dict:
80
  self.lm = lm
81
 
82
  def forward(self, inputs_embeds, attention_mask, position_ids, *past):
 
83
  k, v = past[:n], past[n:]
84
  cache = tuple((k[i], v[i]) for i in range(n))
85
  out = self.lm(inputs_embeds=inputs_embeds, attention_mask=attention_mask,
86
  position_ids=position_ids, past_key_values=cache,
87
  use_cache=True, output_hidden_states=True, return_dict=True)
88
  new = out.past_key_values
89
- flat = []
90
- for i in range(n):
91
- flat.append(new[i][0])
92
- flat.append(new[i][1])
93
- return (out.hidden_states[-1], *flat)
94
 
95
  wrapper = Wrapper().float().eval()
96
  dev = next(lm.parameters()).device
97
  B, S, P = 1, 4, 6
98
  H = cfg.hidden_size
99
  embeds = torch.randn(B, S, H, device=dev)
100
- mask = torch.zeros(B, 1, S, P + S, device=dev)
 
 
 
101
  for i in range(S):
102
- mask[:, :, i, :P + i + 1] = 1.0
103
  pos = torch.arange(P, P + S, device=dev).unsqueeze(0)
104
  past = []
105
  for _ in range(n):
106
  past.append(torch.randn(B, kv_heads, P, head_dim, device=dev))
 
107
  past.append(torch.randn(B, kv_heads, P, head_dim, device=dev))
108
 
109
  with torch.no_grad():
@@ -132,8 +135,8 @@ def stage_lm(mm, torch) -> dict:
132
  feeds = {"inputs_embeds": np_(embeds), "attention_mask": np_(mask),
133
  "position_ids": np_(pos)}
134
  for i in range(n):
135
- feeds[f"past_k_{i}"] = np_(past[2 * i])
136
- feeds[f"past_v_{i}"] = np_(past[2 * i + 1])
137
  got = sess.run(None, feeds)
138
  cos = [cosine(np_(ref[i]), got[i]) for i in range(3)]
139
  log(f"validate hidden cos={cos[0]:.6f} k0={cos[1]:.6f} v0={cos[2]:.6f}")
@@ -223,6 +226,39 @@ def quantize(paths: list[Path], bits: int = 4) -> list[dict]:
223
  return rows
224
 
225
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
  def main() -> None:
227
  import torch
228
 
@@ -234,7 +270,8 @@ def main() -> None:
234
  mm = tts.model
235
  results = []
236
 
237
- for name, fn in (("lm", stage_lm), ("agg", stage_agg), ("voc", stage_voc)):
 
238
  if STAGE not in (name, "all"):
239
  continue
240
  try:
@@ -243,6 +280,9 @@ def main() -> None:
243
  log(f"stage {name} FAILED\n{traceback.format_exc()}")
244
 
245
  q = quantize([OUT / "lm.onnx", OUT / "aggregator.onnx", OUT / "voc.onnx"])
 
 
 
246
  (OUT / "report.json").write_text(json.dumps({"graphs": results, "quant": q},
247
  ensure_ascii=False, indent=1))
248
  log("done")
 
80
  self.lm = lm
81
 
82
  def forward(self, inputs_embeds, attention_mask, position_ids, *past):
83
+ # past arrives as [k0..k(n-1), v0..v(n-1)]; keep that order on the way out too.
84
  k, v = past[:n], past[n:]
85
  cache = tuple((k[i], v[i]) for i in range(n))
86
  out = self.lm(inputs_embeds=inputs_embeds, attention_mask=attention_mask,
87
  position_ids=position_ids, past_key_values=cache,
88
  use_cache=True, output_hidden_states=True, return_dict=True)
89
  new = out.past_key_values
90
+ ks = [new[i][0] for i in range(n)]
91
+ vs = [new[i][1] for i in range(n)]
92
+ return (out.hidden_states[-1], *ks, *vs)
 
 
93
 
94
  wrapper = Wrapper().float().eval()
95
  dev = next(lm.parameters()).device
96
  B, S, P = 1, 4, 6
97
  H = cfg.hidden_size
98
  embeds = torch.randn(B, S, H, device=dev)
99
+ # Qwen2 adds this mask to the attention scores, so blocked positions need a
100
+ # large negative value; 0/1 would let the model attend to the future.
101
+ neg = torch.finfo(torch.float32).min / 2
102
+ mask = torch.full((B, 1, S, P + S), neg, device=dev)
103
  for i in range(S):
104
+ mask[:, :, i, :P + i + 1] = 0.0
105
  pos = torch.arange(P, P + S, device=dev).unsqueeze(0)
106
  past = []
107
  for _ in range(n):
108
  past.append(torch.randn(B, kv_heads, P, head_dim, device=dev))
109
+ for _ in range(n):
110
  past.append(torch.randn(B, kv_heads, P, head_dim, device=dev))
111
 
112
  with torch.no_grad():
 
135
  feeds = {"inputs_embeds": np_(embeds), "attention_mask": np_(mask),
136
  "position_ids": np_(pos)}
137
  for i in range(n):
138
+ feeds[f"past_k_{i}"] = np_(past[i])
139
+ feeds[f"past_v_{i}"] = np_(past[n + i])
140
  got = sess.run(None, feeds)
141
  cos = [cosine(np_(ref[i]), got[i]) for i in range(3)]
142
  log(f"validate hidden cos={cos[0]:.6f} k0={cos[1]:.6f} v0={cos[2]:.6f}")
 
226
  return rows
227
 
228
 
229
+ def stage_probe_audio(mm) -> dict:
230
+ """Dump the audio VAE surface so the vocoder export can stop before ISTFT.
231
+
232
+ `decode` builds a complex STFT internally, which the ONNX exporter refuses
233
+ ("Unknown number type: complex"). The fix is to return the spectrum and do
234
+ the inverse transform on the host, but that needs the real method names.
235
+ """
236
+ import inspect
237
+
238
+ audio = mm.audio
239
+ text = []
240
+ text.append("class: " + type(audio).__name__)
241
+ text.append("\nattrs: " + ", ".join(a for a in dir(audio) if not a.startswith("__")))
242
+ for name in dir(audio):
243
+ if name.startswith("__"):
244
+ continue
245
+ fn = getattr(audio, name)
246
+ if not callable(fn):
247
+ continue
248
+ try:
249
+ src = inspect.getsource(fn)
250
+ except Exception:
251
+ continue
252
+ if any(k in src for k in ("istft", "stft", "complex", "spectrogram", "def decode", "def encode")):
253
+ text.append(f"\n\n===== {name} =====\n{src}")
254
+ out = OUT / "audio_src.txt"
255
+ out.write_text("\n".join(text))
256
+ log(f"wrote {out} ({len(text)} blocks)")
257
+ for line in text[:80]:
258
+ log(line)
259
+ return {"graph": "probe_audio", "chars": sum(len(t) for t in text)}
260
+
261
+
262
  def main() -> None:
263
  import torch
264
 
 
270
  mm = tts.model
271
  results = []
272
 
273
+ for name, fn in (("lm", stage_lm), ("agg", stage_agg), ("probe", lambda m, t: stage_probe_audio(m)),
274
+ ("voc", stage_voc)):
275
  if STAGE not in (name, "all"):
276
  continue
277
  try:
 
280
  log(f"stage {name} FAILED\n{traceback.format_exc()}")
281
 
282
  q = quantize([OUT / "lm.onnx", OUT / "aggregator.onnx", OUT / "voc.onnx"])
283
+ (OUT / "sizes.json").write_text(json.dumps(
284
+ {p_.name: round(p_.stat().st_size / 1e6, 1) for p_ in sorted(OUT.glob("*.onnx"))},
285
+ indent=1))
286
  (OUT / "report.json").write_text(json.dumps({"graphs": results, "quant": q},
287
  ensure_ascii=False, indent=1))
288
  log("done")