Nekochu commited on
Commit
752dc7d
·
verified ·
1 Parent(s): 3067529

Manifest v2: 8-bit default, 4-bit option, tiled decoder; card-size measurements in README

Browse files
README.md CHANGED
@@ -31,48 +31,61 @@ merged in, converted to ONNX so it runs in a web browser on the visitor's own GP
31
  | part | runs on | weights | what it does |
32
  |---|---|---|---|
33
  | `text/` | WASM (CPU) | 8-bit | T5Gemma 2 encoder layers 1 to 12, the three tap projections, the learned suffix tokens and the 2 text-refiner blocks |
34
- | `dit_a/` | WebGPU | 4-bit, AdaLN 8-bit | latent embed, time embed, 6 prefix blocks |
35
- | `dit_b/`, `dit_c/` | WebGPU | 4-bit, AdaLN 8-bit | the 18 middle blocks, 9 each |
36
- | `dit_d/` | WebGPU | 4-bit, AdaLN 8-bit | tail join, 6 suffix blocks, velocity head |
37
- | `vae_dec/` | WebGPU | 8-bit | [dinac3_96](https://huggingface.co/data-archetype/dinac3_96) decoder, de-whitening, output in [0, 1] |
38
  | `embed_bf16.bin` | | bf16, raw | token embeddings `[262144, 640]`, read row by row with HTTP Range (a prompt needs a few KB of it) |
39
  | `tokenizer.json` | | | the T5Gemma 2 tokenizer |
40
- | `manifest.json` | | | part sizes for download progress |
41
 
42
- About 1.7 GB to download in total; the page stores it in the browser after the first visit.
 
43
 
44
  Weights are `MatMulNBits` (block 32, asymmetric) with fp32 activations, so they run on any WebGPU device,
45
- including ones without `shader-f16`. The text graph stays on WASM because Gemma's hidden states have
46
- channels far outside fp16 range.
 
 
 
 
 
 
 
 
 
47
 
48
  All RoPE tables are graph inputs computed by the page, so every graph takes any image size (multiple
49
- of 16) and any prompt length up to 256 tokens with no fixed shape baked in.
50
 
51
  ## Sampling
52
 
53
  4 Euler steps, CFG and path-drop guidance off, the `beta_1_25` schedule with the training resolution
54
  shift `s = min(0, -0.25 - ln(W·H / 256²))`, self-attention gain -0.03 up to about 1 MP (closer to 0
55
- above), as the LoRA was trained. The JS port of the schedule reproduces the LoRA's own recorded grids
56
- (`[1.0, 0.920527, 0.816588, 0.631176, 0.0]` at 832×1216) exactly.
 
 
 
57
 
58
  ## How it was checked
59
 
60
- Against a float32 PyTorch reference of the release code on CPU, same noise:
 
 
 
61
 
62
- | stage | fp32 ONNX | this repo (4-bit) |
63
- |---|---|---|
64
- | refined text tokens, cosine | 1.000000 | 0.99997 |
65
- | velocity at step 1, cosine | 1.000000 | 0.99914 |
66
- | worst step, reference input fed at each step | 1.000000 | 0.9937 |
67
- | final image PSNR vs fp32, 512×512 | 125 dB | 27 dB (same scene and layout) |
68
 
69
- The browser pipeline (JS tokenizer, RoPE, schedule, Euler loop, ORT Web WebGPU) was then run in
70
- Chromium and matched ONNX Runtime on CPU to a cosine of 0.99999999 on the final image. The JS tokenizer
71
- reproduces dflow's prompt rules (`<bos>` frame, quoted text split into single characters) and matched
72
- the Python token ids on every test prompt.
73
 
74
- 8-bit everywhere scores 0.99995 on the worst step but is 2.2 GB for the denoiser; 4-bit is 1.27 GB.
75
- `scripts/` holds the export, quantization and verification code.
76
 
77
  ## Licences
78
 
 
31
  | part | runs on | weights | what it does |
32
  |---|---|---|---|
33
  | `text/` | WASM (CPU) | 8-bit | T5Gemma 2 encoder layers 1 to 12, the three tap projections, the learned suffix tokens and the 2 text-refiner blocks |
34
+ | `q8/dit_a/` … `q8/dit_d/` | WebGPU | **8-bit (default)** | the 2B denoiser in four parts: embed + 6 prefix blocks, 9 + 9 middle blocks, tail join + 6 suffix blocks + velocity head |
35
+ | `q4/dit_a/` … `q4/dit_d/` | WebGPU | 4-bit, AdaLN 8-bit | the same, smaller and visibly softer, for devices short on memory |
36
+ | `vae_trunk/` | WebGPU | 8-bit | [dinac3_96](https://huggingface.co/data-archetype/dinac3_96) decoder: de-whitening and the 4-block transformer trunk (global) |
37
+ | `vae_head/` | WebGPU | fp32 | the decoder's convolutional up-path (local), run tile by tile, output in [0, 1] |
38
  | `embed_bf16.bin` | | bf16, raw | token embeddings `[262144, 640]`, read row by row with HTTP Range (a prompt needs a few KB of it) |
39
  | `tokenizer.json` | | | the T5Gemma 2 tokenizer |
40
+ | `manifest.json` | | | part sizes and the total per variant, for download progress |
41
 
42
+ Download: about **2.7 GB** with the 8-bit denoiser, 1.7 GB with the 4-bit one. The page stores it in the
43
+ browser after the first visit.
44
 
45
  Weights are `MatMulNBits` (block 32, asymmetric) with fp32 activations, so they run on any WebGPU device,
46
+ including ones without `shader-f16`; both bit widths run natively on the WebGPU backend. The text graph
47
+ stays on WASM because Gemma's hidden states have channels far outside fp16 range.
48
+
49
+ Two things keep GPU memory bounded so the trained ~1 MP sizes fit on more devices:
50
+
51
+ - **Attention runs one head at a time** inside the graphs (same math as SDPA). The largest score
52
+ tensor is `[1, 1, S, S]` instead of `[1, 18, S, S]`: 214 MB instead of 3.9 GB at 1824×1024.
53
+ - **The decoder is split** into its global trunk and its local up-path. The up-path runs in tiles that
54
+ overlap by 8 latent cells, wider than its receptive field (about 6.6 cells), so the tiled result is
55
+ identical to one pass (measured maximum difference 0.0). The page sizes the tiles from the GPU's
56
+ largest allowed buffer.
57
 
58
  All RoPE tables are graph inputs computed by the page, so every graph takes any image size (multiple
59
+ of 16) and any prompt length up to 256 tokens.
60
 
61
  ## Sampling
62
 
63
  4 Euler steps, CFG and path-drop guidance off, the `beta_1_25` schedule with the training resolution
64
  shift `s = min(0, -0.25 - ln(W·H / 256²))`, self-attention gain -0.03 up to about 1 MP (closer to 0
65
+ above), as the LoRA was trained. The JS schedule reproduces the LoRA's recorded grids exactly
66
+ (`[1.0, 0.920527, 0.816588, 0.631176, 0.0]` at 832×1216, `[1.0, 0.940256, 0.858143, 0.699269, 0.0]` at 1824×1024).
67
+
68
+ The model and the LoRA were trained at about 1 MP and above. Detail scales with the token count
69
+ (one token per 16×16 pixels), so 512×512 is a quick preview, not a fair look at the model.
70
 
71
  ## How it was checked
72
 
73
+ 1. **The recipe reproduces the LoRA card.** A float32 PyTorch run of the release code on CPU, with the
74
+ card's prompt, seed 4242 and size 1824×1024, gives the card's snow leopard: same pose, spots and
75
+ snowflakes, 32.0 dB from the card image (the card was rendered in bf16 on a GPU and saved as JPEG).
76
+ 2. **The ONNX graphs against that run, same noise, 1824×1024:**
77
 
78
+ | | velocity cosine, steps 1 to 4 | final image vs fp32 |
79
+ |---|---|---|
80
+ | fp32 ONNX | 1.000000 at every step | 125 dB (512×512) |
81
+ | **8-bit denoiser** | 0.99999, 0.99996, 0.99980, 0.99886 | **37.4 dB**, indistinguishable |
82
+ | 4-bit denoiser | 0.99906, 0.99522, 0.98175, 0.96403 | 23.1 dB, face drifts, colour and fur contrast fade |
 
83
 
84
+ 3. **The browser matches ONNX Runtime on CPU.** The JS tokenizer, RoPE, schedule, Euler loop and tiled
85
+ decoder, run in Chromium on WebGPU, matched ONNX Runtime on CPU to a cosine of 0.99999999 on the final
86
+ image, and the JS tokenizer matched dflow's Python token ids on every test prompt (quoted text included).
 
87
 
88
+ `scripts/` holds the export, quantization, verification and comparison code.
 
89
 
90
  ## Licences
91
 
dit_a/dit_a.onnx DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:d073d4d0443cf105d50a2803dc4b59f4a6c7bf28f68e5b54fbae4c8c0fd7ecb6
3
- size 259121
 
 
 
 
dit_a/dit_a.onnx.data DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:20b13bbc09291a1ab0ed501d2fa522977d8341ad9ae61adb42190d0c826d5bb1
3
- size 263442432
 
 
 
 
dit_b/dit_b.onnx DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:dee01a511a604fea5f9a626161979ee2510a4f52ac895b33ae8cf36de23dd36f
3
- size 358898
 
 
 
 
dit_b/dit_b.onnx.data DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:6430288eaef19c9268401cb329bfc0e703cc37cb2553fd2dd8084c5d3403e217
3
- size 392905728
 
 
 
 
dit_c/dit_c.onnx DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:5b6de768fb0a5df8e127a49fcac599a37d63d0edcd8ed2ff4c13e274e9ae90d3
3
- size 358898
 
 
 
 
dit_c/dit_c.onnx.data DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:99e2d9ae68f4f04b6d8ee290acd58145e2b48e30034fa437cc28e7f513448f87
3
- size 392905728
 
 
 
 
dit_d/dit_d.onnx DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:1c9cf9d4b6216267dc9e6640a095b74c7a9714928911db96a7cad77237f5a0ed
3
- size 265008
 
 
 
 
dit_d/dit_d.onnx.data DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:cd638f989df2c3963c486394eb18ebc1a994bc4160c5b2e74bd0987765df670c
3
- size 277137792
 
 
 
 
manifest.json CHANGED
@@ -1,14 +1,22 @@
1
  {
2
- "format": "dflow2-web-v1",
3
  "parts": {
4
  "text": 230535705,
5
- "dit_a": 263701553,
6
- "dit_b": 393264626,
7
- "dit_c": 393264626,
8
- "dit_d": 277402800,
9
- "vae_dec": 142138666
 
 
 
 
 
 
 
 
 
10
  },
11
- "total": 1733692364,
12
  "embeddings": {
13
  "file": "embed_bf16.bin",
14
  "dtype": "bfloat16",
 
1
  {
2
+ "format": "dflow2-web-v2",
3
  "parts": {
4
  "text": 230535705,
5
+ "vae_trunk": 74601504,
6
+ "vae_head": 67717638,
7
+ "q4/dit_a": 264047306,
8
+ "q4/dit_b": 393798101,
9
+ "q4/dit_c": 393798101,
10
+ "q4/dit_d": 277748558,
11
+ "q8/dit_a": 461122273,
12
+ "q8/dit_b": 689410544,
13
+ "q8/dit_c": 689410544,
14
+ "q8/dit_d": 474937573
15
+ },
16
+ "total": {
17
+ "q4": 1735631301,
18
+ "q8": 2721120169
19
  },
 
20
  "embeddings": {
21
  "file": "embed_bf16.bin",
22
  "dtype": "bfloat16",
scripts/decode.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Decode saved latents with the PyTorch dinac3 decoder (fp32): decode.py LATENT.npy OUT.png"""
2
+ import sys
3
+ import numpy as np, torch
4
+ from PIL import Image
5
+ import dfl
6
+ torch.set_num_threads(4)
7
+ vae = dfl.load_vae()
8
+ x = torch.from_numpy(np.load(sys.argv[1])).float()
9
+ with torch.no_grad():
10
+ rgb = vae.decode(x, x.shape[2] * 16, x.shape[3] * 16).clamp(-1, 1)
11
+ Image.fromarray(((rgb[0].permute(1, 2, 0).numpy() + 1) * 127.5).round().clip(0, 255).astype(np.uint8)).save(sys.argv[2])
12
+ print("saved", sys.argv[2])
scripts/export.py CHANGED
@@ -4,6 +4,7 @@ usage: export.py {text,dit_a,dit_b,dit_c,dit_d,vae}
4
  """
5
  from __future__ import annotations
6
 
 
7
  import sys
8
  import time
9
  from pathlib import Path
@@ -27,7 +28,25 @@ def _rms_norm(x, normalized_shape, weight=None, eps=None):
27
  F.rms_norm = _rms_norm
28
  torch.rms_norm = _rms_norm
29
 
30
- OUT = dfl.SP / "onnx_fp32"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  OUT.mkdir(exist_ok=True)
32
  torch.set_num_threads(4)
33
 
@@ -139,6 +158,37 @@ class VaePart(nn.Module):
139
  return ((rgb.clamp(-1.0, 1.0) + 1.0) * 0.5)
140
 
141
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  def export(module, args, names, outs, dyn, path: Path):
143
  t0 = time.time()
144
  path = path.parent / path.stem / path.name
@@ -165,6 +215,15 @@ def main(part: str) -> None:
165
  "g_sin_f": {0: "l"}, "r_sin": {1: "l3"}, "r_cos": {1: "l3"}, "text": {1: "l3"}}
166
  export(TextPart(enc, adapter, model).eval(), args, names, ["text"], dyn, OUT / "text.onnx")
167
  return
 
 
 
 
 
 
 
 
 
168
  if part == "vae":
169
  vae = dfl.load_vae()
170
  args = (torch.randn(1, 96, 3, 4), torch.randn(12, 64), torch.randn(12, 64))
 
4
  """
5
  from __future__ import annotations
6
 
7
+ import math
8
  import sys
9
  import time
10
  from pathlib import Path
 
28
  F.rms_norm = _rms_norm
29
  torch.rms_norm = _rms_norm
30
 
31
+
32
+ def _sdpa_by_head(q, k, v, attn_mask=None, dropout_p=0.0, is_causal=False, scale=None, enable_gqa=False):
33
+ """Attention one head at a time: same math as SDPA, but the largest live score
34
+ tensor is [B, 1, S, S] instead of [B, H, S, S] (18x less memory at 1 MP)."""
35
+ assert dropout_p == 0.0 and not is_causal and not enable_gqa
36
+ heads, dim = int(q.shape[1]), int(q.shape[-1])
37
+ sc = scale if scale is not None else 1.0 / math.sqrt(dim)
38
+ outs = []
39
+ for h in range(heads):
40
+ s = torch.matmul(q[:, h:h + 1], k[:, h:h + 1].transpose(-1, -2)) * sc
41
+ if attn_mask is not None:
42
+ s = s + (attn_mask if attn_mask.shape[1] == 1 else attn_mask[:, h:h + 1])
43
+ outs.append(torch.matmul(torch.softmax(s, dim=-1), v[:, h:h + 1]))
44
+ return torch.cat(outs, dim=1)
45
+
46
+
47
+ F.scaled_dot_product_attention = _sdpa_by_head
48
+
49
+ OUT = dfl.SP / "onnx_fp32h"
50
  OUT.mkdir(exist_ok=True)
51
  torch.set_num_threads(4)
52
 
 
158
  return ((rgb.clamp(-1.0, 1.0) + 1.0) * 0.5)
159
 
160
 
161
+ class VaeTrunk(nn.Module):
162
+ """Whitened latents [1, 96, h, w] -> trunk features [1, 1152, h, w] (global attention)."""
163
+
164
+ def __init__(self, vae):
165
+ super().__init__()
166
+ self.dec = vae.decoder
167
+ mean, std = vae._latent_stats()
168
+ self.register_buffer("mean", mean.clone())
169
+ self.register_buffer("std", std.clone())
170
+
171
+ def forward(self, z, v_sin, v_cos):
172
+ x = self.dec.latent_up(z * self.std + self.mean)
173
+ b, c, h, w = x.shape
174
+ tokens = x.permute(0, 2, 3, 1).reshape(b, h * w, c)
175
+ for block in self.dec.trunk:
176
+ tokens = block(tokens, v_sin, v_cos)
177
+ return tokens.transpose(1, 2).reshape(b, c, h, w)
178
+
179
+
180
+ class VaeHead(nn.Module):
181
+ """Trunk features (any tile) [1, 1152, th, tw] -> RGB [1, 3, 16th, 16tw] in [0, 1].
182
+ Purely local (convolutions and per-pixel norms), so it can run tile by tile."""
183
+
184
+ def __init__(self, vae):
185
+ super().__init__()
186
+ self.head = vae.decoder.conv_up_head
187
+
188
+ def forward(self, feats):
189
+ return (self.head(feats).clamp(-1.0, 1.0) + 1.0) * 0.5
190
+
191
+
192
  def export(module, args, names, outs, dyn, path: Path):
193
  t0 = time.time()
194
  path = path.parent / path.stem / path.name
 
215
  "g_sin_f": {0: "l"}, "r_sin": {1: "l3"}, "r_cos": {1: "l3"}, "text": {1: "l3"}}
216
  export(TextPart(enc, adapter, model).eval(), args, names, ["text"], dyn, OUT / "text.onnx")
217
  return
218
+ if part == "vae_split":
219
+ vae = dfl.load_vae()
220
+ export(VaeTrunk(vae).eval(), (torch.randn(1, 96, 3, 4), torch.randn(12, 64), torch.randn(12, 64)),
221
+ ["z", "v_sin", "v_cos"], ["feats"],
222
+ {"z": {2: "h", 3: "w"}, "v_sin": {0: "hw"}, "v_cos": {0: "hw"}, "feats": {2: "h", 3: "w"}},
223
+ OUT / "vae_trunk.onnx")
224
+ export(VaeHead(vae).eval(), (torch.randn(1, 1152, 3, 4),), ["feats"], ["rgb"],
225
+ {"feats": {2: "h", 3: "w"}, "rgb": {2: "H", 3: "W"}}, OUT / "vae_head.onnx")
226
+ return
227
  if part == "vae":
228
  vae = dfl.load_vae()
229
  args = (torch.randn(1, 96, 3, 4), torch.randn(12, 64), torch.randn(12, 64))
scripts/panel.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Side-by-side comparison panel: full views on top, 1:1 crops of one region below.
2
+
3
+ usage: panel.py OUT.png "x,y,w,h" LABEL=IMG [LABEL=IMG ...]
4
+ The crop box is in the coordinates of the first image; others are scaled to its size
5
+ for the full view and cropped at the same relative position for the 1:1 row.
6
+ """
7
+ import sys
8
+
9
+ from PIL import Image, ImageDraw, ImageFont
10
+
11
+ out, box = sys.argv[1], [int(v) for v in sys.argv[2].split(",")]
12
+ items = [a.split("=", 1) for a in sys.argv[3:]]
13
+ ims = [(label, Image.open(path).convert("RGB")) for label, path in items]
14
+ W0, H0 = ims[0][1].size
15
+ thumb_w = 600
16
+ font = ImageFont.load_default()
17
+ x, y, w, h = box
18
+ rows = []
19
+ for label, im in ims:
20
+ sx, sy = im.size[0] / W0, im.size[1] / H0
21
+ crop = im.crop((int(x * sx), int(y * sy), int((x + w) * sx), int((y + h) * sy)))
22
+ crop = crop.resize((w, h), Image.LANCZOS) if crop.size != (w, h) else crop
23
+ full = im.resize((thumb_w, int(thumb_w * H0 / W0)), Image.LANCZOS)
24
+ d = ImageDraw.Draw(full)
25
+ d.rectangle([x / W0 * thumb_w, y / H0 * full.size[1], (x + w) / W0 * thumb_w, (y + h) / H0 * full.size[1]],
26
+ outline=(255, 60, 0), width=2)
27
+ rows.append((label + f" ({im.size[0]}x{im.size[1]})", full, crop))
28
+ col_w = max(thumb_w, w)
29
+ H = max(r[1].size[1] for r in rows) + h + 40
30
+ panel = Image.new("RGB", (col_w * len(rows) + 8 * (len(rows) - 1), H), (20, 20, 20))
31
+ for i, (label, full, crop) in enumerate(rows):
32
+ ox = i * (col_w + 8)
33
+ ImageDraw.Draw(panel).text((ox + 4, 4), label, fill=(240, 240, 240), font=font)
34
+ panel.paste(full, (ox, 20))
35
+ panel.paste(crop, (ox, 20 + full.size[1] + 16))
36
+ panel.save(out)
37
+ print("saved", out, panel.size)
scripts/qall.sh CHANGED
@@ -4,5 +4,5 @@ OUT=$1; shift
4
  run(){ ../venv/bin/python quant.py "$@" 2>&1 | grep -vE "Warning|^\s*$|INFO" | tail -1; }
5
  run dit_a $OUT "$@" & run dit_d $OUT "$@" & wait
6
  run dit_b $OUT "$@" & run dit_c $OUT "$@" & wait
7
- for p in text vae_dec; do [ -e $OUT/$p ] || ln -s $(realpath ../onnx_q4b32/$p) $OUT/$p; done
8
  du -sh $OUT/dit_* | awk '{s=s" "$2":"$1} END{print s}'
 
4
  run(){ ../venv/bin/python quant.py "$@" 2>&1 | grep -vE "Warning|^\s*$|INFO" | tail -1; }
5
  run dit_a $OUT "$@" & run dit_d $OUT "$@" & wait
6
  run dit_b $OUT "$@" & run dit_c $OUT "$@" & wait
7
+ for p in text vae_dec; do [ -e $OUT/$p ] || true; done
8
  du -sh $OUT/dit_* | awk '{s=s" "$2":"$1} END{print s}'
scripts/quant.py CHANGED
@@ -32,9 +32,10 @@ ap.add_argument("--sym", action="store_true")
32
  ap.add_argument("--hi", default=r"Gemm_mm")
33
  ap.add_argument("--hi-bits", type=int, default=8)
34
  ap.add_argument("--hi-block", type=int, default=32)
 
35
  a = ap.parse_args()
36
 
37
- src = SP / "onnx_fp32" / a.part / f"{a.part}.onnx"
38
  dst = a.out_dir / a.part / f"{a.part}.onnx"
39
  dst.parent.mkdir(parents=True, exist_ok=True)
40
  t0 = time.time()
 
32
  ap.add_argument("--hi", default=r"Gemm_mm")
33
  ap.add_argument("--hi-bits", type=int, default=8)
34
  ap.add_argument("--hi-block", type=int, default=32)
35
+ ap.add_argument("--src", default="onnx_fp32h")
36
  a = ap.parse_args()
37
 
38
+ src = SP / a.src / a.part / f"{a.part}.onnx"
39
  dst = a.out_dir / a.part / f"{a.part}.onnx"
40
  dst.parent.mkdir(parents=True, exist_ok=True)
41
  t0 = time.time()
scripts/ref.py CHANGED
@@ -47,12 +47,15 @@ with torch.no_grad():
47
  x = x + float(ts[i + 1] - ts[i]) * v
48
  print(f"step {i} t={float(ts[i]):.4f} {time.time()-t1:.1f}s |v|={v.std():.3f}", flush=True)
49
  t1 = time.time()
 
 
 
50
  rgb = vae.decode(x, a.height, a.width).clamp(-1, 1)
51
  print(f"decode {time.time()-t1:.1f}s", flush=True)
52
 
53
  img = ((rgb[0].permute(1, 2, 0).numpy() + 1) * 127.5).round().clip(0, 255).astype(np.uint8)
54
  Image.fromarray(img).save(f"{out}.png")
55
  np.savez(f"{out}.npz", ids=np.array(ids, np.int64), cond=cond.numpy(),
56
- refined=prepared.tokens.numpy(), noise=noise.numpy(), times=ts.numpy(),
57
  gain=np.float32(gain), vels=np.stack(vels), latent=x.numpy(), rgb=rgb.numpy())
58
  print("saved", out, f"total {time.time()-t0:.0f}s")
 
47
  x = x + float(ts[i + 1] - ts[i]) * v
48
  print(f"step {i} t={float(ts[i]):.4f} {time.time()-t1:.1f}s |v|={v.std():.3f}", flush=True)
49
  t1 = time.time()
50
+ refined = prepared.tokens.numpy().copy()
51
+ del model, prepared
52
+ import gc; gc.collect()
53
  rgb = vae.decode(x, a.height, a.width).clamp(-1, 1)
54
  print(f"decode {time.time()-t1:.1f}s", flush=True)
55
 
56
  img = ((rgb[0].permute(1, 2, 0).numpy() + 1) * 127.5).round().clip(0, 255).astype(np.uint8)
57
  Image.fromarray(img).save(f"{out}.png")
58
  np.savez(f"{out}.npz", ids=np.array(ids, np.int64), cond=cond.numpy(),
59
+ refined=refined, noise=noise.numpy(), times=ts.numpy(),
60
  gain=np.float32(gain), vels=np.stack(vels), latent=x.numpy(), rgb=rgb.numpy())
61
  print("saved", out, f"total {time.time()-t0:.0f}s")
scripts/tile_test.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys, numpy as np, onnxruntime as ort, ropes
2
+ R = "/tmp/claude-0/-home-user-HF-empty/1caca391-99c3-5a94-acbe-98cceb297ce3/scratchpad/onnx_A2"
3
+ so = ort.SessionOptions(); so.intra_op_num_threads = 2
4
+ trunk = ort.InferenceSession(f"{R}/vae_trunk/vae_trunk.onnx", so)
5
+ head = ort.InferenceSession(f"{R}/vae_head/vae_head.onnx", so)
6
+ full = ort.InferenceSession(f"{R}/vae_dec/vae_dec.onnx", so)
7
+ x = np.load(sys.argv[1])["latent"].astype(np.float32)
8
+ _, _, h, w = x.shape
9
+ vs, vc = ropes.vae_tables(h, w)
10
+ feats = trunk.run(None, {"z": x, "v_sin": vs, "v_cos": vc})[0]
11
+ ref = full.run(None, {"z": x, "v_sin": vs, "v_cos": vc})[0]
12
+ whole = head.run(None, {"feats": feats})[0]
13
+ print("trunk+head vs single graph: max abs", float(np.abs(whole - ref).max()))
14
+ core, halo = int(sys.argv[2]), int(sys.argv[3])
15
+ out = np.zeros_like(whole)
16
+ for y0 in range(0, h, core):
17
+ for x0 in range(0, w, core):
18
+ y1, x1 = min(h, y0 + core), min(w, x0 + core)
19
+ ya, xa, yb, xb = max(0, y0 - halo), max(0, x0 - halo), min(h, y1 + halo), min(w, x1 + halo)
20
+ t = head.run(None, {"feats": np.ascontiguousarray(feats[:, :, ya:yb, xa:xb])})[0]
21
+ out[:, :, y0 * 16:y1 * 16, x0 * 16:x1 * 16] = t[:, :, (y0 - ya) * 16:(y1 - ya) * 16, (x0 - xa) * 16:(x1 - xa) * 16]
22
+ d = np.abs(out - whole)
23
+ print(f"tiled core={core} halo={halo} vs whole: max abs {d.max():.2e}, mean {d.mean():.2e}")
scripts/verify.py CHANGED
@@ -89,10 +89,10 @@ t0 = time.time()
89
  v0 = velocity(lat0, float(times[0]))
90
  print(f"vel[0] cos={cos(v0, ref['vels'][0]):.6f} rel={rel(v0, ref['vels'][0]):.2e} {time.time()-t0:.1f}s/step")
91
  xs = [lat0]
92
- for i in range(len(times) - 2):
93
  xs.append(xs[-1] + np.float32(times[i + 1] - times[i]) * ref["vels"][i])
94
  tf = [cos(v0, ref["vels"][0])] + [cos(velocity(xs[i], float(times[i])), ref["vels"][i])
95
- for i in range(1, len(times) - 1)]
96
  print("teacher-forced vel cos:", " ".join(f"{c:.5f}" for c in tf), f"min={min(tf):.5f}")
97
  if not full:
98
  sys.exit()
@@ -103,6 +103,10 @@ for i in range(len(times) - 1):
103
  print(f"vel[{i}] cos={cos(v, ref['vels'][i]):.6f}")
104
  x = x + np.float32(times[i + 1] - times[i]) * v
105
  print(f"latent cos={cos(x, ref['latent']):.6f} rel={rel(x, ref['latent']):.2e}")
 
 
 
 
106
  vs, vc = ropes.vae_tables(gh, gw)
107
  t0 = time.time()
108
  rgb = sess("vae_dec").run(None, {"z": x.astype(np.float32), "v_sin": vs, "v_cos": vc})[0]
@@ -110,7 +114,8 @@ want = (ref["rgb"] + 1) * 0.5
110
  print(f"rgb cos={cos(rgb, want):.6f} maxabs={np.abs(rgb-want).max():.3f} "
111
  f"psnr={10*math.log10(1/np.mean((rgb-want)**2)):.1f}dB {time.time()-t0:.1f}s")
112
  img = (rgb[0].transpose(1, 2, 0) * 255).round().clip(0, 255).astype(np.uint8)
113
- out = SP / "work" / f"onnx_{tag}.png"
 
114
  Image.fromarray(img).save(out)
115
  print("saved", out)
116
  if "--dump" in sys.argv:
 
89
  v0 = velocity(lat0, float(times[0]))
90
  print(f"vel[0] cos={cos(v0, ref['vels'][0]):.6f} rel={rel(v0, ref['vels'][0]):.2e} {time.time()-t0:.1f}s/step")
91
  xs = [lat0]
92
+ for i in range(len(times) - 2 if "--no-tf" not in sys.argv else 0):
93
  xs.append(xs[-1] + np.float32(times[i + 1] - times[i]) * ref["vels"][i])
94
  tf = [cos(v0, ref["vels"][0])] + [cos(velocity(xs[i], float(times[i])), ref["vels"][i])
95
+ for i in range(1, len(xs))]
96
  print("teacher-forced vel cos:", " ".join(f"{c:.5f}" for c in tf), f"min={min(tf):.5f}")
97
  if not full:
98
  sys.exit()
 
103
  print(f"vel[{i}] cos={cos(v, ref['vels'][i]):.6f}")
104
  x = x + np.float32(times[i + 1] - times[i]) * v
105
  print(f"latent cos={cos(x, ref['latent']):.6f} rel={rel(x, ref['latent']):.2e}")
106
+ name0 = next((a.split("=", 1)[1] for a in sys.argv if a.startswith("--name=")), f"onnx_{tag}")
107
+ np.save(SP / "work" / f"{name0}_latent.npy", x)
108
+ if "--no-decode" in sys.argv:
109
+ sys.exit()
110
  vs, vc = ropes.vae_tables(gh, gw)
111
  t0 = time.time()
112
  rgb = sess("vae_dec").run(None, {"z": x.astype(np.float32), "v_sin": vs, "v_cos": vc})[0]
 
114
  print(f"rgb cos={cos(rgb, want):.6f} maxabs={np.abs(rgb-want).max():.3f} "
115
  f"psnr={10*math.log10(1/np.mean((rgb-want)**2)):.1f}dB {time.time()-t0:.1f}s")
116
  img = (rgb[0].transpose(1, 2, 0) * 255).round().clip(0, 255).astype(np.uint8)
117
+ name = next((a.split("=", 1)[1] for a in sys.argv if a.startswith("--name=")), f"onnx_{tag}")
118
+ out = SP / "work" / f"{name}.png"
119
  Image.fromarray(img).save(out)
120
  print("saved", out)
121
  if "--dump" in sys.argv:
vae_dec/vae_dec.onnx DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:4c3af48e76e304ceacd67d386333a1366e136db1d268d8b7843b3c656055f937
3
- size 26456362
 
 
 
 
vae_dec/vae_dec.onnx.data DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:a63eafe6f1c29b58ace1793f3a39f78fdea9c45efd46ee42cf92df88452637f0
3
- size 115682304