abhisheksensharma commited on
Commit
ae4e95d
·
verified ·
1 Parent(s): 3c442e1

Upload folder using huggingface_hub

Browse files
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md CHANGED
@@ -1,3 +1,252 @@
1
  ---
2
  license: apache-2.0
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: apache-2.0
3
+ pipeline_tag: image-to-video
4
+ tags:
5
+ - world-model
6
+ - interactive
7
+ - real-time
8
+ - autoregressive
9
+ - video-generation
10
  ---
11
+
12
+ # GTA world model: weights and inference code
13
+
14
+ An interactive world model. You give it one start image, then hold keys; it generates the video that follows,
15
+ one frame at a time, and streams it to a browser while you play.
16
+
17
+ The architecture is **Summaryformer**. It is my own design: I arrived at it after testing a lot of ideas on
18
+ consumer hardware, and I trained it from scratch. This checkpoint was trained on GG800, my new 800-hour GTA5
19
+ dataset.
20
+
21
+ This repository holds the weights and the complete inference runtime: the model, its memory, the sampler and the
22
+ streaming server. There is no training code here. What I took from other people's work is listed under
23
+ [Credits](#credits).
24
+
25
+ ## The memory
26
+
27
+ The part of Summaryformer I most want people to read about is how a frame remembers the past.
28
+
29
+ A frame generated a second ago matters in detail: the next frame has to continue its motion pixel for pixel.
30
+ A frame generated many seconds ago matters only in outline: what was there, roughly where. Keeping every past
31
+ frame at full resolution spends almost all of the attention budget on detail nobody needs. Keeping only a short
32
+ window forgets everything else.
33
+
34
+ So every frame in this model is stored twice, at two sizes, and the model itself writes both.
35
+
36
+ ### A frame is a record
37
+
38
+ Each frame enters the transformer as one **record**:
39
+
40
+ ```
41
+ record(t) = [ raw(t) : H*W tokens ] ++ [ sum(t) : X tokens ]
42
+ ```
43
+
44
+ - `raw(t)` is the frame's latent grid, one token per cell. At the served 384x672 that is 24x42 = 1008 tokens.
45
+ - `sum(t)` is X = 96 **summary tokens**. They start from a learned init (the same for every frame), have no
46
+ position on the grid, and go through the same 28 blocks in the same forward pass as the raw tokens. By the last
47
+ block they hold a compact description of the frame.
48
+
49
+ There is no separate summarizer network and no extra pass. The summary is a by-product of generating the frame.
50
+
51
+ ### What a frame attends to
52
+
53
+ While frame `t` is being generated, every one of its tokens attends to:
54
+
55
+ 1. itself: the raw tokens and the summary tokens of frame `t`;
56
+ 2. the last Y = 2 frames, as whole records (full resolution);
57
+ 3. the older frames inside the window W = 24, **as their 96 summary tokens only**;
58
+ 4. frame 0, the start image, as a whole record. It is never evicted.
59
+
60
+ Recent frames give local detail. Summaries give the long horizon. The start image anchors the scene.
61
+
62
+ ### One buffer, no mask
63
+
64
+ All of this is one preallocated key/value buffer per block:
65
+
66
+ ```
67
+ | Z0 : record(0) | RAW : (Y+1) records, rotating | SUM : (W-Y) x X summary rows, rotating |
68
+ read = buffer[0 : end]
69
+ ```
70
+
71
+ - `Z0` holds the start image's record.
72
+ - `RAW` holds the frame being generated and the Y frames before it.
73
+ - `SUM` holds one X-row summary for each older frame in the window.
74
+
75
+ When a frame falls out of the raw window, the keys and values of its 96 summary tokens are copied from `RAW`
76
+ into `SUM`, and its 1008 raw rows are overwritten by the next frame. That copy of 96 rows per block is the entire
77
+ cost of moving a frame into long-term memory.
78
+
79
+ Attention is one dense read of the filled prefix of that buffer per block. There is no attention mask and no
80
+ concatenation: what a frame may see is decided by what is in the buffer.
81
+
82
+ At the served resolution with the trained window, the buffer holds 6,528 keys. The same span with every frame
83
+ kept at full resolution would be 26,208.
84
+
85
+ | | |
86
+ |---|---|
87
+ | summary tokens per frame (X) | 96 |
88
+ | raw tokens per frame at 384x672 | 1008 |
89
+ | frames kept whole (Y) | 2 |
90
+ | memory window in frames (W) | 24 trained; the server default serves 16 |
91
+
92
+ One body frame of latents decodes to 4 RGB frames, so a window of 24 covers 96 RGB frames.
93
+
94
+ ### Telling a summary from a pixel: level planes
95
+
96
+ Raw tokens and summary tokens of the same frame share a temporal position, so rotary position embeddings alone
97
+ cannot tell them apart. I did not add a token-type embedding. Instead the two lowest-frequency planes of the
98
+ temporal RoPE band are used as a **level axis**.
99
+
100
+ Each attention head has 12 temporal planes. The two slowest rotate by less than half a radian over 1024 frames,
101
+ and by a small fraction of that over the distances that occur inside the memory window, so for raw tokens they
102
+ carry no usable position. Summary tokens get an exact quarter
103
+ turn on those two planes. A query can then weight "summary of frame t" and "pixel of frame t" independently,
104
+ using dimensions that were otherwise idle. The model checks at construction that those planes really are idle
105
+ and refuses to build if they are not.
106
+
107
+ ### Running for a long time: the start image follows the window
108
+
109
+ Frame ids keep growing as the session goes on, but the start image was written at id 0. Left alone, the
110
+ temporal distance between the start image and the live window would grow without bound.
111
+
112
+ RoPE keys are rotations, and `rotation(id + T) = rotation(id) * rotation(T)`. So a stored key can be moved
113
+ forward in time by multiplying it, in place, by one more rotation. Whenever the gap between the start image and
114
+ the oldest frame in memory reaches 5, the start image's keys are rotated forward to bring the gap back to 1.
115
+ Values are untouched. Nothing is recomputed.
116
+
117
+ ### What I believe is new
118
+
119
+ - Summary tokens produced by the generator's own forward pass, kept as the only trace of older frames, with full
120
+ records kept for the newest few.
121
+ - One key/value buffer with a raw region and a summary region, fed by eviction, read with a single unmasked
122
+ attention call.
123
+ - Level planes: marking token kind with a fixed rotation on RoPE planes that carry no position.
124
+ - Rotating the cached keys of the anchor frame so it stays next to a moving window.
125
+
126
+ ## The rest of the model
127
+
128
+ - **Size.** 630,205,008 parameters. 28 blocks, width 1280, 20 heads of 64, SwiGLU feed-forward.
129
+ - **Latents.** 48 channels on a /16 grid. The start image is one latent frame; every later latent frame is 4 RGB
130
+ frames.
131
+ - **Two entrances, two exits.** The start image and the generated frames have separate token embeddings and
132
+ separate output heads on the same trunk. One is a still image and the other is video.
133
+ - **Conditioning.** There is no text. The denoising timestep modulates every block. The player's action
134
+ (5 numbers), the frame rate and the grid shape are added to that modulation, each through its own learned
135
+ per-block gate.
136
+ - **Sampling.** Each frame takes three denoising passes (t = 999, 878, 669) and one more pass on the clean result,
137
+ which rewrites that frame's entry in memory. The memory always holds clean frames.
138
+ - **Positions.** One rotary table with temporal, height and width bands, indexed in time by frame id. This part
139
+ is adapted from Wan2.1 (see Credits); the level planes and the changes listed in `rope.py` are mine.
140
+ - **Diffusion.** v-prediction on a cosine noise schedule with a log-SNR shift. Inference needs only the
141
+ signal and noise scale at the few timesteps a frame is denoised at; that is all of `noise_schedule.py`.
142
+ - **Attention kernels.** Two: PyTorch FlexAttention and FlashAttention's `flash_attn_with_kvcache`. The server uses
143
+ FlexAttention.
144
+
145
+ ## Files
146
+
147
+ ```
148
+ serve_ckpts/
149
+ gta_model.pt the model weights
150
+ sae_compact.pt the autoencoder weights
151
+ latent_stats_*.pt per-channel mean / std of the autoencoder's latent
152
+ summary_server.py FastAPI server: start image in, H.264 out, keys in
153
+ summary_streaming_inference.py one session: the per-frame loop
154
+ summaryformer.py the model
155
+ summaryformer_wrapper.py the model's public surface
156
+ gta_streaming_kv_cache.py the memory buffer
157
+ summaryformer_utils/
158
+ transformer_block.py the block
159
+ rope.py rotary positions and level planes
160
+ streaming_sink.py moving the start image's keys
161
+ latent_head.py output head
162
+ visual_mlp.py SwiGLU feed-forward
163
+ z0_focus_mask.py optional focus region on the start image
164
+ rollout_flex_attention.py FlexAttention kernel
165
+ fast_flash_kv.py FlashAttention kernel
166
+ recency_bias.py optional recency bias on summary keys
167
+ streaming_server_utils/
168
+ ckpt_name_schema.py checkpoint file names
169
+ controls.py keys to the model's 5-number action
170
+ sae.py the autoencoder (parallel and autoregressive encode / decode)
171
+ noise_schedule.py the noise schedule and the timesteps a frame is denoised at
172
+ inference_common.py small shared helpers
173
+ ```
174
+
175
+ ## Running it
176
+
177
+ Requirements: a CUDA GPU; Python with `torch` (FlexAttention and `torch.compile`), `numpy`, `fastapi`, `uvicorn`,
178
+ `pillow`, `av`, `imageio`. `flash_attn` is optional.
179
+
180
+ Everything the server needs is in this repository, at the paths its settings point to. The settings are the
181
+ `CONFIG` dict at the top of `summary_server.py`:
182
+
183
+ - the model checkpoint, in `checkpoints_dir` (default `serve_ckpts/`): `serve_ckpts/gta_model.pt`;
184
+ - the autoencoder checkpoint (`sae_ckpt`, default `sae_compact.pt`): the encoder that turns the start image
185
+ into a latent and the decoder that turns latents into frames;
186
+ - two latent-statistics files: `latent_stats_z0.pt` (start image) and `latent_stats_z_rest.pt` (generated
187
+ frames). They hold the per-channel mean and standard deviation of the autoencoder's latent.
188
+
189
+ Download the repository and start the server from its root:
190
+
191
+ ```
192
+ hf download lucidml/gta --local-dir gta
193
+ cd gta
194
+ python summary_server.py # serves on 0.0.0.0:3002
195
+ ```
196
+
197
+ At startup the server loads the weights, compiles the model and plays a short warm-up session, so the first start
198
+ takes a while. One GPU process serves one player at a time.
199
+
200
+ The browser client is not in this repository. The protocol is small:
201
+
202
+ | | |
203
+ |---|---|
204
+ | `POST /z0/{user_id}` | upload the start image (form field `z0_image`) |
205
+ | `WS /ws/{user_id}` | the session |
206
+ | `GET /status`, `GET /models` | occupancy and the available checkpoints |
207
+
208
+ On the WebSocket the server sends binary messages, one byte (`0x01` key frame, `0x00` delta frame) followed by an
209
+ H.264 Annex-B access unit at 384x672. The client sends JSON with the keys currently held:
210
+
211
+ ```json
212
+ {"type": "keys", "pressed": {"w": true, "a": false, "s": false, "d": false, "shift": false, "space": false, "left": false, "right": true}}
213
+ ```
214
+
215
+ ## Limits
216
+
217
+ - Sessions are finite. The position table is extended to 4096 frame ids at startup and a session stops when it
218
+ reaches the last one. The server also has a wall-clock limit per session (`ws_session_limit_s`, default 180 s;
219
+ 0 disables it).
220
+ - CUDA only.
221
+
222
+ ## Credits
223
+
224
+ Summaryformer is my own architecture and this model was trained from scratch. These are the pieces that came
225
+ from other people:
226
+
227
+ - **KV-cached inference, learned from Self-Forcing.** The
228
+ [Self-Forcing](https://github.com/guandeh17/Self-Forcing) repo (Apache-2.0; arXiv 2506.08009) is where I
229
+ learned how a KV cache works for autoregressive video and how to run inference with one. Self-Forcing is itself
230
+ built on Wan2.1. The memory here is a different design, but that is where I learned the technique, and the
231
+ `conditional_dict` name at the model's boundary is from there.
232
+ - **Rotary positions, from Wan2.1.** I found the Wan2.1 code hard to follow at first. The part of it that
233
+ mattered most for this model was its rotary positions, so that is the part I adapted: the 3-D rotary position
234
+ code, and the way it handles time by giving every frame an integer id that indexes the temporal band of the
235
+ table. [Wan2.1](https://github.com/Wan-Video/Wan2.1) is Apache-2.0, Copyright 2024-2025 The Alibaba Wan Team
236
+ Authors. `summaryformer_utils/rope.py` lists what I changed.
237
+ - **Noise schedule and parameterization, from the literature.** The cosine schedule is from Nichol & Dhariwal,
238
+ *Improved Denoising Diffusion Probabilistic Models* (arXiv 2102.09672). The log-SNR shift is from Hoogeboom
239
+ et al., *simple diffusion* (arXiv 2301.11093). v-prediction is from Salimans & Ho, *Progressive Distillation
240
+ for Fast Sampling of Diffusion Models* (arXiv 2202.00512). `noise_schedule.py` is my own
241
+ implementation of those formulas.
242
+ - **Streaming convolutions in the autoencoder, from Wan2.1.** The autoencoder is my own network and was trained
243
+ from scratch. Its causal 3-D convolution, which carries a two-frame tail of the past from one call to the
244
+ next, and the clip layout of one first frame followed by groups of 4, follow the
245
+ [Wan2.1](https://github.com/Wan-Video/Wan2.1) VAE (Apache-2.0).
246
+ - [FlashAttention](https://github.com/Dao-AILab/flash-attention) and PyTorch FlexAttention for the attention
247
+ kernels.
248
+ - The optional recency bias follows Recency Forcing (arXiv 2609.19729).
249
+
250
+ ## License
251
+
252
+ Apache-2.0. See `LICENSE`.
gta_streaming_kv_cache.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Summaryformer visual KV cache: one buffer, two regions, two cursors, one dense prefix read.
2
+
3
+ One ``SummaryKVCache`` per session, one entry per trunk layer.
4
+
5
+ Per layer, ONE preallocated ``[B, cap, H, D]`` K and the matching V (flash layout)::
6
+
7
+ REC = Tf + X one RECORD = raw(t) ++ sum(t)
8
+ REC_z0 = Z + X (0 when z0_tokens=0) z0's record; no Z0 region and no sink when Z = 0
9
+
10
+ | Z0 : REC_z0 | RAW : (Y+1) slots x REC, rotating | SUM : (W-Y) slots x X, rotating |
11
+ read = [0 : end]
12
+
13
+ cap = REC_z0 + (Y+1)*REC + (W-Y)*X
14
+ end = REC_z0 + n_raw*REC + filled_s*X
15
+
16
+ * ``Z0`` holds frame 0's whole record (the sink). Written by the z0 pass, never evicted. ``streaming_sink``
17
+ rotates this ONE slot's K (RoPE, temporal band only). ``z0_tokens=0`` at ``build`` removes the region.
18
+ * ``RAW`` holds the CURRENT record and the Y history records. There is no separate tail. Every denoising
19
+ pass of frame t writes ``record(t)`` at ``raw_slot_start(cursor_r)`` (constant within the frame).
20
+ Commit is ``cursor_r += 1 (mod Y+1)``, ``filled_r = min(filled_r+1, Y+1)``. No copy on commit.
21
+ * ``SUM`` is fed by eviction. ``begin_frame`` — before the first write of a frame — if ``cursor_r`` holds a
22
+ committed record (``filled_r == Y+1``) and ``W > Y``, copies that slot's X summary rows (``[Tf : Tf+X]``)
23
+ into SUM slot ``cursor_s``, then ``cursor_s += 1 (mod W-Y)``, ``filled_s = min(filled_s+1, W-Y)``. When
24
+ ``W == Y`` there is no SUM region and that donation is skipped (no copy, cursor stays). One X-row copy per
25
+ layer per frame otherwise. Nothing is evicted before RAW is full, so the live prefix is contiguous through warm-up:
26
+ ``Z0 ++ RAW[0 : n_raw*REC] ++ SUM[0 : filled_s*X]``. ``n_raw`` counts RAW slots that hold valid keys,
27
+ including the slot being written this frame.
28
+ * ``end`` is a Python int on the eager plan and one persistent 0-d int64 device tensor (``end_dev``, updated
29
+ in place) for a compiled forward. Every query of the frame — the raw rows and the X summary rows — reads
30
+ that same prefix: one ``attend_buffer_prefix`` per layer, ``Lq = REC``.
31
+ * Slot order inside a region does not matter (K carries absolute-id RoPE). No duplicate keys: a frame inside
32
+ the raw window is its whole record, a frame beyond it is its X summary rows, frame 0 is the sink record.
33
+
34
+ Lifecycle (K denoising passes per frame, then the caller commits)::
35
+
36
+ z0 : plan = cache.plan_z0()
37
+ each pass writes record(0) into Z0 and reads [0 : REC_z0]
38
+ after the clean z0 warm the caller calls cache.note_z0_written()
39
+ body : cache.begin_frame() donation, once, before the first write (idempotent until commit)
40
+ plan = cache.plan_body() write offset + end; also calls begin_frame
41
+ each pass writes the whole record at plan.write and reads [0 : end]
42
+ "recache": one more t=0 pass rewrites that same RAW slot with the clean record, then commit
43
+ "last_step_writes": commit the slot the last pass already wrote (noisy x_t); no extra pass
44
+ commit_current_frame() advances cursor_r. No copy.
45
+
46
+ ``plan_body()`` returns ``end`` as a Python int. ``plan_body(device_ends=True)`` returns ``end_dev``.
47
+ The write offset is always an int (the slot does not move during the frame).
48
+
49
+ Recency bias is OFF unless ``enable_recency`` is called. The hook is the existing per-key additive bias
50
+ over this one buffer (zeros on Z0 and RAW, values on SUM rows). No new kernel: the block passes it on the
51
+ single prefix read. ``begin_frame`` refreshes Δ after the donation updates the slot→frame map (a warm-up
52
+ frame with nothing donated still refreshes; the SUM rows stay 0).
53
+
54
+ No mask. No ``torch.cat`` on this path: donation and the block's write are slice copies into
55
+ storage allocated in ``build``.
56
+ """
57
+ from __future__ import annotations
58
+
59
+ from typing import NamedTuple, Optional
60
+
61
+ import torch
62
+
63
+ from summaryformer_utils.recency_bias import RECENCY_BIAS_KEY, RecencyBiasConfig, RecencyBiasState
64
+
65
+
66
+ class SummaryKVPlan(NamedTuple):
67
+ """What ONE KV-cached forward of ONE frame does to / reads from the buffer.
68
+
69
+ Built by ``SummaryKVCache.plan_z0`` / ``plan_body``. Consumed by ``SelfAttention._attend_with_cache``.
70
+ One write offset, one end, ``query_tokens`` queries (the whole record).
71
+ """
72
+
73
+ kind: str # "z0" | "body"
74
+ raw_tokens: int # raw rows in this frame's record (Z for the z0 pass, Tf for a body pass)
75
+ summary_tokens: int # X
76
+ write: int # row where the WHOLE record [raw | sum] is written
77
+ end: "int | torch.Tensor" # every query attends buffer[0 : end]
78
+ # Plain FIELDS, not @property: dynamo traces NamedTuple fields as constants but turns a property on a
79
+ # NamedTuple into an opaque GetAttrVariable, so `int(kv_plan.query_tokens)` graph-broke once per block in the
80
+ # compiled body. plan_z0 / plan_body fill them.
81
+ query_tokens: int # raw_tokens + summary_tokens (the record width every block must receive)
82
+ ends_are_device: bool # isinstance(end, torch.Tensor): the compiled streaming form
83
+
84
+
85
+ class SummaryKVCache(torch.nn.Module):
86
+ """One-buffer visual KV cache for the Summaryformer trunk (module docstring has the layout and the lifecycle).
87
+
88
+ Geometry comes from the MODEL (``summary_tokens`` = X, ``raw_window_frames`` = Y, ``summary_window_frames`` = W,
89
+ ``num_layers``, heads, head_dim). ``W`` is the total memory span and must be ``>= Y`` (``W == Y`` is an empty
90
+ SUM region). ``build`` takes the only per-bucket number, ``frame_tokens`` = Tf (and ``z0_tokens``, default Tf).
91
+ """
92
+
93
+ def __init__(self, model) -> None:
94
+ super().__init__()
95
+ for attr in ("summary_tokens", "raw_window_frames", "summary_window_frames", "num_layers", "num_heads", "dim"):
96
+ if not hasattr(model, attr):
97
+ raise TypeError(f"SummaryKVCache(model): model lacks `{attr}` (expected Summaryformer).")
98
+ self.summary_tokens = int(model.summary_tokens) # X
99
+ self.raw_window_frames = int(model.raw_window_frames) # Y
100
+ self.summary_window_frames = int(model.summary_window_frames) # W, total span, raw window included
101
+ self.num_layers = int(model.num_layers)
102
+ self.num_heads = int(model.num_heads)
103
+ self.head_dim = int(model.dim) // int(model.num_heads)
104
+ if self.summary_tokens < 1:
105
+ raise ValueError(f"summary_tokens must be >= 1; got {self.summary_tokens}.")
106
+ if self.raw_window_frames < 0 or self.summary_window_frames < 0:
107
+ raise ValueError(
108
+ f"raw_window_frames / summary_window_frames must be >= 0; got "
109
+ f"{self.raw_window_frames} / {self.summary_window_frames}."
110
+ )
111
+ if self.summary_window_frames < self.raw_window_frames:
112
+ raise ValueError(
113
+ f"summary_window_frames={self.summary_window_frames} < raw_window_frames={self.raw_window_frames}: "
114
+ "W is the total memory span, raw window included."
115
+ )
116
+
117
+ self.frame_tokens: Optional[int] = None # Tf
118
+ self.z0_tokens: Optional[int] = None # Z (0 = no sink)
119
+ self.batch: Optional[int] = None
120
+ self.capacity: Optional[int] = None
121
+ # Per-layer [{"k","v"[, RECENCY_BIAS_KEY]}]. Allocated in build().
122
+ self.layers: Optional[list] = None
123
+
124
+ self.cursor_r = 0
125
+ self.cursor_s = 0
126
+ self.filled_r = 0 # committed records currently sitting in RAW (0 .. Y+1)
127
+ self.filled_s = 0 # summaries currently sitting in SUM (0 .. W-Y)
128
+ self.n_committed = 0 # body frames committed this session (recency Δ; not a slot count)
129
+ self.z0_written = False
130
+ self._body_open = False # True after begin_frame, False after commit
131
+ self.end_dev: Optional[torch.Tensor] = None
132
+ self.recency: Optional[RecencyBiasState] = None
133
+
134
+ # ------------------------------------------------------------------ #
135
+ # Geometry.
136
+ # ------------------------------------------------------------------ #
137
+ def _require_built(self) -> None:
138
+ if self.layers is None or self.frame_tokens is None or self.z0_tokens is None:
139
+ raise RuntimeError("SummaryKVCache.build(...) must be called before use.")
140
+
141
+ @property
142
+ def record_tokens(self) -> int:
143
+ """REC = Tf + X."""
144
+ self._require_built()
145
+ return int(self.frame_tokens) + int(self.summary_tokens)
146
+
147
+ @property
148
+ def z0_record_tokens(self) -> int:
149
+ """REC_z0 = Z + X, or 0 when built without a sink."""
150
+ self._require_built()
151
+ return int(self.z0_tokens) + int(self.summary_tokens) if int(self.z0_tokens) > 0 else 0
152
+
153
+ @property
154
+ def has_sink(self) -> bool:
155
+ self._require_built()
156
+ return int(self.z0_tokens) > 0
157
+
158
+ @property
159
+ def n_raw_slots(self) -> int:
160
+ """Y+1: the current record plus Y history records."""
161
+ return int(self.raw_window_frames) + 1
162
+
163
+ @property
164
+ def n_sum_slots(self) -> int:
165
+ """W−Y SUM-region slots. 0 when W == Y (nothing is evicted into SUM)."""
166
+ return int(self.summary_window_frames) - int(self.raw_window_frames)
167
+
168
+ @property
169
+ def raw_region_start(self) -> int:
170
+ self._require_built()
171
+ return int(self.z0_record_tokens)
172
+
173
+ @property
174
+ def sum_region_start(self) -> int:
175
+ self._require_built()
176
+ return int(self.raw_region_start + self.n_raw_slots * self.record_tokens)
177
+
178
+ def z0_span(self) -> tuple[int, int]:
179
+ """``[start, end)`` of the one Z0 slot (empty when built without a sink)."""
180
+ self._require_built()
181
+ return 0, int(self.z0_record_tokens)
182
+
183
+ def raw_slot_start(self, slot: int) -> int:
184
+ slot = int(slot)
185
+ if not 0 <= slot < self.n_raw_slots:
186
+ raise IndexError(f"raw slot {slot} outside [0, {self.n_raw_slots}).")
187
+ return int(self.raw_region_start + slot * self.record_tokens)
188
+
189
+ def sum_slot_start(self, slot: int) -> int:
190
+ slot = int(slot)
191
+ if self.n_sum_slots <= 0 or not 0 <= slot < self.n_sum_slots:
192
+ raise IndexError(f"summary slot {slot} outside [0, {self.n_sum_slots}).")
193
+ return int(self.sum_region_start + slot * int(self.summary_tokens))
194
+
195
+ # ------------------------------------------------------------------ #
196
+ # The one attended length.
197
+ # ------------------------------------------------------------------ #
198
+ def n_raw_live(self) -> int:
199
+ """RAW slots that hold valid keys. Includes the slot being written while a body frame is open."""
200
+ self._require_built()
201
+ if self._body_open:
202
+ if int(self.filled_r) < self.n_raw_slots:
203
+ return int(self.filled_r) + 1
204
+ return self.n_raw_slots
205
+ return int(self.filled_r)
206
+
207
+ def end_body(self) -> int:
208
+ """``REC_z0 + n_raw*REC + filled_s*X``. During an open frame this is the prefix every query reads."""
209
+ self._require_built()
210
+ return int(
211
+ self.z0_record_tokens
212
+ + self.n_raw_live() * self.record_tokens
213
+ + int(self.filled_s) * int(self.summary_tokens)
214
+ )
215
+
216
+ def _sync_end_dev(self) -> None:
217
+ if isinstance(self.end_dev, torch.Tensor):
218
+ self.end_dev.fill_(int(self.end_body()))
219
+
220
+ def device_scalars(self) -> tuple[torch.Tensor, ...]:
221
+ """``(end_dev,)``: the persistent 0-d device tensor (mark it static for cudagraphs)."""
222
+ self._require_built()
223
+ if not isinstance(self.end_dev, torch.Tensor):
224
+ raise RuntimeError("SummaryKVCache end scalar missing: build() allocates it.")
225
+ return (self.end_dev,)
226
+
227
+ # ------------------------------------------------------------------ #
228
+ # Plans.
229
+ # ------------------------------------------------------------------ #
230
+ def plan_z0(self) -> SummaryKVPlan:
231
+ """Return the z0 plan: write offset 0 (the Z0 slot), every query attends ``[0 : REC_z0]``.
232
+
233
+ Does not write K/V and does not set ``z0_written`` (the caller calls ``note_z0_written``
234
+ after the clean warm). Refuses a cache built with ``z0_tokens=0``.
235
+ """
236
+ self._require_built()
237
+ if not self.has_sink:
238
+ raise RuntimeError("plan_z0 on a cache built with z0_tokens=0 (no sink).")
239
+ rec0 = int(self.z0_record_tokens)
240
+ return SummaryKVPlan(
241
+ kind="z0",
242
+ raw_tokens=int(self.z0_tokens),
243
+ summary_tokens=int(self.summary_tokens),
244
+ write=0,
245
+ end=rec0,
246
+ query_tokens=int(self.z0_tokens) + int(self.summary_tokens),
247
+ ends_are_device=False,
248
+ )
249
+
250
+ def plan_body(self, *, device_ends: bool = False) -> SummaryKVPlan:
251
+ """Open the frame (``begin_frame``, once) and return the body plan. This method does not write K/V.
252
+
253
+ The write offset is the current RAW slot; the block writes ``record(t)`` there. Every query reads
254
+ ``[0 : end]``. ``device_ends=True`` hands out ``end_dev`` (compiled streaming; ``begin_frame`` has
255
+ already filled it). Refuses to run before the sink is written when the cache has one.
256
+ """
257
+ self.begin_frame()
258
+ end = self.end_dev if device_ends else self.end_body()
259
+ return SummaryKVPlan(
260
+ kind="body",
261
+ raw_tokens=int(self.frame_tokens),
262
+ summary_tokens=int(self.summary_tokens),
263
+ write=self.raw_slot_start(int(self.cursor_r)),
264
+ end=end,
265
+ query_tokens=int(self.frame_tokens) + int(self.summary_tokens),
266
+ ends_are_device=bool(device_ends),
267
+ )
268
+
269
+ # ------------------------------------------------------------------ #
270
+ # Lifecycle: z0 warm -> begin_frame donation -> body passes -> commit (cursor advance).
271
+ # ------------------------------------------------------------------ #
272
+ def note_z0_written(self) -> None:
273
+ """Mark the clean z0 record present in Z0. Call after the clean z0 warm, before any body frame.
274
+
275
+ A second call only leaves the flag set. Refuses a cache built with ``z0_tokens=0``.
276
+ """
277
+ self._require_built()
278
+ if not self.has_sink:
279
+ raise RuntimeError("note_z0_written on a cache built with z0_tokens=0.")
280
+ self.z0_written = True
281
+
282
+ def begin_frame(self) -> None:
283
+ """Donate the RAW slot about to be overwritten, once, before this frame's first write.
284
+
285
+ Idempotent until ``commit_current_frame``: a second call returns before any copy or cursor move.
286
+ When ``filled_r == Y+1`` the slot at ``cursor_r`` holds a committed record. If ``W > Y`` its X summary
287
+ rows are copied into SUM slot ``cursor_s`` and the SUM cursor advances; when ``W == Y`` that donation
288
+ is skipped entirely (no copy, cursor stays). Then ``end_dev`` is the length of the prefix this frame's
289
+ passes will read, including the slot about to be written and, when a donation happened, the new summary.
290
+ """
291
+ self._require_built()
292
+ if self._body_open:
293
+ return
294
+ if self.has_sink and not self.z0_written:
295
+ raise RuntimeError(
296
+ "begin_frame before the sink exists: run the z0 pass and call note_z0_written() first "
297
+ "(or build with z0_tokens=0 for a sink-less stream)."
298
+ )
299
+ if int(self.filled_r) == self.n_raw_slots and self.n_sum_slots > 0:
300
+ tf = int(self.frame_tokens)
301
+ x = int(self.summary_tokens)
302
+ rs = self.raw_slot_start(int(self.cursor_r))
303
+ slot_s = int(self.cursor_s)
304
+ ss = self.sum_slot_start(slot_s)
305
+ for layer in self.layers:
306
+ layer["k"][:, ss:ss + x].copy_(layer["k"][:, rs + tf:rs + tf + x])
307
+ layer["v"][:, ss:ss + x].copy_(layer["v"][:, rs + tf:rs + tf + x])
308
+ if self.recency is not None:
309
+ # 0-based index of the body frame leaving RAW. Query frame is n_committed (not yet incremented).
310
+ self.recency.slot_frame[slot_s] = int(self.n_committed) - self.n_raw_slots
311
+ self.filled_s = min(int(self.filled_s) + 1, self.n_sum_slots)
312
+ self.cursor_s = int((slot_s + 1) % self.n_sum_slots)
313
+ self._body_open = True
314
+ if self.recency is not None:
315
+ self.recency.n_committed = int(self.n_committed)
316
+ self.recency.refresh()
317
+ self._sync_end_dev()
318
+
319
+ def commit_current_frame(self) -> None:
320
+ """Advance the RAW cursor. No copy: the passes already wrote the record into its slot.
321
+
322
+ ``cursor_r = (cursor_r + 1) mod (Y+1)``, ``filled_r = min(filled_r+1, Y+1)``, ``n_committed += 1``,
323
+ and the frame closes (``_body_open`` false), so a second commit raises until the next ``begin_frame``.
324
+ The frame must already be open (``begin_frame`` / ``plan_body``) so a commit cannot skip the donation.
325
+ """
326
+ self._require_built()
327
+ if not self._body_open:
328
+ raise RuntimeError(
329
+ "commit_current_frame before begin_frame: open the frame (plan_body / begin_frame) so an "
330
+ "evicted slot can donate its summary rows before the cursor moves."
331
+ )
332
+ self.cursor_r = int((int(self.cursor_r) + 1) % self.n_raw_slots)
333
+ self.filled_r = min(int(self.filled_r) + 1, self.n_raw_slots)
334
+ self.n_committed = int(self.n_committed) + 1
335
+ self._body_open = False
336
+ self._sync_end_dev()
337
+
338
+ # ------------------------------------------------------------------ #
339
+ # Recency hook (OFF unless enable_recency is called). Existing kernels, no new one.
340
+ # ------------------------------------------------------------------ #
341
+ def enable_recency(self, cfg) -> Optional[RecencyBiasState]:
342
+ """Per-key additive logit bias over the one buffer. Zeros on Z0 and RAW; values on SUM rows.
343
+
344
+ ``cfg``: RecencyBiasConfig | dict | None (None disables). Call AFTER ``build()``; the config survives
345
+ ``reset()``. Fails if ``decay_end`` exceeds ``W + 1`` (a summary leaves SUM at Δ = W+1). Refuses when
346
+ a body frame is open or any body frame has been committed, or the SUM cursor has moved; a z0 sink
347
+ already written is allowed (SUM is still empty). The block adds ``layer["recency_bias"]`` on the single
348
+ prefix read; the flex kernel takes it, the flash kvcache kernel does not (a biased read is always flex).
349
+ """
350
+ self._require_built()
351
+ cfg = RecencyBiasConfig.from_dict(cfg)
352
+ if cfg is None:
353
+ self.disable_recency()
354
+ return None
355
+ w = int(self.summary_window_frames)
356
+ if int(cfg.decay_end) > w + 1:
357
+ raise RuntimeError(
358
+ f"recency.decay_end={cfg.decay_end} > W + 1 = {w + 1}: a summary is evicted from SUM "
359
+ f"(Δ={w + 1}) before the bias reaches its floor; set decay_end <= {w + 1}"
360
+ )
361
+ if int(self.filled_s) != 0 or int(self.cursor_s) != 0 or self._body_open or int(self.n_committed) != 0:
362
+ raise RuntimeError("enable_recency must be called before any body frame is opened or committed and before any SUM donation (a written z0 is fine)")
363
+ buf = self.layers[0]["k"]
364
+ cap, device = int(buf.size(1)), buf.device
365
+ reuse = None
366
+ if (
367
+ self.recency is not None
368
+ and tuple(self.recency.token_bias.shape) == (cap,)
369
+ and self.recency.token_bias.device == device
370
+ ):
371
+ reuse = self.recency.token_bias
372
+ self.recency = RecencyBiasState(
373
+ cfg,
374
+ ring_frames=int(self.n_sum_slots),
375
+ ring_start=int(self.sum_region_start),
376
+ frame_tokens=int(self.summary_tokens),
377
+ capacity=cap,
378
+ device=device,
379
+ token_bias=reuse,
380
+ )
381
+ self._attach_recency()
382
+ return self.recency
383
+
384
+ def disable_recency(self) -> None:
385
+ self.recency = None
386
+ if isinstance(self.layers, list):
387
+ for layer in self.layers:
388
+ layer.pop(RECENCY_BIAS_KEY, None)
389
+
390
+ def _attach_recency(self) -> None:
391
+ if self.recency is None or not isinstance(self.layers, list):
392
+ return
393
+ for layer in self.layers:
394
+ layer[RECENCY_BIAS_KEY] = self.recency.token_bias
395
+
396
+ # ------------------------------------------------------------------ #
397
+ # Allocation / reset.
398
+ # ------------------------------------------------------------------ #
399
+ def build(
400
+ self,
401
+ *,
402
+ batch: int,
403
+ frame_tokens: int,
404
+ dtype: torch.dtype,
405
+ device: torch.device,
406
+ z0_tokens: int | None = None,
407
+ allow_oversize_reuse: bool = False,
408
+ ) -> None:
409
+ """Allocate (or reuse) the one K/V buffer per layer and ``end_dev``; zero them; reset state.
410
+
411
+ Args:
412
+ frame_tokens: Tf, tokens per body frame at this bucket.
413
+ z0_tokens: Z, tokens of the z0 frame (default Tf). 0 = no Z0 region, no sink.
414
+ allow_oversize_reuse: also reuse a buffer whose row axis is LONGER than ``cap`` (same B/H/D/dtype/
415
+ device). Every read is ``[0:end]`` and every write is at a geometry offset.
416
+
417
+ Reuses existing storage when shape/dtype/device match so addresses stay stable (cudagraphs).
418
+ """
419
+ frame_tokens = int(frame_tokens)
420
+ z0_tokens = frame_tokens if z0_tokens is None else int(z0_tokens)
421
+ if frame_tokens <= 0:
422
+ raise ValueError(f"frame_tokens must be > 0; got {frame_tokens}.")
423
+ if z0_tokens < 0:
424
+ raise ValueError(f"z0_tokens must be >= 0; got {z0_tokens}.")
425
+ x = int(self.summary_tokens)
426
+ rec = frame_tokens + x
427
+ rec0 = (z0_tokens + x) if z0_tokens > 0 else 0
428
+ n_raw = int(self.raw_window_frames) + 1
429
+ n_sum = int(self.summary_window_frames) - int(self.raw_window_frames)
430
+ cap = int(rec0 + n_raw * rec + n_sum * x)
431
+ b, h, d = int(batch), int(self.num_heads), int(self.head_dim)
432
+ device = torch.device(device)
433
+
434
+ def _reusable(have) -> bool:
435
+ return (
436
+ isinstance(have, torch.Tensor)
437
+ and have.dtype == dtype
438
+ and have.device == device
439
+ and int(have.dim()) == 4
440
+ and (int(have.size(0)), int(have.size(2)), int(have.size(3))) == (b, h, d)
441
+ and (int(have.size(1)) == cap or (bool(allow_oversize_reuse) and int(have.size(1)) > cap))
442
+ )
443
+
444
+ have_layers = (
445
+ isinstance(self.layers, list)
446
+ and len(self.layers) == int(self.num_layers)
447
+ and all(isinstance(layer, dict) for layer in self.layers)
448
+ )
449
+ can_reuse = have_layers and _reusable(self.layers[0].get("k")) and _reusable(self.layers[0].get("v"))
450
+
451
+ self.frame_tokens = frame_tokens
452
+ self.z0_tokens = z0_tokens
453
+ self.batch = b
454
+ self.capacity = cap
455
+
456
+ if can_reuse:
457
+ for layer in self.layers:
458
+ layer["k"].zero_()
459
+ layer["v"].zero_()
460
+ else:
461
+ self.layers = [
462
+ {
463
+ "k": torch.zeros((b, cap, h, d), dtype=dtype, device=device),
464
+ "v": torch.zeros((b, cap, h, d), dtype=dtype, device=device),
465
+ }
466
+ for _ in range(int(self.num_layers))
467
+ ]
468
+ if not (isinstance(self.end_dev, torch.Tensor) and self.end_dev.device == device):
469
+ self.end_dev = torch.zeros((), dtype=torch.long, device=device)
470
+ self.reset_state()
471
+ if self.recency is not None:
472
+ self.enable_recency(self.recency.cfg)
473
+
474
+ def reset_state(self) -> None:
475
+ """Reset the mutable stream counters only (NOT the buffers)."""
476
+ self.cursor_r = 0
477
+ self.cursor_s = 0
478
+ self.filled_r = 0
479
+ self.filled_s = 0
480
+ self.n_committed = 0
481
+ self.z0_written = False
482
+ self._body_open = False
483
+ if self.layers is not None and self.frame_tokens is not None and self.z0_tokens is not None:
484
+ self._sync_end_dev()
485
+ if self.recency is not None:
486
+ self.recency.reset()
487
+
488
+ def reset(self) -> None:
489
+ """Zero the buffers in place and reset counters. Keeps addresses stable."""
490
+ if isinstance(self.layers, list):
491
+ for layer in self.layers:
492
+ layer["k"].zero_()
493
+ layer["v"].zero_()
494
+ self.reset_state()
495
+
496
+ def release(self) -> None:
497
+ """Drop the storages. The next ``build()`` allocates again."""
498
+ self.disable_recency()
499
+ if isinstance(self.layers, list):
500
+ for layer in self.layers:
501
+ layer.clear()
502
+ self.layers = None
503
+ self.end_dev = None
504
+ self.capacity = None
505
+
506
+ def describe(self) -> str:
507
+ self._require_built()
508
+ return (
509
+ f"SummaryKVCache(L={self.num_layers} B={self.batch} H={self.num_heads} D={self.head_dim} "
510
+ f"Tf={self.frame_tokens} Z={self.z0_tokens} X={self.summary_tokens} Y={self.raw_window_frames} "
511
+ f"W={self.summary_window_frames} REC={self.record_tokens} cap={self.capacity} "
512
+ f"| Z0 0:{self.raw_region_start} RAW {self.raw_region_start}:{self.sum_region_start} "
513
+ f"({self.n_raw_slots}x{self.record_tokens}) SUM {self.sum_region_start}: "
514
+ f"({self.n_sum_slots}x{self.summary_tokens}) | cursor_r={self.cursor_r} filled_r={self.filled_r} "
515
+ f"cursor_s={self.cursor_s} filled_s={self.filled_s} n_raw_live={self.n_raw_live()} "
516
+ f"end={self.end_body()} open={self._body_open} z0_written={self.z0_written})"
517
+ )
inference_common.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small pieces shared by the streaming session and the server.
2
+
3
+ StageSampling / resolve_sampling which timesteps a body frame is denoised at
4
+ wrapper_ctor_kwargs_from_ckpt_config checkpoint config -> model constructor arguments
5
+ cond_dict, frame_tokens conditioning dict, tokens per frame
6
+ warm_z0_clean the clean write of the seed frame into memory
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+
12
+ import torch
13
+
14
+ from gta_streaming_kv_cache import SummaryKVCache
15
+ from noise_schedule import SampleGrid, sample_grid
16
+
17
+
18
+ # --------------------------------------------------------------------------------------
19
+ # Sampling plan
20
+ # --------------------------------------------------------------------------------------
21
+ @dataclass(frozen=True)
22
+ class StageSampling:
23
+ """Where a body frame is denoised: a grid of timesteps and the order of model calls on it.
24
+
25
+ Between two calls the current estimate of the clean frame is re-noised with FRESH noise to the next
26
+ timestep (``summary_streaming_inference.renoise_body_x0``).
27
+ """
28
+
29
+ grid: SampleGrid
30
+ # Grid indices the model is called at, in order, high -> low t, repeats allowed (a repeat re-noises the estimate
31
+ # back to the same t and denoises again). None = every grid index once. Index 0 (t = 0) is never a call.
32
+ step_plan: tuple[int, ...] | None = None
33
+
34
+ def __post_init__(self):
35
+ n = len(self.grid)
36
+ if n < 2:
37
+ raise ValueError(f"sampling grid too short: {self.grid.timesteps}")
38
+ if self.step_plan is not None:
39
+ plan = tuple(int(i) for i in self.step_plan)
40
+ if not plan or any(i < 1 or i >= n for i in plan):
41
+ raise ValueError(f"step_plan must be non-empty grid indices in 1..{n - 1}; got {plan}")
42
+ if any(plan[k] < plan[k + 1] for k in range(len(plan) - 1)):
43
+ raise ValueError(f"step_plan must be non-increasing (high -> low t); got {plan}")
44
+
45
+ @property
46
+ def indices(self) -> list[int]:
47
+ """Grid indices of the model calls, in order."""
48
+ if self.step_plan is not None:
49
+ return [int(i) for i in self.step_plan]
50
+ return list(range(len(self.grid) - 1, 0, -1))
51
+
52
+ @property
53
+ def timesteps(self) -> list[int]:
54
+ """The timesteps (0..999) of those calls, e.g. ``[999, 878, 669]``."""
55
+ return [int(self.grid.timesteps[i]) for i in self.indices]
56
+
57
+ @property
58
+ def label(self) -> str:
59
+ ts = self.timesteps
60
+ return f"{len(ts)} [{','.join(str(t) for t in ts)}]" if len(ts) <= 6 else f"{len(ts)}"
61
+
62
+
63
+ def resolve_sampling(config: dict, *, steps: int | None = None, tag: str = "sampling") -> StageSampling:
64
+ """The sampling plan a checkpoint config asks for.
65
+
66
+ ``steps`` (default: the config's own ``len(timesteps)``) is the number of model calls per frame. The grid is
67
+ rebuilt from the config's schedule (``shifted_cosine_ratio``) and ``timestep_shift``; the caller checks it against
68
+ the config's ``timesteps`` list.
69
+ """
70
+ if not isinstance(config, dict):
71
+ raise TypeError(f"ckpt config must be a dict; got {type(config)}")
72
+ if str(config["noise_schedule"]) != "shifted_cosine":
73
+ raise ValueError(f"noise_schedule must be 'shifted_cosine'; got {config['noise_schedule']!r}")
74
+ n = len(config["timesteps"]) if steps is None else int(steps)
75
+ grid = sample_grid(steps=n, shift=float(config["timestep_shift"]), ratio=float(config["shifted_cosine_ratio"]))
76
+ samp = StageSampling(grid=grid)
77
+ print(f"[{tag}] steps={n} shift={float(config['timestep_shift']):g} t=[{','.join(str(t) for t in samp.timesteps)}]")
78
+ return samp
79
+
80
+
81
+ # --------------------------------------------------------------------------------------
82
+ # Checkpoint config -> model
83
+ # --------------------------------------------------------------------------------------
84
+ _ARCH_KEYS = ("dim", "ffn_dim", "num_heads", "num_layers", "summary_tokens", "raw_window_frames", "summary_window_frames")
85
+
86
+
87
+ def num_layers_from_ckpt_config(cfg: dict) -> int:
88
+ """Number of trunk blocks."""
89
+ n = int(cfg["num_layers"])
90
+ if n < 1:
91
+ raise ValueError(f"num_layers must be >= 1; got {n}")
92
+ return n
93
+
94
+
95
+ def wrapper_ctor_kwargs_from_ckpt_config(cfg: dict) -> dict:
96
+ """``SummaryformerWrapper`` kwargs from a checkpoint config.
97
+
98
+ Memory geometry is X / Y / W: ``summary_tokens`` / ``raw_window_frames`` / ``summary_window_frames``.
99
+ """
100
+ if not isinstance(cfg, dict):
101
+ raise TypeError(f"ckpt config must be a dict; got {type(cfg)}")
102
+ missing = [k for k in _ARCH_KEYS if k not in cfg]
103
+ if missing:
104
+ raise KeyError(f"ckpt config missing {missing}.")
105
+ return dict(
106
+ dim=int(cfg["dim"]),
107
+ ffn_dim=int(cfg["ffn_dim"]),
108
+ num_heads=int(cfg["num_heads"]),
109
+ num_layers=num_layers_from_ckpt_config(cfg),
110
+ summary_tokens=int(cfg["summary_tokens"]),
111
+ raw_window_frames=int(cfg["raw_window_frames"]),
112
+ summary_window_frames=int(cfg["summary_window_frames"]),
113
+ )
114
+
115
+
116
+ # --------------------------------------------------------------------------------------
117
+ # Geometry / conditioning
118
+ # --------------------------------------------------------------------------------------
119
+ def frame_tokens(model, h: int, w: int) -> int:
120
+ """Tokens of one frame on an ``h x w`` latent grid: one token per latent cell."""
121
+ return int(h) * int(w)
122
+
123
+
124
+ def cond_dict(*, fps=None, action_context=None, z0_focus_region=None) -> dict:
125
+ """``z0_focus_region`` is a seed-frame knob (Bool [B,H,W])."""
126
+ out = {
127
+ "fps": fps,
128
+ "action_context": action_context,
129
+ }
130
+ if z0_focus_region is not None:
131
+ out["z0_focus_region"] = z0_focus_region
132
+ return out
133
+
134
+
135
+ @torch.no_grad()
136
+ def warm_z0_clean(wrapper, kv: SummaryKVCache, cond_pos: dict, xhat0: torch.Tensor) -> None:
137
+ """Write the clean seed frame's record into the Z0 slot (one pass at t = 0), then ``kv.note_z0_written()``.
138
+
139
+ ``xhat0 [B, 1, C, H, W]``. No ``begin_frame`` and no cursor commit: the seed frame is the sink, not a RAW slot.
140
+ """
141
+ if not (isinstance(xhat0, torch.Tensor) and xhat0.dim() == 5 and int(xhat0.size(1)) == 1):
142
+ raise TypeError(f"xhat0 must be Tensor[B,1,C,H,W]; got {getattr(xhat0, 'shape', type(xhat0))}")
143
+ t0 = torch.zeros((int(xhat0.size(0)),), device=xhat0.device, dtype=torch.float32)
144
+ wrapper.forward_z0(x_z0=xhat0, conditional_dict=cond_pos, t_z0=t0, kv_cache=kv)
145
+ kv.note_z0_written()
latent_stats_z0.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d54229638c573c539af10abb10cfc8c8b189f35e3d3939b2753fe6b383a4b56d
3
+ size 2793
latent_stats_z_rest.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0cfcdc29cc8cbb8fab0eff2009370aadf58d3a289a2120fc1185fd9ec8689702
3
+ size 2829
noise_schedule.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The noise schedule, and the few timesteps a frame is denoised at.
2
+
3
+ x_t = signal(t) * x0 + noise(t) * eps signal(t)^2 + noise(t)^2 = 1 t = 0 .. 999
4
+
5
+ ``alpha_bar(t) = signal(t)^2`` is a cosine schedule (Nichol & Dhariwal, 2021) with a constant log-SNR shift
6
+ (Hoogeboom et al., 2023): ``SNR(u) = ratio^2 * SNR_cosine(u)``. That curve, sampled at 1000 timesteps, is all of the
7
+ diffusion process that inference needs. There is no posterior, no variance and no loss in this file.
8
+
9
+ The model is called at K of those timesteps per frame. They are not evenly spaced: start from K + 1 evenly spaced
10
+ timesteps (0 and 999 included), move each one toward noise by ``2 ln(shift)`` in log-SNR, and snap it to the nearest
11
+ timestep of the 1000. ``shift = 1`` leaves the even spacing. The lowest point, t = 0, is the clean end and is never a
12
+ model call.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import math
17
+ from dataclasses import dataclass
18
+
19
+ import numpy as np
20
+
21
+ TRAIN_TIMESTEPS = 1000
22
+ # The largest single-step noise increase the discretized curve may take (keeps the last steps finite).
23
+ _MAX_STEP_NOISE = 0.999
24
+ _COSINE_OFFSET = 0.008
25
+
26
+
27
+ def _cosine_alpha_bar(u: float) -> float:
28
+ return math.cos((u + _COSINE_OFFSET) / (1.0 + _COSINE_OFFSET) * math.pi / 2) ** 2
29
+
30
+
31
+ def _shifted_alpha_bar(u: float, ratio: float) -> float:
32
+ """The cosine curve at ``u`` in [0, 1] with its SNR multiplied by ``ratio^2``."""
33
+ base = min(max(_cosine_alpha_bar(u), 1e-12), 1.0 - 1e-12)
34
+ snr = base / (1.0 - base) * (ratio ** 2)
35
+ return snr / (1.0 + snr)
36
+
37
+
38
+ def alpha_bar_table(ratio: float, steps: int = TRAIN_TIMESTEPS) -> np.ndarray:
39
+ """``alpha_bar`` at timesteps ``0 .. steps - 1`` (float64), the product of per-step factors read off the curve."""
40
+ ratio = max(1e-12, float(ratio))
41
+ curve = [_shifted_alpha_bar(i / steps, ratio) for i in range(steps + 1)]
42
+ step_noise = np.array([min(1.0 - curve[i + 1] / curve[i], _MAX_STEP_NOISE) for i in range(steps)], dtype=np.float64)
43
+ return np.cumprod(1.0 - step_noise)
44
+
45
+
46
+ def even_timesteps(points: int, steps: int = TRAIN_TIMESTEPS) -> list[int]:
47
+ """``points`` timesteps evenly spaced over ``0 .. steps - 1``, both ends included."""
48
+ points = int(points)
49
+ if points < 2:
50
+ raise ValueError(f"need at least 2 points (the clean end and the noise end); got {points}")
51
+ stride = (steps - 1) / (points - 1)
52
+ ts = [int(round(i * stride)) for i in range(points)]
53
+ ts[0], ts[-1] = 0, steps - 1
54
+ if len(set(ts)) != points:
55
+ raise ValueError(f"{points} points do not fit on {steps} timesteps")
56
+ return ts
57
+
58
+
59
+ def shifted_timesteps(alpha_bar: np.ndarray, points: int, shift: float) -> list[int]:
60
+ """``points`` timesteps whose log-SNR is that of the even spacing moved toward noise by ``2 ln(shift)``.
61
+
62
+ Only WHICH timesteps are visited changes; the schedule itself is untouched. Ends stay at 0 and the last timestep.
63
+ """
64
+ shift = float(shift)
65
+ if shift <= 0:
66
+ raise ValueError(f"shift must be > 0; got {shift}")
67
+ steps = int(len(alpha_bar))
68
+ even = even_timesteps(points, steps)
69
+ if abs(shift - 1.0) < 1e-12:
70
+ return even
71
+ ab = np.clip(np.asarray(alpha_bar, dtype=np.float64), 1e-300, 1.0 - 1e-16)
72
+ log_snr = np.log(ab) - np.log1p(-ab) # falls as t rises
73
+ wanted = log_snr[np.asarray(even)] - 2.0 * math.log(shift)
74
+ picked = [int(np.argmin(np.abs(log_snr - w))) for w in wanted]
75
+ picked[0], picked[-1] = 0, steps - 1
76
+ # Two points may snap to the same timestep where the curve is nearly flat; move the later one up by one.
77
+ taken: set[int] = set()
78
+ for t in picked:
79
+ while t in taken and t < steps - 1:
80
+ t += 1
81
+ taken.add(t)
82
+ if len(taken) != int(points):
83
+ raise RuntimeError(f"could not place {points} distinct timesteps at shift={shift} (got {sorted(taken)})")
84
+ return sorted(taken)
85
+
86
+
87
+ @dataclass(frozen=True)
88
+ class SampleGrid:
89
+ """The timesteps one frame may be denoised at, ascending, with the signal and noise scale at each.
90
+
91
+ Index 0 is t = 0 (the clean end, never a model call); the last index is the noise end.
92
+ """
93
+
94
+ timesteps: tuple[int, ...]
95
+ signal: np.ndarray # sqrt(alpha_bar(t)), float64, one per timestep
96
+ noise: np.ndarray # sqrt(1 - alpha_bar(t))
97
+
98
+ def __len__(self) -> int:
99
+ return len(self.timesteps)
100
+
101
+
102
+ def sample_grid(*, steps: int, shift: float, ratio: float) -> SampleGrid:
103
+ """The grid for ``steps`` model calls per frame: ``steps + 1`` timesteps (the extra one is t = 0)."""
104
+ steps = int(steps)
105
+ if steps < 1:
106
+ raise ValueError(f"steps must be >= 1; got {steps}")
107
+ alpha_bar = alpha_bar_table(ratio)
108
+ ts = shifted_timesteps(alpha_bar, steps + 1, shift)
109
+ at = alpha_bar[np.asarray(ts)]
110
+ return SampleGrid(timesteps=tuple(int(t) for t in ts), signal=np.sqrt(at), noise=np.sqrt(1.0 - at))
sae.py ADDED
@@ -0,0 +1,709 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """sae.py -- the autoencoder.
2
+
3
+ encoder: RGB -> (z0, z_rest)
4
+ decoder: (z0, z_rest) -> RGB
5
+
6
+ Two latents on the same /16 grid, 48 channels each, every token on the RMS-1 sphere:
7
+
8
+ z0 : [B, 48, 1, H/16, W/16] the first frame, by itself (an image)
9
+ z_rest : [B, 48, k, H/16, W/16] the video body, one latent frame per 4 RGB frames
10
+
11
+ A clip is 1 + 4k RGB frames. Frame 0 never mixes with anything in time, so a single image is a legal clip
12
+ and the seed of a stream.
13
+
14
+ Both sides are built from one schedule format, coarse -> fine:
15
+
16
+ (scale_vs_RGB, kind, n_res, channels)
17
+ kind = "2d" | "3d" | "st"
18
+ 2d -- per-frame residual blocks; spatial hop attached to this scale
19
+ 3d -- causal residual blocks; spatial hop attached to this scale
20
+ st -- causal residual blocks; 2x in space and 2x in time
21
+
22
+ The encoder walks it fine -> coarse (RGB in, latent out), the decoder coarse -> fine. The decoder does both
23
+ time doublings first, at /16, and then only spatial hops.
24
+
25
+ Every temporal op is causal, so there are two ways to run each side and they give the same result.
26
+
27
+ Parallel, the whole clip in one call:
28
+
29
+ encode_parallel(1 + 4k RGB frames) -> (z0, z_rest with k frames)
30
+ decode_parallel(z0, z_rest) -> 1 + 4k RGB frames
31
+
32
+ Autoregressive, one chunk per call, each call taking the cache the previous one returned:
33
+
34
+ encode_bootstrap(1 RGB frame) -> (z0, cache)
35
+ encode_steady(4 RGB frames, cache) -> (1 z_rest frame, cache)
36
+ decode_bootstrap(z0) -> (1 RGB frame, cache)
37
+ decode_steady(1 z_rest frame, cache) -> (4 RGB frames, cache)
38
+
39
+ The cache is a list over the causal blocks, each entry the tail tensors that block needs from the past.
40
+ The server uses the autoregressive calls: encode_bootstrap for the start image, decode_* for every frame.
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ from dataclasses import dataclass
46
+
47
+ import torch
48
+ import torch.nn as nn
49
+ import torch.nn.functional as F
50
+
51
+
52
+ # Every temporal conv has kernel 3, so one output frame reads the 2 frames before it.
53
+ TAIL_FRAMES = 2
54
+
55
+ Cache = list # list[list[torch.Tensor | None]]
56
+
57
+
58
+ def _causal_kind(kind: str) -> bool:
59
+ return kind in ("3d", "st")
60
+
61
+
62
+ def _st_kind(kind: str) -> bool:
63
+ return kind == "st"
64
+
65
+
66
+ def _tail(x: torch.Tensor, frames: int) -> torch.Tensor:
67
+ """The last ``frames`` frames as their own channels-last tensor.
68
+
69
+ A slice keeps the strides of the tensor it was cut from. These tails cross torch.compile calls, so the
70
+ layout has to be the same every time. clone() rather than contiguous(): it also fixes the strides when a
71
+ size-1 dimension makes PyTorch call a view contiguous.
72
+ """
73
+ return x[:, :, -frames:].clone(memory_format=torch.channels_last_3d)
74
+
75
+
76
+ def _cl3d(x: torch.Tensor) -> torch.Tensor:
77
+ """Conv3d activations as NDHWC."""
78
+ return x.contiguous(memory_format=torch.channels_last_3d)
79
+
80
+
81
+ # ---------------------------------------------------------------------------
82
+ # config
83
+ # ---------------------------------------------------------------------------
84
+ @dataclass
85
+ class SAEConfig:
86
+ patch: int = 16
87
+ out_dims_z0: int = 48
88
+ out_dims_z_rest: int = 48
89
+ rgb_stages_encoder: tuple[tuple[int, str, int, int], ...] = (
90
+ (16, "st", 5, 512),
91
+ (8, "st", 2, 384),
92
+ (4, "3d", 2, 192),
93
+ (2, "2d", 2, 96),
94
+ )
95
+ rgb_stages_decoder: tuple[tuple[int, str, int, int], ...] = (
96
+ (16, "st", 6, 512),
97
+ (8, "st", 2, 384),
98
+ (4, "3d", 2, 192),
99
+ (2, "2d", 2, 96),
100
+ )
101
+
102
+ @property
103
+ def width(self) -> int:
104
+ """Channel width at the latent grid."""
105
+ return int(self.rgb_stages_encoder[0][3])
106
+
107
+ @property
108
+ def t_compress(self) -> int:
109
+ """RGB frames per z_rest frame: 2 per "st" stage."""
110
+ return 2 ** sum(1 for s in self.rgb_stages_encoder if _st_kind(s[1]))
111
+
112
+
113
+ def _frame_groups(n_frames: int, group: int) -> list[slice]:
114
+ """The clip layout as slices: frame 0 by itself, then groups of ``group`` frames. The parallel calls run
115
+ their per-frame parts on these groups, the same batches the autoregressive calls see."""
116
+ return [slice(0, 1)] + [slice(i, i + group) for i in range(1, n_frames, group)]
117
+
118
+
119
+ # ---------------------------------------------------------------------------
120
+ # norms
121
+ # ---------------------------------------------------------------------------
122
+ class RMSNorm3d(nn.Module):
123
+ """Channel-only RMS norm on [B, C, T, H, W]. Nothing is reduced over time or space, so a streamed chunk
124
+ is normalized exactly like the whole clip."""
125
+
126
+ def __init__(self, dim: int, eps: float = 1e-4):
127
+ super().__init__()
128
+ self.eps = eps
129
+ self.gamma = nn.Parameter(torch.ones(1, dim, 1, 1, 1))
130
+
131
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
132
+ return x * torch.rsqrt(x.pow(2).mean(1, keepdim=True) + self.eps) * self.gamma
133
+
134
+
135
+ class RMSNorm2d(nn.Module):
136
+ """The same norm on [N, C, H, W]."""
137
+
138
+ def __init__(self, dim: int, eps: float = 1e-4):
139
+ super().__init__()
140
+ self.eps = eps
141
+ self.gamma = nn.Parameter(torch.ones(1, dim, 1, 1))
142
+
143
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
144
+ return x * torch.rsqrt(x.pow(2).mean(1, keepdim=True) + self.eps) * self.gamma
145
+
146
+
147
+ class SphereNorm3d(nn.Module):
148
+ """Put every token's channel vector at RMS 1. No parameters."""
149
+
150
+ def __init__(self, eps: float = 1e-6):
151
+ super().__init__()
152
+ self.eps = eps
153
+
154
+ def forward(self, z: torch.Tensor) -> torch.Tensor:
155
+ rms = z.float().pow(2).mean(dim=1, keepdim=True).add(self.eps).sqrt()
156
+ return z / rms.to(z.dtype)
157
+
158
+
159
+ # ---------------------------------------------------------------------------
160
+ # causal conv
161
+ # ---------------------------------------------------------------------------
162
+ class CausalConv3d(nn.Conv3d):
163
+ """Conv3d that never reads a future frame: all of the temporal padding goes on the past side.
164
+
165
+ Streaming: the frames the kernel needs from before this chunk come in as ``tail`` (what the previous call
166
+ returned). With no tail the past is zeros, which is the start of a clip. Carrying a short tail of past
167
+ frames through a causal conv is the streaming scheme of the Wan2.1 VAE (Apache-2.0).
168
+ """
169
+
170
+ def __init__(self, *args, **kwargs):
171
+ super().__init__(*args, **kwargs)
172
+ kt = self.kernel_size[0]
173
+ pt, ph, pw = self.padding
174
+ assert 2 * pt == kt - 1, f"needs 'same' temporal padding, got kernel {kt} pad {pt}"
175
+ self.past = kt - 1 # frames of history one output frame reads
176
+ self._space_pad = (pw, pw, ph, ph)
177
+ self.padding = (0, 0, 0)
178
+
179
+ def _conv(self, x: torch.Tensor, tail: torch.Tensor | None):
180
+ seen = x if tail is None else torch.cat([tail, x], dim=2)
181
+ missing = self.past - (0 if tail is None else tail.shape[2])
182
+ y = super().forward(_cl3d(F.pad(seen, (*self._space_pad, missing, 0))))
183
+ return _cl3d(y), seen
184
+
185
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
186
+ return self._conv(x, None)[0]
187
+
188
+ def stream(self, x: torch.Tensor, tail: torch.Tensor | None):
189
+ """-> (y, the tail the next call needs)."""
190
+ y, seen = self._conv(x, tail)
191
+ return y, _tail(seen, TAIL_FRAMES)
192
+
193
+
194
+ # ---------------------------------------------------------------------------
195
+ # time and space hops
196
+ # ---------------------------------------------------------------------------
197
+ def _match_channels(x: torch.Tensor, cout: int) -> torch.Tensor:
198
+ """Channel adapter with no parameters, for the bypass around a hop: tile channels to widen, mean
199
+ channel groups to narrow, tile-and-crop / crop when the widths do not divide."""
200
+ c = x.shape[1]
201
+ if cout == c:
202
+ return x
203
+ if cout % c == 0:
204
+ return x.repeat_interleave(cout // c, dim=1)
205
+ if c % cout == 0:
206
+ b, _, t, h, w = x.shape
207
+ return x.reshape(b, cout, c // cout, t, h, w).mean(2)
208
+ if cout > c:
209
+ reps = (cout + c - 1) // c
210
+ return x.repeat_interleave(reps, dim=1)[:, :cout]
211
+ return x[:, :cout]
212
+
213
+
214
+ class TemporalDown(nn.Module):
215
+ """2x in time: every pair of new frames becomes one. The conv output is summed with the plain mean of
216
+ the pair. The first frame of a stream skips this (bootstrap): it passes through and becomes the carry."""
217
+
218
+ def __init__(self, c: int):
219
+ super().__init__()
220
+ self.conv = nn.Conv3d(c, c, (3, 1, 1), stride=(2, 1, 1)) # no padding: the carry is the past
221
+
222
+ @staticmethod
223
+ def _pair_mean(frames: torch.Tensor) -> torch.Tensor:
224
+ return F.avg_pool3d(frames, kernel_size=(2, 1, 1), stride=(2, 1, 1))
225
+
226
+ def forward(self, x: torch.Tensor) -> torch.Tensor: # parallel: [.., 1 + 2k, ..] -> [.., 1 + k, ..]
227
+ if x.shape[2] < 3:
228
+ return x[:, :, :1]
229
+ return _cl3d(torch.cat([x[:, :, :1], self.conv(_cl3d(x)) + self._pair_mean(x[:, :, 1:])], dim=2))
230
+
231
+ def bootstrap(self, x: torch.Tensor):
232
+ return x, _tail(x, 1)
233
+
234
+ def steady(self, x: torch.Tensor, carry: torch.Tensor):
235
+ inp = _cl3d(torch.cat([carry, x], dim=2)) # x = an even number of new frames
236
+ y = _cl3d(self.conv(inp) + self._pair_mean(x))
237
+ return y, _tail(inp, 1)
238
+
239
+
240
+ class Downsample3D(nn.Module):
241
+ """2x in space, then 2x in time. Each step is a conv summed with a pooling bypass (block mean in space,
242
+ pair mean in time). The two steps are separate so the first frame can skip the temporal one."""
243
+
244
+ def __init__(self, cin: int, cout: int):
245
+ super().__init__()
246
+ self.cout = cout
247
+ self.spatial = CausalConv3d(cin, cout, kernel_size=(1, 3, 3), stride=(1, 2, 2), padding=(0, 1, 1))
248
+ self.tdown = TemporalDown(cout)
249
+
250
+ def _spatial(self, x: torch.Tensor) -> torch.Tensor:
251
+ s = F.avg_pool3d(x, kernel_size=(1, 2, 2), stride=(1, 2, 2))
252
+ return _cl3d(self.spatial(x) + _match_channels(s, self.cout))
253
+
254
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
255
+ return self.tdown(self._spatial(x))
256
+
257
+ def bootstrap(self, x: torch.Tensor) -> tuple[torch.Tensor, list]:
258
+ y, carry = self.tdown.bootstrap(self._spatial(x))
259
+ return y, [carry]
260
+
261
+ def steady(self, x: torch.Tensor, cache: list) -> tuple[torch.Tensor, list]:
262
+ y, carry = self.tdown.steady(self._spatial(x), cache[0])
263
+ return y, [carry]
264
+
265
+
266
+ class TemporalUp(nn.Module):
267
+ """2x in time: the conv emits two channel groups per frame, which become two consecutive frames, summed
268
+ with the input frame repeated twice. Output frames 2t and 2t+1 read input frames <= t only. The first
269
+ frame of a stream skips this (bootstrap), so one latent image stays one frame."""
270
+
271
+ def __init__(self, c: int):
272
+ super().__init__()
273
+ self.conv = CausalConv3d(c, c * 2, kernel_size=(3, 1, 1), padding=(1, 0, 0))
274
+
275
+ @staticmethod
276
+ def _interleave(y: torch.Tensor) -> torch.Tensor:
277
+ """[b, 2c, t, h, w] -> [b, c, 2t, h, w]."""
278
+ b, c2, t, h, w = y.shape
279
+ c = c2 // 2
280
+ y = y.reshape(b, 2, c, t, h, w)
281
+ y = torch.stack((y[:, 0], y[:, 1]), dim=3)
282
+ return _cl3d(y.reshape(b, c, t * 2, h, w))
283
+
284
+ def forward(self, x: torch.Tensor) -> torch.Tensor: # parallel: [.., 1 + k, ..] -> [.., 1 + 2k, ..]
285
+ if x.shape[2] < 2:
286
+ return x
287
+ body = x[:, :, 1:]
288
+ rest = self._interleave(self.conv(body)) + body.repeat_interleave(2, dim=2)
289
+ return _cl3d(torch.cat([x[:, :, :1], rest], dim=2))
290
+
291
+ def bootstrap(self, x: torch.Tensor):
292
+ return x, None
293
+
294
+ def steady(self, x: torch.Tensor, tail):
295
+ y, tail = self.conv.stream(x, tail)
296
+ return _cl3d(self._interleave(y) + x.repeat_interleave(2, dim=2)), tail
297
+
298
+
299
+ class UpsampleTime(nn.Module):
300
+ """TemporalUp, then a per-frame 3x3 conv summed with its input. No change in space."""
301
+
302
+ def __init__(self, c: int):
303
+ super().__init__()
304
+ self.tup = TemporalUp(c)
305
+ self.up = CausalConv3d(c, c, kernel_size=(1, 3, 3), padding=(0, 1, 1))
306
+
307
+ def _up(self, x: torch.Tensor) -> torch.Tensor:
308
+ return _cl3d(self.up(x) + x)
309
+
310
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
311
+ return self._up(self.tup(x))
312
+
313
+ def bootstrap(self, x: torch.Tensor) -> tuple[torch.Tensor, list]:
314
+ x, tail = self.tup.bootstrap(x)
315
+ return self._up(x), [tail]
316
+
317
+ def steady(self, x: torch.Tensor, cache: list) -> tuple[torch.Tensor, list]:
318
+ x, tail = self.tup.steady(x, cache[0])
319
+ return self._up(x), [tail]
320
+
321
+
322
+ class As5D(nn.Module):
323
+ """Run a per-frame 2-D module on [B, C, T, H, W] by folding T into the batch."""
324
+
325
+ def __init__(self, mod: nn.Module):
326
+ super().__init__()
327
+ self.mod = mod
328
+
329
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
330
+ B, C, T, h, w = x.shape
331
+ y = self.mod(x.permute(0, 2, 1, 3, 4).reshape(B * T, C, h, w).contiguous(memory_format=torch.channels_last))
332
+ _, Cout, H, W = y.shape
333
+ return y.reshape(B, T, Cout, H, W).permute(0, 2, 1, 3, 4).contiguous(memory_format=torch.channels_last_3d)
334
+
335
+
336
+ class PixelShuffleUp(nn.Module):
337
+ """Decoder spatial hop: conv at the low resolution -> PixelShuffle(r) -> SiLU."""
338
+
339
+ def __init__(self, cin: int, cout: int, r: int):
340
+ super().__init__()
341
+ self.r = r
342
+ self.conv = nn.Conv2d(cin, cout * r * r, 3, padding=1)
343
+ self.shuffle = nn.PixelShuffle(r)
344
+ self.act = nn.SiLU()
345
+
346
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
347
+ return self.act(self.shuffle(self.conv(x)))
348
+
349
+
350
+ class PixelUnshuffleDown(nn.Module):
351
+ """Encoder spatial hop: PixelUnshuffle(r) -> conv -> SiLU."""
352
+
353
+ def __init__(self, cin: int, cout: int, r: int):
354
+ super().__init__()
355
+ self.r = r
356
+ self.unshuffle = nn.PixelUnshuffle(r)
357
+ self.conv = nn.Conv2d(cin * r * r, cout, 3, padding=1)
358
+ self.act = nn.SiLU()
359
+
360
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
361
+ return self.act(self.conv(self.unshuffle(x)))
362
+
363
+
364
+ class SubPixelToRGB(nn.Module):
365
+ """Last decoder hop: conv -> PixelShuffle(r) -> RGB at full resolution. No activation."""
366
+
367
+ def __init__(self, cin: int, r: int):
368
+ super().__init__()
369
+ self.r = r
370
+ self.conv = nn.Conv2d(cin, 3 * r * r, kernel_size=3, padding=1)
371
+ self.shuffle = nn.PixelShuffle(r)
372
+
373
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
374
+ return self.shuffle(self.conv(x))
375
+
376
+
377
+ class SubPixelFromRGB(nn.Module):
378
+ """First encoder hop: RGB at full resolution -> PixelUnshuffle(r) -> conv. No activation."""
379
+
380
+ def __init__(self, cout: int, r: int):
381
+ super().__init__()
382
+ self.r = r
383
+ self.unshuffle = nn.PixelUnshuffle(r)
384
+ self.conv = nn.Conv2d(3 * r * r, cout, kernel_size=3, padding=1)
385
+
386
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
387
+ return self.conv(self.unshuffle(x))
388
+
389
+
390
+ # ---------------------------------------------------------------------------
391
+ # residual blocks
392
+ # ---------------------------------------------------------------------------
393
+ class ResBlock(nn.Module):
394
+ """Pre-norm causal 3x3x3 residual block. Cache = the tails of its two convs."""
395
+
396
+ def __init__(self, c: int):
397
+ super().__init__()
398
+ self.norm1 = RMSNorm3d(c)
399
+ self.conv1 = CausalConv3d(c, c, kernel_size=3, padding=1)
400
+ self.norm2 = RMSNorm3d(c)
401
+ self.conv2 = CausalConv3d(c, c, kernel_size=3, padding=1)
402
+ self.act = nn.GELU()
403
+
404
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
405
+ h = self.conv1(self.act(self.norm1(x)))
406
+ h = self.conv2(self.act(self.norm2(h)))
407
+ return _cl3d(x + h)
408
+
409
+ def steady(self, x: torch.Tensor, cache: list) -> tuple[torch.Tensor, list]:
410
+ h, tail1 = self.conv1.stream(self.act(self.norm1(x)), cache[0])
411
+ h, tail2 = self.conv2.stream(self.act(self.norm2(h)), cache[1])
412
+ return _cl3d(x + h), [tail1, tail2]
413
+
414
+ def bootstrap(self, x: torch.Tensor) -> tuple[torch.Tensor, list]:
415
+ return self.steady(x, [None, None])
416
+
417
+
418
+ class ResBlock2D(nn.Module):
419
+ """Pre-norm per-frame 3x3 residual block. No state."""
420
+
421
+ def __init__(self, c: int):
422
+ super().__init__()
423
+ self.norm1 = RMSNorm2d(c)
424
+ self.conv1 = nn.Conv2d(c, c, kernel_size=3, padding=1)
425
+ self.norm2 = RMSNorm2d(c)
426
+ self.conv2 = nn.Conv2d(c, c, kernel_size=3, padding=1)
427
+ self.act = nn.GELU()
428
+
429
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
430
+ h = self.conv1(self.act(self.norm1(x)))
431
+ h = self.conv2(self.act(self.norm2(h)))
432
+ return x + h
433
+
434
+
435
+ # ---------------------------------------------------------------------------
436
+ # the pixel path between RGB and the latent grid
437
+ # ---------------------------------------------------------------------------
438
+ class RgbStages(nn.Module):
439
+ """One schedule, built as the encoder (RGB -> latent grid) or as the decoder (latent grid -> RGB).
440
+
441
+ blocks_3d: the causal part (residual blocks and the hops that touch time); it carries the stream cache.
442
+ blocks_2d: the per-frame part; no state.
443
+ Encoder order: blocks_2d then blocks_3d. Decoder order: blocks_3d then blocks_2d.
444
+ """
445
+
446
+ def __init__(self, stages: tuple[tuple[int, str, int, int], ...], *, encode: bool):
447
+ super().__init__()
448
+ self.encode = encode
449
+ b3d: list[nn.Module] = []
450
+ b2d: list[nn.Module] = []
451
+
452
+ if encode:
453
+ # Open from RGB, walk fine -> coarse.
454
+ b2d.append(SubPixelFromRGB(stages[-1][3], stages[-1][0]))
455
+ for i in range(len(stages) - 1, -1, -1):
456
+ scale, kind, n_res, c = stages[i]
457
+ target = b3d if _causal_kind(kind) else b2d
458
+ for _ in range(n_res):
459
+ target.append(ResBlock(c) if _causal_kind(kind) else ResBlock2D(c))
460
+ if i == 0:
461
+ continue
462
+ nscale, nkind, _, nc = stages[i - 1]
463
+ if _st_kind(nkind):
464
+ b3d.append(Downsample3D(c, nc))
465
+ else:
466
+ down = PixelUnshuffleDown(c, nc, nscale // scale)
467
+ if _causal_kind(nkind) and _causal_kind(kind):
468
+ b3d.append(As5D(down))
469
+ else:
470
+ b2d.append(down)
471
+ else:
472
+ # Residual blocks at the latent grid, then every time doubling, then spatial hops only.
473
+ scale0, _kind0, n_res0, c0 = stages[0]
474
+ for _ in range(n_res0):
475
+ b3d.append(ResBlock(c0))
476
+ for _ in range(sum(1 for s in stages if _st_kind(s[1]))):
477
+ b3d.append(UpsampleTime(c0))
478
+ prev_scale, prev_ch = scale0, c0
479
+ for scale, kind, n_res, c in stages[1:]:
480
+ up = PixelShuffleUp(prev_ch, c, prev_scale // scale)
481
+ if _causal_kind(kind):
482
+ b3d.append(As5D(up))
483
+ else:
484
+ b2d.append(up)
485
+ target = b3d if _causal_kind(kind) else b2d
486
+ for _ in range(n_res):
487
+ target.append(ResBlock(c) if _causal_kind(kind) else ResBlock2D(c))
488
+ prev_scale, prev_ch = scale, c
489
+ b2d.append(SubPixelToRGB(prev_ch, prev_scale))
490
+
491
+ self.blocks_3d = nn.ModuleList(b3d)
492
+ self.blocks_2d = nn.ModuleList(b2d)
493
+
494
+ def forward_3d(self, x: torch.Tensor, group: int) -> torch.Tensor:
495
+ """Parallel: the causal part on a whole clip. Past frames come from the clip itself, zeros before it.
496
+ A per-frame hop (As5D) runs on the clip's frame groups."""
497
+ for blk in self.blocks_3d:
498
+ if isinstance(blk, As5D):
499
+ parts = [blk(x[:, :, g]) for g in _frame_groups(x.shape[2], group)]
500
+ x = parts[0] if len(parts) == 1 else _cl3d(torch.cat(parts, dim=2))
501
+ else:
502
+ x = blk(x)
503
+ return x
504
+
505
+ def stream_3d(self, x: torch.Tensor, cache: Cache | None, bootstrap: bool) -> tuple[torch.Tensor, Cache]:
506
+ """Autoregressive: the causal part on one chunk. ``bootstrap``: the first frame (no cache in)."""
507
+ new_cache: Cache = []
508
+ ci = 0
509
+ for blk in self.blocks_3d:
510
+ if isinstance(blk, (ResBlock, Downsample3D, UpsampleTime)):
511
+ if bootstrap:
512
+ x, c = blk.bootstrap(x)
513
+ else:
514
+ assert cache is not None
515
+ x, c = blk.steady(x, cache[ci])
516
+ ci += 1
517
+ new_cache.append(c)
518
+ else:
519
+ x = blk(x)
520
+ return x, new_cache
521
+
522
+ def encode_2d(self, video: torch.Tensor) -> torch.Tensor:
523
+ """RGB [B, T, 3, H, W] -> hidden [B, C, T, h, w], frame by frame."""
524
+ B, T, C, H, W = video.shape
525
+ x = video.reshape(B * T, C, H, W).contiguous(memory_format=torch.channels_last)
526
+ for blk in self.blocks_2d:
527
+ x = blk(x)
528
+ _, D, h, w = x.shape
529
+ return x.reshape(B, T, D, h, w).permute(0, 2, 1, 3, 4).contiguous(memory_format=torch.channels_last_3d)
530
+
531
+ def decode_2d(self, hidden: torch.Tensor) -> torch.Tensor:
532
+ """hidden [B, C, T, h, w] -> RGB [B, T, 3, H, W], frame by frame."""
533
+ B, C, T, h, w = hidden.shape
534
+ x = hidden.permute(0, 2, 1, 3, 4).reshape(B * T, C, h, w).contiguous(memory_format=torch.channels_last)
535
+ for blk in self.blocks_2d:
536
+ x = blk(x)
537
+ return x.reshape(B, T, 3, x.shape[-2], x.shape[-1])
538
+
539
+
540
+ # ---------------------------------------------------------------------------
541
+ # encoder
542
+ # ---------------------------------------------------------------------------
543
+ class BottleneckHead(nn.Module):
544
+ """1x1x1 linear read-out to the latent channels, then onto the sphere."""
545
+
546
+ def __init__(self, cin: int, out_dims: int):
547
+ super().__init__()
548
+ self.out_dims = out_dims
549
+ self.proj = nn.Conv3d(cin, out_dims, kernel_size=1)
550
+ self.sphere_norm = SphereNorm3d()
551
+
552
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
553
+ return self.sphere_norm(_cl3d(self.proj(_cl3d(x))))
554
+
555
+
556
+ class ShakeAE(nn.Module):
557
+ """The encoder. RGB [B, T, 3, H, W] (H, W multiples of 16) -> z0 or z_rest.
558
+
559
+ One trunk, two read-outs: ``head_z0`` for the first frame, ``head_rest`` for the body.
560
+ """
561
+
562
+ def __init__(self, cfg: SAEConfig | None = None):
563
+ super().__init__()
564
+ self.cfg = cfg or SAEConfig()
565
+ self.rgb = RgbStages(self.cfg.rgb_stages_encoder, encode=True)
566
+ self.head_z0 = BottleneckHead(self.cfg.width, self.cfg.out_dims_z0)
567
+ self.head_rest = BottleneckHead(self.cfg.width, self.cfg.out_dims_z_rest)
568
+
569
+ @property
570
+ def t_compress(self) -> int:
571
+ """RGB frames per z_rest frame."""
572
+ return self.cfg.t_compress
573
+
574
+ # ---- parallel: the whole clip in one call ---------------------------------------------------
575
+ def encode_parallel(self, video: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
576
+ """RGB [B, 1 + 4k, 3, H, W] -> (z0 [B, C0, 1, h, w], z_rest [B, Cr, k, h, w]). k = 0 is one image.
577
+
578
+ Same weights and the same result as encode_bootstrap followed by k encode_steady calls.
579
+ """
580
+ t = self.t_compress
581
+ assert (video.shape[1] - 1) % t == 0, f"T={video.shape[1]} must be 1 + {t}k"
582
+ x = _cl3d(torch.cat([self.rgb.encode_2d(video[:, g]) for g in _frame_groups(video.shape[1], t)], dim=2))
583
+ x = self.rgb.forward_3d(x, t)
584
+ z0 = self.head_z0(x[:, :, :1])
585
+ if x.shape[2] > 1:
586
+ return z0, self.head_rest(x[:, :, 1:])
587
+ return z0, video.new_zeros(video.shape[0], self.cfg.out_dims_z_rest, 0, *z0.shape[-2:])
588
+
589
+ # ---- autoregressive: one chunk per call -----------------------------------------------------
590
+ def encode_bootstrap(self, video_chunk: torch.Tensor) -> tuple[torch.Tensor, Cache]:
591
+ """The first frame: 1 RGB frame -> z0 [B, C0, 1, h, w]."""
592
+ assert video_chunk.shape[1] == 1, f"bootstrap expects T=1, got T={video_chunk.shape[1]}"
593
+ x, cache = self.rgb.stream_3d(self.rgb.encode_2d(video_chunk), None, bootstrap=True)
594
+ return self.head_z0(x), cache
595
+
596
+ def encode_steady(self, video_chunk: torch.Tensor, cache: Cache) -> tuple[torch.Tensor, Cache]:
597
+ """A body chunk: 4 RGB frames -> 1 z_rest frame [B, Cr, 1, h, w]."""
598
+ assert video_chunk.shape[1] == self.t_compress, (
599
+ f"steady expects T={self.t_compress}, got T={video_chunk.shape[1]}")
600
+ x, cache = self.rgb.stream_3d(self.rgb.encode_2d(video_chunk), cache, bootstrap=False)
601
+ return self.head_rest(x), cache
602
+
603
+
604
+ # ---------------------------------------------------------------------------
605
+ # decoder
606
+ # ---------------------------------------------------------------------------
607
+ class Decoder(nn.Module):
608
+ """The decoder. z0 and z_rest enter the same trunk through their own 1x1x1 projection."""
609
+
610
+ def __init__(self, cfg: SAEConfig | None = None):
611
+ super().__init__()
612
+ self.cfg = cfg or SAEConfig()
613
+ self.proj_in_z0 = nn.Conv3d(self.cfg.out_dims_z0, self.cfg.width, kernel_size=1)
614
+ self.proj_in_rest = nn.Conv3d(self.cfg.out_dims_z_rest, self.cfg.width, kernel_size=1)
615
+ self.rgb = RgbStages(self.cfg.rgb_stages_decoder, encode=False)
616
+
617
+ @property
618
+ def t_compress(self) -> int:
619
+ """RGB frames per z_rest frame."""
620
+ return self.cfg.t_compress
621
+
622
+ # ---- parallel: the whole clip in one call ---------------------------------------------------
623
+ def decode_parallel(self, z0: torch.Tensor, z_rest: torch.Tensor) -> torch.Tensor:
624
+ """(z0 [B, C0, 1, h, w], z_rest [B, Cr, k, h, w]) -> RGB [B, 1 + 4k, 3, H, W]. k = 0 is one image.
625
+
626
+ Same weights and the same result as decode_bootstrap followed by k decode_steady calls.
627
+ """
628
+ assert z0.shape[2] == 1 and z0.shape[1] == self.cfg.out_dims_z0, tuple(z0.shape)
629
+ x = _cl3d(self.proj_in_z0(z0))
630
+ if z_rest.shape[2] > 0:
631
+ assert z_rest.shape[1] == self.cfg.out_dims_z_rest, tuple(z_rest.shape)
632
+ x = _cl3d(torch.cat([x, _cl3d(self.proj_in_rest(z_rest))], dim=2))
633
+ t = self.t_compress
634
+ x = self.rgb.forward_3d(x, t)
635
+ return torch.cat([self.rgb.decode_2d(x[:, :, g]) for g in _frame_groups(x.shape[2], t)], dim=1)
636
+
637
+ # ---- autoregressive: one chunk per call -----------------------------------------------------
638
+ def decode_bootstrap(self, z_chunk: torch.Tensor) -> tuple[torch.Tensor, Cache]:
639
+ """z0 [B, C0, 1, h, w] -> 1 RGB frame [B, 1, 3, H, W]."""
640
+ assert z_chunk.shape[2] == 1, f"bootstrap expects 1 latent frame, got T={z_chunk.shape[2]}"
641
+ assert z_chunk.shape[1] == self.cfg.out_dims_z0, (
642
+ f"z0 channels={z_chunk.shape[1]} != out_dims_z0={self.cfg.out_dims_z0}")
643
+ h, cache = self.rgb.stream_3d(_cl3d(self.proj_in_z0(z_chunk)), None, bootstrap=True)
644
+ return self.rgb.decode_2d(h), cache
645
+
646
+ def decode_steady(self, z_chunk: torch.Tensor, cache: Cache) -> tuple[torch.Tensor, Cache]:
647
+ """One z_rest frame [B, Cr, 1, h, w] -> 4 RGB frames [B, 4, 3, H, W]."""
648
+ assert z_chunk.shape[2] == 1, f"steady expects 1 latent frame, got T={z_chunk.shape[2]}"
649
+ assert z_chunk.shape[1] == self.cfg.out_dims_z_rest, (
650
+ f"z_rest channels={z_chunk.shape[1]} != out_dims_z_rest={self.cfg.out_dims_z_rest}")
651
+ h, cache = self.rgb.stream_3d(_cl3d(self.proj_in_rest(z_chunk)), cache, bootstrap=False)
652
+ return self.rgb.decode_2d(h), cache
653
+
654
+
655
+ # ---------------------------------------------------------------------------
656
+ # memory format
657
+ # ---------------------------------------------------------------------------
658
+ def _apply_channels_last(module: nn.Module) -> tuple[int, int]:
659
+ """Conv3d weights -> channels_last_3d, Conv2d weights -> channels_last. Returns the two counts."""
660
+ n3 = n2 = 0
661
+ for m in module.modules():
662
+ if isinstance(m, nn.Conv3d):
663
+ m.weight.data = m.weight.data.contiguous(memory_format=torch.channels_last_3d)
664
+ n3 += 1
665
+ elif isinstance(m, nn.Conv2d):
666
+ m.weight.data = m.weight.data.contiguous(memory_format=torch.channels_last)
667
+ n2 += 1
668
+ return n3, n2
669
+
670
+
671
+ def _assert_channels_last(module: nn.Module, *, tag: str) -> None:
672
+ bad: list[str] = []
673
+ for name, m in module.named_modules():
674
+ if isinstance(m, nn.Conv3d) and not m.weight.is_contiguous(memory_format=torch.channels_last_3d):
675
+ bad.append(f"{name} (Conv3d not channels_last_3d)")
676
+ elif isinstance(m, nn.Conv2d) and not m.weight.is_contiguous(memory_format=torch.channels_last):
677
+ bad.append(f"{name} (Conv2d not channels_last)")
678
+ assert not bad, f"[{tag}] conv weights not channels-last: {bad[:8]}"
679
+
680
+
681
+ # ---------------------------------------------------------------------------
682
+ # The space the model works in. The encoder's latent sits on the sphere; the model sees it standardized
683
+ # per channel. ``stats`` is a dict with 'mean' [C] and 'std' [C], or a (mean, std) pair. Both directions
684
+ # share _diag_stats_like, so they are exact inverses.
685
+ # ---------------------------------------------------------------------------
686
+ def _diag_stats_like(stats, z: torch.Tensor, *, eps: float = 1e-6):
687
+ """Per-channel (mean, std) shaped to broadcast against ``z`` along dim 1, on z's device and dtype."""
688
+ if isinstance(stats, dict):
689
+ mean, std = stats["mean"], stats["std"]
690
+ else:
691
+ mean, std = stats
692
+ mean = torch.as_tensor(mean, device=z.device, dtype=z.dtype)
693
+ std = torch.as_tensor(std, device=z.device, dtype=z.dtype).clamp_min(eps)
694
+ assert mean.numel() == z.shape[1] == std.numel(), (
695
+ f"stats channels (mean {mean.numel()}, std {std.numel()}) != latent channels {z.shape[1]}")
696
+ view = [1, z.shape[1]] + [1] * (z.ndim - 2)
697
+ return mean.reshape(view), std.reshape(view)
698
+
699
+
700
+ def training_latent_to_diag_gaussian_latent(z: torch.Tensor, stats, *, eps: float = 1e-6) -> torch.Tensor:
701
+ """Encoder latent -> the model's space: (z - mean) / std per channel. ``z``: [B, C, ...]."""
702
+ mean, std = _diag_stats_like(stats, z, eps=eps)
703
+ return (z - mean) / std
704
+
705
+
706
+ def diag_gaussian_latent_to_training_latent(z: torch.Tensor, stats, *, eps: float = 1e-6) -> torch.Tensor:
707
+ """The model's space -> encoder latent: z * std + mean per channel. Apply before decoding."""
708
+ mean, std = _diag_stats_like(stats, z, eps=eps)
709
+ return z * std + mean
sae_compact.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a9fe2d914079d824613b675596979554a61bd85fd3763d4c8573f212aa635c01
3
+ size 875802867
serve_ckpts/gta_model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:195780af9dcf18cbea0eadb5fe88b4873c2cd1227b34a190c0b20f75e458abad
3
+ size 2520957857
streaming_server_utils/__init__.py ADDED
File without changes
streaming_server_utils/ckpt_name_schema.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Checkpoint file names.
2
+
3
+ <stem>.pt with stem = token("-" token)* tokens are [a-z0-9_]+, optionally with decimal
4
+ parts like `a2.5` (lowercase; the parser lowercases)
5
+
6
+ At most ONE token is the RECIPE token `<K><r|nr>`:
7
+ K number of denoising steps per frame (2, 3, ...) == len(ckpt config timesteps)
8
+ r "recache": every step read-only + an extra t=0 pass writes the clean KV
9
+ nr "last_step_writes": the last step is the KV writer, no t=0 pass
10
+ so `2nr`, `3nr`, `2r`, `3r`, `4r`. A name without a recipe token (`gta_model.pt`, the released file) takes the
11
+ recipe from the checkpoint's config. The released checkpoint is 3 steps, recache.
12
+
13
+ Optional token `rec`: serve this checkpoint with the server's CONFIG["serve_recency"] bias. Inference-time only;
14
+ the weights are untouched. A checkpoint whose config carries its own recency bias is always served with that one
15
+ and must not carry `rec` (refused).
16
+
17
+ Every other token is a free label and means nothing to the server. The stem is the model_id the client sees and
18
+ sends back.
19
+
20
+ gta_model.pt no recipe token: the recipe is the one in the checkpoint's config
21
+ gta-3r.pt 3 steps per frame, recache
22
+ gta-3r-rec.pt the same weights, served with the recency bias on
23
+
24
+ The name is a contract, not the source of truth: the server reads K and the cache mode from the .pt's config
25
+ and refuses a file whose recipe token disagrees (a mislabeled checkpoint is worse than an unlabeled one).
26
+ Everything else (window size, timesteps, recency, sink_gap_max, noise schedule) is read from the .pt as well; the
27
+ name only has to tell a human which loop the model runs.
28
+ """
29
+ from __future__ import annotations
30
+
31
+ import os
32
+ import re
33
+ from dataclasses import dataclass
34
+
35
+ CACHE_MODE_OF_TOKEN = {"r": "recache", "nr": "last_step_writes"}
36
+ TOKEN_OF_CACHE_MODE = {v: k for k, v in CACHE_MODE_OF_TOKEN.items()}
37
+ _RECIPE_RE = re.compile(r"^(\d+)(nr|r)$")
38
+ # Labels are [a-z0-9_]+, optionally with decimal parts (a2.5).
39
+ _TOKEN_RE = re.compile(r"^[a-z0-9_]+(?:\.[0-9]+)*$")
40
+ RECENCY_TOKEN = "rec"
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class CkptName:
45
+ model_id: str # the stem, e.g. "gta-3r"
46
+ steps: int # K
47
+ cache_mode: str # "recache" | "last_step_writes"
48
+ labels: tuple[str, ...]
49
+ serve_recency: bool = False # `rec` token: apply the server's recency bias to a checkpoint that has none
50
+
51
+ @property
52
+ def recipe(self) -> str:
53
+ """Human tag: "2NR", "3R", "2NR+rec"."""
54
+ base = f"{self.steps}{TOKEN_OF_CACHE_MODE[self.cache_mode].upper()}"
55
+ return f"{base}+{RECENCY_TOKEN}" if self.serve_recency else base
56
+
57
+
58
+ def parse_ckpt_name(path_or_name: str, saved: dict | None = None) -> CkptName:
59
+ """`.../gta_model.pt` or `.../gta-3r.pt` -> CkptName. Raises ValueError on anything off-schema.
60
+
61
+ `saved` is the checkpoint's config. It is needed only for a name without a recipe token, whose steps and
62
+ cache mode are then the config's.
63
+ """
64
+ base = os.path.basename(str(path_or_name))
65
+ stem, ext = os.path.splitext(base)
66
+ if ext.lower() != ".pt" or not stem:
67
+ raise ValueError(f"[ckpt-name] {base!r}: expected <tokens>.pt")
68
+ tokens = stem.lower().split("-")
69
+ if any(not _TOKEN_RE.match(t) for t in tokens):
70
+ raise ValueError(f"[ckpt-name] {base!r}: tokens must be [a-z0-9_]+ or decimal tags like a2.5, joined by '-' (got {tokens})")
71
+ recipes = [t for t in tokens if _RECIPE_RE.match(t)]
72
+ if len(recipes) > 1:
73
+ raise ValueError(f"[ckpt-name] {base!r}: at most one recipe token <K>r|<K>nr (2nr, 3r, ...); found {recipes}")
74
+ if recipes:
75
+ m = _RECIPE_RE.match(recipes[0])
76
+ steps, cache_mode = int(m.group(1)), CACHE_MODE_OF_TOKEN[m.group(2)]
77
+ else:
78
+ if not isinstance(saved, dict):
79
+ raise ValueError(f"[ckpt-name] {base!r}: no recipe token <K>r|<K>nr in the name and no checkpoint config to read it from")
80
+ steps, cache_mode = len(saved.get("timesteps") or []), saved.get("cache_mode")
81
+ if cache_mode not in TOKEN_OF_CACHE_MODE:
82
+ raise ValueError(f"[ckpt-name] {base!r}: the checkpoint config has cache_mode={cache_mode!r}; expected one of {sorted(TOKEN_OF_CACHE_MODE)}")
83
+ if steps < 1:
84
+ raise ValueError(f"[ckpt-name] {base!r}: K must be >= 1")
85
+ n_rec = tokens.count(RECENCY_TOKEN)
86
+ if n_rec > 1:
87
+ raise ValueError(f"[ckpt-name] {base!r}: the {RECENCY_TOKEN!r} token appears {n_rec} times")
88
+ return CkptName(model_id=stem.lower(), steps=steps, cache_mode=cache_mode,
89
+ labels=tuple(t for t in tokens if t not in recipes and t != RECENCY_TOKEN), serve_recency=n_rec == 1)
90
+
91
+
92
+ def trained_recency(saved: dict):
93
+ """The recency bias the checkpoint carries: its config's ``recency`` dict, or None (absent /
94
+ {"enabled": False} = none)."""
95
+ rec = saved.get("recency")
96
+ if isinstance(rec, dict) and rec.get("enabled", True) is False:
97
+ return None
98
+ return rec if rec else None
99
+
100
+
101
+ def check_name_against_config(name: CkptName, saved: dict) -> None:
102
+ """The .pt's config must agree with the recipe token. Raises RuntimeError otherwise."""
103
+ ts = list(saved.get("timesteps") or [])
104
+ mode = saved.get("cache_mode")
105
+ if len(ts) != name.steps:
106
+ raise RuntimeError(f"[ckpt-name] {name.model_id}.pt says {name.steps} steps but the ckpt config has timesteps={ts}")
107
+ if mode != name.cache_mode:
108
+ want = TOKEN_OF_CACHE_MODE.get(str(mode), "?")
109
+ raise RuntimeError(f"[ckpt-name] {name.model_id}.pt says {name.recipe} but the ckpt config has cache_mode={mode!r} "
110
+ f"(the name should carry {name.steps}{want})")
111
+ if name.serve_recency and trained_recency(saved) is not None:
112
+ raise RuntimeError(f"[ckpt-name] {name.model_id}.pt carries {RECENCY_TOKEN!r} but the checkpoint has its own recency "
113
+ f"{trained_recency(saved)}; it is served with its own bias regardless -- drop the token")
streaming_server_utils/controls.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def _clamp(v: float, lo: float, hi: float) -> float:
2
+ return float(max(float(lo), min(float(hi), float(v))))
3
+
4
+
5
+ def _as_float(v, default: float) -> float:
6
+ try:
7
+ return float(v)
8
+ except Exception:
9
+ return float(default)
10
+
11
+
12
+ def _client_schema_5d(state: dict | None) -> list[float]:
13
+ """
14
+ Map Next.js/WebRTC client controls to our 5-D action vector:
15
+ [forwardBack, strafeLeftRight, turnLeftRight, vertical, boost]
16
+
17
+ Inputs supported:
18
+ - { "pressed": { w,a,s,d,shift,space,left,right } }
19
+ - { "pressed_keys": ["w","a",...] } (legacy)
20
+ - {
21
+ "schemaVersion": "keys+intensity-v1",
22
+ "actionVector5d": [f0, f1, f2, f3, f4],
23
+ "sensitivity": {
24
+ "forwardBack": x, "strafeLeftRight": x, "turnLeftRight": x, "vertical": x, "boost": x
25
+ },
26
+ }
27
+
28
+ Rules (keyboard → axes/buttons):
29
+ - axis0 = (w - s) * forwardBack
30
+ - axis1 = (d - a) * strafeLeftRight
31
+ - axis2 = (right - left) * turnLeftRight
32
+ - axis3 = space * vertical
33
+ - axis4 = shift * boost
34
+ """
35
+ if not isinstance(state, dict):
36
+ return [0.0, 0.0, 0.0, 0.0, 0.0]
37
+
38
+ schema_version = str(state.get("schemaVersion", "")).strip()
39
+ vec_direct = state.get("actionVector5d", None)
40
+ if schema_version == "keys+intensity-v1" and isinstance(vec_direct, (list, tuple)) and int(len(vec_direct)) == 5:
41
+ return [_clamp(_as_float(x, 0.0), -1.0, 1.0) for x in vec_direct]
42
+
43
+ sens = state.get("sensitivity", None)
44
+ if not isinstance(sens, dict):
45
+ sens = {}
46
+ s_forward = _clamp(_as_float(sens.get("forwardBack", 1.0), 1.0), 0.0, 1.0)
47
+ s_strafe = _clamp(_as_float(sens.get("strafeLeftRight", 1.0), 1.0), 0.0, 1.0)
48
+ s_turn = _clamp(_as_float(sens.get("turnLeftRight", 1.0), 1.0), 0.0, 1.0)
49
+ s_vertical = _clamp(_as_float(sens.get("vertical", 1.0), 1.0), 0.0, 1.0)
50
+ s_boost = _clamp(_as_float(sens.get("boost", 1.0), 1.0), 0.0, 1.0)
51
+
52
+ pressed = state.get("pressed")
53
+ if isinstance(pressed, dict):
54
+ w = bool(pressed.get("w", False))
55
+ a = bool(pressed.get("a", False))
56
+ s = bool(pressed.get("s", False))
57
+ d = bool(pressed.get("d", False))
58
+ shift = bool(pressed.get("shift", False))
59
+ space = bool(pressed.get("space", False))
60
+ left = bool(pressed.get("left", False))
61
+ right = bool(pressed.get("right", False))
62
+ else:
63
+ keys = set(k.lower() for k in state.get("pressed_keys", []) if isinstance(k, str))
64
+ w = ("w" in keys)
65
+ a = ("a" in keys)
66
+ s = ("s" in keys)
67
+ d = ("d" in keys)
68
+ shift = ("shift" in keys)
69
+ space = ("space" in keys)
70
+ left = ("arrowleft" in keys) or ("left" in keys)
71
+ right = ("arrowright" in keys) or ("right" in keys)
72
+
73
+ wv = 1.0 if w else 0.0
74
+ sv = 1.0 if s else 0.0
75
+ av = 1.0 if a else 0.0
76
+ dv = 1.0 if d else 0.0
77
+ lv = 1.0 if left else 0.0
78
+ rv = 1.0 if right else 0.0
79
+ space_v = 1.0 if space else 0.0
80
+ shift_v = 1.0 if shift else 0.0
81
+
82
+ axis0 = _clamp((wv - sv) * s_forward, -1.0, 1.0)
83
+ axis1 = _clamp((dv - av) * s_strafe, -1.0, 1.0)
84
+ axis2 = _clamp((rv - lv) * s_turn, -1.0, 1.0)
85
+ axis3 = _clamp(space_v * s_vertical, -1.0, 1.0)
86
+ axis4 = _clamp(shift_v * s_boost, -1.0, 1.0)
87
+
88
+ return [axis0, axis1, axis2, axis3, axis4]
89
+
90
+
91
+ def nextjs_client_actions_to_world_model_5_dim_actions(state: dict | None, *, allow_jump_sprint: bool = False) -> list[float]:
92
+ """
93
+ Client controls -> the model's 5-d action:
94
+ [forward(W/S), sideways(A/D), sprint, jump, camera_rx]
95
+ Signs: +sideways = D, +camera_rx = turning right (arrow right).
96
+
97
+ allow_jump_sprint=True (the checkpoint config's `jump_sprint`): shift goes to dim 2 (sprint) and space to
98
+ dim 3 (jump), with the client's gains applied, clamped to [0, 1].
99
+ allow_jump_sprint=False: dims 2 and 3 are 0 whatever the client sends (space / shift are ignored).
100
+ No keys pressed -> the all-zero vector (standing still).
101
+ """
102
+ # Client schema (both the key path and actionVector5d): [forwardBack, strafeLeftRight, turnLeftRight, vertical, boost]
103
+ v = _client_schema_5d(state)
104
+ if allow_jump_sprint:
105
+ sprint = _clamp(v[4], 0.0, 1.0) # shift -> dim 2
106
+ jump = _clamp(v[3], 0.0, 1.0) # space -> dim 3
107
+ return [v[0], v[1], sprint, jump, v[2]]
108
+ return [v[0], v[1], 0.0, 0.0, v[2]]
summary_server.py ADDED
The diff for this file is too large to render. See raw diff
 
summary_streaming_inference.py ADDED
@@ -0,0 +1,937 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Summaryformer streaming session: one trunk, one full-res stage, one tick per body frame.
2
+
3
+ One ``SummaryKVCache`` — one K/V buffer per layer,
4
+ ``| Z0 | RAW : (Y+1) slots | SUM : (W−Y) slots |`` — one ``StageSpec``, model calls only at the
5
+ timesteps on the spec.
6
+
7
+ z0 (GT, from the upload) --forward_z0 t=0, note_z0_written--> Z0 slot (never generated)
8
+ frame t (abs_t = 1, 2, ...), i frames already committed:
9
+ T = SinkChaser.rotate(kv, model.rope_table, n_committed=i) # one Z0 slot, one int (0 = none)
10
+ kv.begin_frame() # donate RAW[cursor_r]'s X summary rows into SUM
11
+ lat ~ N(0,1) fp32
12
+ for t in spec.timesteps (e.g. 999, 878, 669):
13
+ v = forward_body(lat, t) -> x0_hat = signal(t) * lat - noise(t) * v # writes record(t) into RAW[cursor_r]
14
+ lat = signal(t_next) * x0_hat + noise(t_next) * z, z FRESH (re-noise to the next timestep)
15
+ cache_mode "recache" (KR): t=0 pass rewrites that RAW slot with the clean record, then commit
16
+ cache_mode "last_step_writes" (KNR): commit the record the last pass wrote (no extra pass)
17
+ commit = cursor_r += 1 (mod Y+1); no copy
18
+ -> x0 (diag-gauss) -> un-gaussianize (rest stats) -> SAE decode_steady -> 4 RGB frames
19
+
20
+ Geometry is the model's: X summary tokens, Y raw-window frames, W summary-window frames, one
21
+ full-res grid (24x42 serve / the spec's ``hw``). One dense attention call per layer (every
22
+ query reads the prefix ``[0 : end]``); nothing on the cache path may ``torch.cat``.
23
+
24
+ Numerics: bf16 autocast on CUDA, fp32 latents / x0 arithmetic, bf16 KV (fp32 KV on CPU so
25
+ parity tests can be bit-exact). Weight dtype is the server's business.
26
+
27
+ torch.compile: the server hands in ``forward_body_compiled`` / ``decode_steady_compiled``.
28
+ ``forward_body`` runs compiled from body frame 1 (frame id is a persistent 0-d int64 device
29
+ tensor filled in place; a tensor id selects ``plan_body(device_ends=True)``, whose ``end`` is
30
+ the one ``end_dev``). z0 warm is eager. SAE decode is compiled only once ``n_body >= Y`` unless
31
+ the flag says otherwise. KV storage (``k``, ``v``, the recency bias) and ``end_dev`` are pinned
32
+ (``mark_static_address``) after ``build`` and ``enable_recency``, so cudagraphs replay against
33
+ them. The wrapper marks those; this session does not mark them twice.
34
+
35
+ Long horizon: ``SinkChaser`` rotates the one Z0 slot when ``oldest_alive - sink_id`` reaches
36
+ ``sink_gap_max`` (one int). Absolute ids keep growing; the session HARD-STOPS at the last RoPE
37
+ table row instead of wrapping.
38
+
39
+ Fail-fast: spec vs model at ctor; ``step()`` before ``start()``; abs_t >= RoPE rows;
40
+ a None sink gap (an unbounded stream needs the one slot chased).
41
+
42
+ Recency comes from ``StageSpec.recency`` and is enabled on the empty buffer right after build /
43
+ reset, before any body frame and before any compiled marking. The bias covers the whole buffer
44
+ and is non-zero only on the SUM region.
45
+
46
+ z0 focus region rides the z0 warm's cond ONLY, never body frames.
47
+ """
48
+ from __future__ import annotations
49
+
50
+ import time
51
+ from collections import deque
52
+ from dataclasses import dataclass
53
+
54
+ import torch
55
+
56
+ from gta_streaming_kv_cache import SummaryKVCache
57
+ from inference_common import (
58
+ StageSampling,
59
+ cond_dict,
60
+ frame_tokens,
61
+ warm_z0_clean,
62
+ )
63
+ from sae import diag_gaussian_latent_to_training_latent, training_latent_to_diag_gaussian_latent
64
+ from summaryformer import Summaryformer
65
+ from summaryformer_utils.streaming_sink import (
66
+ SinkChaser,
67
+ sink_gaps_describe,
68
+ sink_gaps_from_config,
69
+ )
70
+ from summaryformer_wrapper import SummaryformerWrapper
71
+
72
+ # How a generated frame's keys and values get into the cache: "recache" runs one extra clean pass over
73
+ # the finished frame; "last_step_writes" keeps what the final denoising step wrote. The checkpoint's
74
+ # config names which one it expects.
75
+ CACHE_MODES = ("recache", "last_step_writes")
76
+
77
+ Z0_C = Z_REST_C = int(Summaryformer.LATENT_CHANNELS)
78
+ SAE_SPATIAL = 16
79
+ _RGB_MEAN = torch.tensor([0.485, 0.456, 0.406]).view(1, 1, 3, 1, 1)
80
+ _RGB_STD = torch.tensor([0.229, 0.224, 0.225]).view(1, 1, 3, 1, 1)
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class StageSpec:
85
+ """ONE stage; the server builds it from the ckpt config and the session checks it against the model.
86
+
87
+ ``samp``: ``resolve_sampling(ckpt_cfg)``, the timesteps a body frame is denoised at.
88
+ ``stats_*``: full-res diag-gauss artifacts (C=48). ``sink_gap_max``: one int >= 2 (the one Z0 slot).
89
+ """
90
+ hw: tuple[int, int]
91
+ stats_z0: dict
92
+ stats_rest: dict
93
+ samp: StageSampling
94
+ cache_mode: str
95
+ sink_gap_max: int
96
+ recency: dict | None
97
+ focus_region: torch.Tensor | None
98
+
99
+ def __post_init__(self):
100
+ h, w = (int(self.hw[0]), int(self.hw[1]))
101
+ if h <= 0 or w <= 0:
102
+ raise ValueError(f"StageSpec.hw must be positive (h, w); got {self.hw!r}")
103
+ if not isinstance(self.samp, StageSampling):
104
+ raise TypeError(f"StageSpec.samp must be StageSampling; got {type(self.samp)}")
105
+ if len(self.samp.timesteps) < 1:
106
+ raise ValueError(f"StageSpec.samp has no model timesteps: {self.samp.timesteps}")
107
+ if self.cache_mode not in CACHE_MODES:
108
+ raise ValueError(f"StageSpec.cache_mode={self.cache_mode!r} not in {CACHE_MODES}")
109
+ gap = sink_gaps_from_config(self.sink_gap_max)
110
+ if gap is None:
111
+ raise RuntimeError(
112
+ "StageSpec.sink_gap_max is None: an unbounded stream needs the one Z0 slot chased "
113
+ f"({sink_gaps_describe(gap)}; pass an int >= 2)"
114
+ )
115
+ object.__setattr__(self, "sink_gap_max", gap)
116
+ if self.recency is not None and not isinstance(self.recency, dict):
117
+ raise TypeError(f"StageSpec.recency must be a dict or None; got {type(self.recency)}")
118
+ for name, art in (("stats_z0", self.stats_z0), ("stats_rest", self.stats_rest)):
119
+ if not (isinstance(art, dict) and "mean" in art and "std" in art):
120
+ raise ValueError(f"StageSpec.{name} must be a diag-gauss dict with mean/std")
121
+ if int(torch.as_tensor(art["mean"]).numel()) != Z0_C:
122
+ raise ValueError(
123
+ f"StageSpec.{name} mean numel={int(torch.as_tensor(art['mean']).numel())} != C={Z0_C}"
124
+ )
125
+ region = self.focus_region
126
+ if region is None:
127
+ return
128
+ if not (
129
+ isinstance(region, torch.Tensor)
130
+ and region.dtype == torch.bool
131
+ and tuple(region.shape) == (1, h, w)
132
+ ):
133
+ raise RuntimeError(
134
+ f"StageSpec.focus_region must be Bool [1,{h},{w}] or None; "
135
+ f"got {getattr(region, 'shape', type(region))} dtype={getattr(region, 'dtype', None)}"
136
+ )
137
+ if not bool(region.any()):
138
+ raise RuntimeError("StageSpec.focus_region is all-False: pass None for 'no region'")
139
+
140
+ @property
141
+ def h(self) -> int:
142
+ return int(self.hw[0])
143
+
144
+ @property
145
+ def w(self) -> int:
146
+ return int(self.hw[1])
147
+
148
+ @property
149
+ def timesteps(self) -> list[int]:
150
+ """Timesteps the model is called at on body frames, high -> low (e.g. [999, 878, 669]). The session
151
+ only ever denoises body frames; the seed frame is written clean at t = 0."""
152
+ return list(self.samp.timesteps)
153
+
154
+ @property
155
+ def spaced_indices(self) -> list[int]:
156
+ """Indices into the sampling grid's tables the loop visits, in order, len == nfe
157
+ (repeats when the samp carries a step_plan)."""
158
+ return list(self.samp.indices)
159
+
160
+ @property
161
+ def nfe(self) -> int:
162
+ return len(self.timesteps)
163
+
164
+
165
+ def _stats_to_device(stats: dict, device: torch.device) -> dict:
166
+ """Diag-gauss artifact with mean/std already on `device` (fp32): no H2D per call."""
167
+ out = dict(stats)
168
+ out["mean"] = torch.as_tensor(stats["mean"]).to(device=device, dtype=torch.float32)
169
+ out["std"] = torch.as_tensor(stats["std"]).to(device=device, dtype=torch.float32)
170
+ return out
171
+
172
+
173
+ def _check_spec_against_model(model, spec: StageSpec) -> None:
174
+ """X/Y/W live on the model."""
175
+ x, y, w = (
176
+ int(model.summary_tokens),
177
+ int(model.raw_window_frames),
178
+ int(model.summary_window_frames),
179
+ )
180
+ if x < 1 or y < 0 or w < 0:
181
+ raise RuntimeError(f"[summary-stream] model X/Y/W={(x, y, w)} is not a serveable geometry")
182
+
183
+
184
+ # ``start(focus_region=FOCUS_DEFAULT)``: use the spec's region (the ckpt's served default, a centred diamond when the
185
+ # focus operator was trained). ``None`` = no region for this game; a Bool ``[1, h, w]`` = a custom region (the client's
186
+ # painted mask) for this game only. The default is restored by the next ``start`` that does not override it.
187
+ FOCUS_DEFAULT = object()
188
+
189
+
190
+ def _coerce_focus_region(region, spec: StageSpec, device) -> torch.Tensor | None:
191
+ if region is None:
192
+ return None
193
+ if not (
194
+ isinstance(region, torch.Tensor)
195
+ and region.dtype == torch.bool
196
+ and tuple(region.shape) == (1, spec.h, spec.w)
197
+ ):
198
+ raise RuntimeError(
199
+ f"[summary-stream] focus_region must be Bool [1,{spec.h},{spec.w}] or None; "
200
+ f"got {getattr(region, 'shape', type(region))} dtype={getattr(region, 'dtype', None)}"
201
+ )
202
+ if not bool(region.any()):
203
+ raise RuntimeError("[summary-stream] focus_region is all-False: pass None for 'no region'")
204
+ return region.to(device=device).contiguous()
205
+
206
+
207
+ def _normalize_fps(fps) -> float | None:
208
+ """NaN / None = no fps conditioning; a number in [1, 120] is the game clock."""
209
+ if fps is None:
210
+ return None
211
+ if isinstance(fps, torch.Tensor):
212
+ if fps.numel() != 1:
213
+ raise RuntimeError(f"[summary-stream] fps tensor must be a scalar; got {tuple(fps.shape)}")
214
+ fps = float(fps.item())
215
+ if isinstance(fps, (int, float)):
216
+ f = float(fps)
217
+ if f != f: # NaN
218
+ return None
219
+ if not 1.0 <= f <= 120.0:
220
+ raise RuntimeError(f"[summary-stream] fps must be None/NaN or a number in [1, 120]; got {fps!r}")
221
+ return f
222
+ raise RuntimeError(f"[summary-stream] fps must be None/NaN or a number in [1, 120]; got {fps!r}")
223
+
224
+
225
+ # ----------------------------------------------------------------------------------------------
226
+ # SAE sphere projection (serve-time option)
227
+ # ----------------------------------------------------------------------------------------------
228
+ # The SAE encoder ends in `sae.SphereNorm3d`: every 48-channel token is forced to RMS=1 (L2 radius
229
+ # sqrt(48)), no mean subtraction, non-affine. The decoder expects such tokens and has no input norm of
230
+ # its own. The diffusion model works in per-channel diag-gauss space, where that sphere is an
231
+ # ellipsoid, so a generated x0_hat can drift off the sphere. These modes put it back:
232
+ # "off" nothing.
233
+ # "decode" project the RAW latent handed to the SAE decoder only (seed and every body frame). The
234
+ # diffusion loop and the KV are untouched.
235
+ # "all" "decode" plus: every x0_hat inside the renoise loop (ungauss -> project -> regauss, so
236
+ # the next re-noise, the t=0 recache write and the decode all see the on-sphere x0), and
237
+ # the seed z0 in start() (a no-op for an encoder z0, which is already on the sphere).
238
+ SPHERE_MODES = ("off", "decode", "all")
239
+ _SPHERE_EPS = 1e-6 # sae.SphereNorm3d: eps added INSIDE the sqrt
240
+
241
+
242
+ def sphere_project_raw(z_raw: torch.Tensor, *, cdim: int = 1) -> torch.Tensor:
243
+ """RAW SAE latent -> the encoder's SphereNorm3d manifold: per-token RMS=1 over the channel axis.
244
+ Bit-for-bit the encoder's op (fp32 rms, eps inside the sqrt). Shape-agnostic; ``cdim`` is the
245
+ 48-channel axis."""
246
+ rms = z_raw.float().pow(2).mean(dim=cdim, keepdim=True).add(_SPHERE_EPS).sqrt()
247
+ return z_raw / rms.to(z_raw.dtype)
248
+
249
+
250
+ def _sched_tables(samp: StageSampling, device: torch.device) -> tuple[torch.Tensor, torch.Tensor]:
251
+ """The sampling grid's signal / noise scales, sqrt(ā) / sqrt(1-ā), on `device` (fp32), indexed by grid
252
+ index."""
253
+ a = torch.as_tensor(samp.grid.signal, device=device, dtype=torch.float32)
254
+ b = torch.as_tensor(samp.grid.noise, device=device, dtype=torch.float32)
255
+ return a, b
256
+
257
+
258
+ def _body_steps(samp: StageSampling) -> tuple[list[int], list[int]]:
259
+ """(grid indices, timesteps) the body loop visits, in order, len == NFE. Each grid index once
260
+ high -> low, or ``samp.step_plan`` (repeats allowed: a repeated index re-noises x0_hat to the same t
261
+ and calls the model there again)."""
262
+ return list(samp.indices), list(samp.timesteps)
263
+
264
+
265
+ def renoise_body_x0(
266
+ *,
267
+ call,
268
+ cond: dict,
269
+ samp: StageSampling,
270
+ lat_shape: tuple[int, ...],
271
+ noise_fn,
272
+ sqrt_ab: torch.Tensor,
273
+ sqrt_om: torch.Tensor,
274
+ t_buffer: torch.Tensor,
275
+ project_x0=None,
276
+ ) -> torch.Tensor:
277
+ """K renoise passes on one body frame. Model at REAL timesteps; fresh z between passes.
278
+
279
+ ``call(x[B,1,C,H,W], t[B,1], cond) -> v[B,1,C,H,W]``. ``noise_fn(shape) -> tensor``.
280
+ ``sqrt_ab`` / ``sqrt_om`` are the device-resident signal / noise tables of the sampling grid
281
+ (``_sched_tables``). Returns x0
282
+ ``[B,1,C,H,W]`` fp32. ``project_x0`` (optional, eager, fp32 gauss -> fp32 gauss) is applied to
283
+ every x0 estimate before it is re-noised or returned (sphere mode "all").
284
+ """
285
+ indices, real_ts = _body_steps(samp)
286
+ if len(indices) != len(real_ts) or not indices:
287
+ raise RuntimeError(f"[summary-stream] spaced/real timestep mismatch: {indices} vs {real_ts}")
288
+ lat = noise_fn(lat_shape)
289
+ if not (isinstance(lat, torch.Tensor) and lat.dim() == 5 and int(lat.size(1)) == 1):
290
+ raise RuntimeError(f"[summary-stream] noise_fn must return [B,1,C,H,W]; got {getattr(lat, 'shape', type(lat))}")
291
+ x0 = None
292
+ for step_i, (t_idx, t_real) in enumerate(zip(indices, real_ts)):
293
+ t_buffer.fill_(float(t_real))
294
+ v = call(lat, t_buffer, cond).float()
295
+ a, b = sqrt_ab[int(t_idx)], sqrt_om[int(t_idx)]
296
+ x0 = (a * lat - b * v) / (a * a + b * b)
297
+ if project_x0 is not None:
298
+ x0 = project_x0(x0)
299
+ if step_i < len(indices) - 1:
300
+ z = noise_fn(tuple(x0.shape))
301
+ a_n, b_n = sqrt_ab[int(indices[step_i + 1])], sqrt_om[int(indices[step_i + 1])]
302
+ lat = a_n * x0 + b_n * z
303
+ return x0
304
+
305
+
306
+ class SummaryStreamSession:
307
+ """One player, one device. Owns the KV buffer, RNG, SAE decode cache, gaussianization boundary."""
308
+
309
+ def __init__(
310
+ self,
311
+ *,
312
+ generator,
313
+ sae_decoder,
314
+ spec: StageSpec,
315
+ device,
316
+ rgb_hw: tuple[int, int] = (384, 672),
317
+ forward_body_compiled=None,
318
+ decode_steady_compiled=None,
319
+ use_compiled_sae_in_steady_state: bool = True,
320
+ ):
321
+ gen = getattr(generator, "module", generator)
322
+ if not isinstance(gen, SummaryformerWrapper):
323
+ raise RuntimeError(f"[summary-stream] generator must be SummaryformerWrapper; got {type(generator)}")
324
+ if not isinstance(spec, StageSpec):
325
+ raise TypeError(f"[summary-stream] spec must be StageSpec; got {type(spec)}")
326
+ if not (hasattr(sae_decoder, "decode_bootstrap") and hasattr(sae_decoder, "decode_steady")):
327
+ raise RuntimeError("[summary-stream] sae_decoder must expose decode_bootstrap / decode_steady")
328
+ device = torch.device(device)
329
+ model = gen.model
330
+ _check_spec_against_model(model, spec)
331
+ rh, rw = (int(x) for x in rgb_hw)
332
+ if (rh, rw) != (spec.h * SAE_SPATIAL, spec.w * SAE_SPATIAL):
333
+ raise RuntimeError(
334
+ f"[summary-stream] rgb_hw {rh}x{rw} != {SAE_SPATIAL} * latent grid {spec.h}x{spec.w}"
335
+ )
336
+
337
+ self.generator, self.model, self.sae, self.device = gen, model, sae_decoder, device
338
+ self.spec = spec
339
+ self.focus_region_default = self.focus_region = _coerce_focus_region(spec.focus_region, spec, device)
340
+ self.rgb_hw = (rh, rw)
341
+ # Serve: bf16 autocast + bf16 KV. CPU parity: fp32 throughout so x0 can be torch.equal.
342
+ self.amp_dtype = torch.bfloat16 if device.type == "cuda" else torch.float32
343
+ try:
344
+ self.sae_dtype = next(sae_decoder.parameters()).dtype
345
+ except StopIteration:
346
+ self.sae_dtype = torch.float32
347
+ self.tf = int(frame_tokens(model, spec.h, spec.w))
348
+ self.X = int(model.summary_tokens)
349
+ self.Y = int(model.raw_window_frames)
350
+ self.W = int(model.summary_window_frames)
351
+
352
+ self.visual_kv: SummaryKVCache = gen.new_visual_kv_cache()
353
+ if not isinstance(self.visual_kv, SummaryKVCache):
354
+ raise RuntimeError("[summary-stream] new_visual_kv_cache must return SummaryKVCache")
355
+ with torch.no_grad():
356
+ self.visual_kv.build(
357
+ batch=1, frame_tokens=self.tf, dtype=self.amp_dtype, device=device,
358
+ )
359
+ # Recency on the empty buffer (bias non-zero only on SUM), before any frame and before
360
+ # static marking. mark_streaming_caches_static pins k, v, the bias, and the one end_dev.
361
+ self.visual_kv.enable_recency(spec.recency)
362
+ self.recency = self.visual_kv.recency
363
+ self._chaser = self._new_chaser()
364
+
365
+ self._body_x, self._sae_x = forward_body_compiled, decode_steady_compiled
366
+ self.use_compiled_sae_in_steady_state = bool(use_compiled_sae_in_steady_state)
367
+ self._mode_log: dict[str, str] = {}
368
+ self._any_generator_compiled = self._body_x is not None
369
+ if self._any_generator_compiled:
370
+ n_static = int(SummaryformerWrapper.mark_streaming_caches_static(self.visual_kv))
371
+ if n_static <= 0:
372
+ raise RuntimeError("[summary-stream] compiled generator given but no KV tensors were marked static")
373
+ print(f"[perf][cudagraph] marked {n_static} KV tensors static (mark_static_address) at build", flush=True)
374
+
375
+ self._rng: torch.Generator | None = None
376
+ self.noise_fn = None # optional ``(shape) -> tensor`` hook (parity tests)
377
+ self._abs_t: int | None = None
378
+ self._abs_t_dev = torch.zeros((), device=device, dtype=torch.long)
379
+ self._n_body = 0
380
+ self._sae_cache = None
381
+ self.last_x0: torch.Tensor | None = None
382
+ self.last_ms: dict[str, float] = {}
383
+ self._fps_logged: float | None | str = "unset"
384
+ self._peak_ema: float | None = None
385
+
386
+ self._stats_dev = {
387
+ "z0": _stats_to_device(spec.stats_z0, device),
388
+ "rest": _stats_to_device(spec.stats_rest, device),
389
+ }
390
+ self._sqrt_ab, self._sqrt_om = _sched_tables(spec.samp, device)
391
+ # Forward re-prefill history (see reprefill()): the last W committed body frames as
392
+ # (gauss x0 [1,C,h,w] fp32 AS WRITTEN by the recache pass, action [1,1,5], fps), plus the
393
+ # game's gauss z0. ~190 KB/frame at 24x42; 6 MB at W=32.
394
+ self._hist: deque = deque(maxlen=int(self.W))
395
+ self._z0_gauss: torch.Tensor | None = None
396
+ self._z0_fps: float | None = None
397
+ self.reprefill_every: int = 0 # 0 = off; n = rebuild the KV from history every n body frames
398
+ self._since_reprefill = 0 # body frames since start() / the last reprefill (the trigger counter)
399
+ self.n_reprefills = 0 # rebuilds this game
400
+ self.last_reprefill: dict | None = None
401
+ self._t_dev = torch.zeros((1, 1), device=device, dtype=torch.float32)
402
+ self._fps_dev = torch.zeros((1,), device=device, dtype=torch.float32)
403
+ self._action_dev = torch.zeros((1, 1, 5), device=device, dtype=torch.float32)
404
+ self._action_pin = (
405
+ torch.zeros((1, 1, 5), dtype=torch.float32).pin_memory() if device.type == "cuda" else None
406
+ )
407
+ self._rgb_mean, self._rgb_std = _RGB_MEAN.to(device), _RGB_STD.to(device)
408
+ self._ev: dict[str, tuple] = {}
409
+ if self._any_generator_compiled:
410
+ for t_ in (self._abs_t_dev, self._t_dev, self._fps_dev, self._action_dev):
411
+ torch._dynamo.mark_static_address(t_)
412
+ self._print_rings()
413
+
414
+ def _new_chaser(self) -> SinkChaser:
415
+ return SinkChaser(
416
+ raw_window=self.Y, summary_window=self.W, gaps=self.spec.sink_gap_max, first_id=1,
417
+ )
418
+
419
+ def _print_rings(self) -> None:
420
+ kv = self.visual_kv
421
+ rec = self.recency
422
+ print(
423
+ f"[summary-stream] one trunk X={self.X} Y={self.Y} W={self.W} Tf={self.tf} "
424
+ f"grid={self.spec.h}x{self.spec.w} rgb={self.rgb_hw[0]}x{self.rgb_hw[1]} "
425
+ f"cache_mode={self.spec.cache_mode} amp={self.amp_dtype} "
426
+ f"{sink_gaps_describe(self.spec.sink_gap_max)} "
427
+ f"rope_rows={int(self.model.rope_table.size(0))} (hard stop) "
428
+ f"compiled(body={self._body_x is not None}, sae={self._sae_x is not None}) "
429
+ f"body compiled from frame 1 (device frame id); sae from steady state",
430
+ flush=True,
431
+ )
432
+ print(f"[summary-stream] {kv.describe()} model t={self.spec.timesteps} nfe={self.spec.nfe}", flush=True)
433
+ print(
434
+ f"[summary-stream] {'recency OFF' if rec is None else rec.cfg.describe()}",
435
+ flush=True,
436
+ )
437
+ if rec is not None:
438
+ from summaryformer_utils.recency_bias import prepare_flex_decode
439
+ # One prefix read: queries are the whole record (Tf + X), keys are the whole buffer.
440
+ print(
441
+ f"[summary-stream] biased attend: {prepare_flex_decode(cap=int(kv.capacity), batch=1, kv_heads=int(self.model.num_heads), frame_tokens=self.tf + self.X, device=self.device)}",
442
+ flush=True,
443
+ )
444
+ print(f"[summary-stream] {self._focus_region_desc()}", flush=True)
445
+
446
+ def _focus_region_desc(self) -> str:
447
+ r = self.focus_region
448
+ if r is None:
449
+ return "z0 focus region OFF (no marker on z0)"
450
+ return (
451
+ f"z0 focus region ON: {int(r.sum().item())}/{int(r.numel())} z0 tokens marked "
452
+ f"({100.0 * float(r.float().mean()):.0f}%), z0 warm only"
453
+ )
454
+
455
+ @property
456
+ def n_body(self) -> int:
457
+ return int(self._n_body)
458
+
459
+ @property
460
+ def abs_t(self) -> int | None:
461
+ return self._abs_t
462
+
463
+ @property
464
+ def chaser(self) -> SinkChaser:
465
+ return self._chaser
466
+
467
+ def _gauss_in(self, z_raw: torch.Tensor, *, which: str) -> torch.Tensor:
468
+ return training_latent_to_diag_gaussian_latent(z_raw.float(), self._stats_dev[which])
469
+
470
+ def _gauss_out(self, z: torch.Tensor, *, which: str) -> torch.Tensor:
471
+ """Gauss -> RAW for the SAE decoder. Sphere modes "decode" / "all" project the RAW token
472
+ onto the encoder's RMS=1 sphere here, in fp32, before the dtype cast and the compiled decode."""
473
+ z_raw = diag_gaussian_latent_to_training_latent(z.float(), self._stats_dev[which])
474
+ if self.sphere_mode != "off":
475
+ z_raw = sphere_project_raw(z_raw, cdim=1)
476
+ return z_raw.to(dtype=self.sae_dtype).unsqueeze(2).contiguous(memory_format=torch.channels_last_3d)
477
+
478
+ # Sphere projection mode (SPHERE_MODES). Plain attribute, read per call; no compiled graph depends
479
+ # on it (every projection is an eager fp32 op on the tensor BEFORE a compiled call).
480
+ sphere_mode: str = "off"
481
+
482
+ def set_sphere_mode(self, mode: str) -> None:
483
+ if mode not in SPHERE_MODES:
484
+ raise ValueError(f"[summary-stream] sphere mode {mode!r} not in {SPHERE_MODES}")
485
+ if mode != self.sphere_mode:
486
+ print(f"[summary-stream] sphere projection {self.sphere_mode} -> {mode}", flush=True)
487
+ self.sphere_mode = mode
488
+
489
+ def _project_gauss(self, z: torch.Tensor, *, which: str) -> torch.Tensor:
490
+ """Gauss -> RAW -> sphere -> gauss, fp32. ``z`` is the [B,1,C,H,W] renoise x0 (the diag-gauss
491
+ helpers want C at dim 1, so the T=1 axis is squeezed around them)."""
492
+ stats = self._stats_dev[which]
493
+ five = z.dim() == 5
494
+ zb = z.float().squeeze(1) if five else z.float()
495
+ z_raw = sphere_project_raw(diag_gaussian_latent_to_training_latent(zb, stats), cdim=1)
496
+ out = training_latent_to_diag_gaussian_latent(z_raw, stats)
497
+ return out.unsqueeze(1) if five else out
498
+
499
+ def _coerce_bchw(self, z, *, name: str) -> torch.Tensor:
500
+ if isinstance(z, torch.Tensor) and z.dim() == 5 and 1 in (int(z.size(1)), int(z.size(2))):
501
+ z = z.squeeze(1) if int(z.size(1)) == 1 else z.squeeze(2)
502
+ if not (isinstance(z, torch.Tensor) and tuple(z.shape) == (1, Z0_C, self.spec.h, self.spec.w)):
503
+ raise RuntimeError(
504
+ f"[summary-stream] {name} must be [1,{Z0_C},{self.spec.h},{self.spec.w}]; "
505
+ f"got {getattr(z, 'shape', type(z))}"
506
+ )
507
+ return z.to(device=self.device).contiguous()
508
+
509
+ def _rgb_out(self, rgb_btchw: torch.Tensor, *, frames: int) -> torch.Tensor:
510
+ rh, rw = self.rgb_hw
511
+ if tuple(rgb_btchw.shape) != (1, frames, 3, rh, rw):
512
+ raise RuntimeError(
513
+ f"[summary-stream] SAE rgb {tuple(rgb_btchw.shape)} != (1,{frames},3,{rh},{rw})"
514
+ )
515
+ return (rgb_btchw.float() * self._rgb_std + self._rgb_mean).clamp(0.0, 1.0)
516
+
517
+ def _autocast(self, dtype: torch.dtype | None = None):
518
+ dt = self.amp_dtype if dtype is None else dtype
519
+ return torch.autocast(
520
+ device_type="cuda", dtype=dt, enabled=self.device.type == "cuda" and dt != torch.float32,
521
+ )
522
+
523
+ def _timed(self, name: str, fn):
524
+ if self.device.type == "cuda":
525
+ s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
526
+ s.record()
527
+ out = fn()
528
+ e.record()
529
+ self._ev[name] = (s, e)
530
+ return out
531
+ t0 = time.perf_counter()
532
+ out = fn()
533
+ self._ev[name] = (t0, time.perf_counter())
534
+ return out
535
+
536
+ def _collect_ms(self) -> dict[str, float]:
537
+ ms = {
538
+ k: float(s.elapsed_time(e)) if self.device.type == "cuda" else (e - s) * 1000.0
539
+ for k, (s, e) in self._ev.items()
540
+ }
541
+ self._ev.clear()
542
+ return ms
543
+
544
+ def _in_steady_state(self) -> bool:
545
+ return self._n_body >= int(self.Y)
546
+
547
+ def _pick(self, what: str, eager, compiled, use_compiled: bool):
548
+ mode = "compiled" if (compiled is not None and use_compiled) else "eager"
549
+ if self._mode_log.get(what) != mode:
550
+ print(f"[perf][{what}-mode] mode={mode} abs_t={self._abs_t} n_body={self._n_body}", flush=True)
551
+ self._mode_log[what] = mode
552
+ return compiled if mode == "compiled" else eager
553
+
554
+ def _forward_body(self):
555
+ return self._pick("generator-body", self.generator.forward_body, self._body_x, True)
556
+
557
+ def _decode_steady(self):
558
+ return self._pick(
559
+ "sae-decode", self.sae.decode_steady, self._sae_x,
560
+ self._in_steady_state() or not self.use_compiled_sae_in_steady_state,
561
+ )
562
+
563
+ def _cond(self, fps: float | None, action_b15: torch.Tensor | None = None, **z0_knobs) -> dict:
564
+ fps_v = None
565
+ if fps is not None:
566
+ self._fps_dev.fill_(float(fps))
567
+ fps_v = self._fps_dev
568
+ return cond_dict(
569
+ fps=fps_v,
570
+ action_context=action_b15,
571
+ **z0_knobs,
572
+ )
573
+
574
+ def _action_to_device(self, action_b15: torch.Tensor) -> torch.Tensor:
575
+ if action_b15.device == self._action_dev.device:
576
+ self._action_dev.copy_(action_b15.to(torch.float32))
577
+ elif self._action_pin is not None:
578
+ self._action_pin.copy_(action_b15.to(torch.float32))
579
+ self._action_dev.copy_(self._action_pin, non_blocking=True)
580
+ else:
581
+ self._action_dev.copy_(action_b15.to(self._action_dev.device, torch.float32))
582
+ return self._action_dev
583
+
584
+ def _noise(self, shape) -> torch.Tensor:
585
+ if self.noise_fn is not None:
586
+ z = self.noise_fn(shape)
587
+ return z.to(device=self.device, dtype=torch.float32)
588
+ if self._rng is None:
589
+ raise RuntimeError("[summary-stream] RNG missing (start() first) and no noise_fn")
590
+ return torch.randn(shape, generator=self._rng, device=self.device, dtype=torch.float32)
591
+
592
+ def _frame_id_arg(self, abs_t: int, *, compiled: bool):
593
+ """Compiled form: persistent 0-d int64 filled in place. The model treats a tensor id as
594
+ ``plan_body(device_ends=True)`` and reads the one ``end_dev``. Eager: the Python int."""
595
+ if compiled:
596
+ self._abs_t_dev.fill_(int(abs_t))
597
+ return self._abs_t_dev
598
+ return int(abs_t)
599
+
600
+ def _body_call(self, x: torch.Tensor, t_buf: torch.Tensor, cond: dict, *, abs_t: int):
601
+ fn = self._forward_body()
602
+ compiled = fn is self._body_x
603
+ with self._autocast():
604
+ v = fn(
605
+ cond, x.to(self.amp_dtype), t_buf, kv_cache=self.visual_kv,
606
+ absolute_start_frames=self._frame_id_arg(abs_t, compiled=compiled),
607
+ )
608
+ return v
609
+
610
+ def _denoise_frame(self, cond: dict, *, abs_t: int) -> torch.Tensor:
611
+ """One body frame: the denoising passes, then the cache write the ckpt's cache_mode asks for. B=1.
612
+
613
+ ``begin_frame`` once before the passes (the model's first ``forward_body`` calls it too;
614
+ the second call is a no-op until commit). Donation of the RAW slot about to be overwritten
615
+ happens here, before any write. Commit advances ``cursor_r`` and does not copy.
616
+ """
617
+ self.visual_kv.begin_frame()
618
+ lat_shape = (1, 1, Z_REST_C, self.spec.h, self.spec.w)
619
+ x0 = renoise_body_x0(
620
+ call=lambda x, t, c, _abs=abs_t: self._body_call(x, t, c, abs_t=_abs),
621
+ cond=cond,
622
+ samp=self.spec.samp,
623
+ lat_shape=lat_shape,
624
+ noise_fn=self._noise,
625
+ sqrt_ab=self._sqrt_ab,
626
+ sqrt_om=self._sqrt_om,
627
+ t_buffer=self._t_dev,
628
+ # Sphere mode "all": every x0 estimate back onto the SAE sphere (eager fp32, before the
629
+ # re-noise, the t=0 recache below, and the decode). "decode" leaves the loop alone.
630
+ project_x0=(lambda x: self._project_gauss(x, which="rest")) if self.sphere_mode == "all" else None,
631
+ )
632
+ if self.spec.cache_mode == "recache":
633
+ self._t_dev.fill_(0.0)
634
+ self._body_call(x0, self._t_dev, cond, abs_t=abs_t)
635
+ self.visual_kv.commit_current_frame()
636
+ # What the cache now holds for this frame is the clean record of THIS x0: remember it.
637
+ self._hist.append((
638
+ x0[:, 0].detach().float().clone(),
639
+ self._action_dev.detach().clone(),
640
+ self._fps_logged if isinstance(self._fps_logged, (int, float)) else None,
641
+ ))
642
+ else:
643
+ self.visual_kv.commit_current_frame()
644
+ return x0
645
+
646
+ # ------------------------------------------------------------------------------------------
647
+ # RE-PREFILL: rebuild the whole KV from the clean x0 history
648
+ # ------------------------------------------------------------------------------------------
649
+ # After thousands of frames the buffer is not what a fresh forward over the same frames would
650
+ # produce: Z0's K has been rotated in place in bf16 every (gap_max-1) frames (SinkChaser), and
651
+ # every SUM row is a memcpy of K/V that were computed against whatever the prefix was when that
652
+ # frame ran. reprefill() throws the buffer away and replays [z0 | last W clean x0]: the z0 warm,
653
+ # then every stored frame as a clean t=0 write + commit. Ids are renumbered to 0..n, so the sink
654
+ # gap is back to 1 and abs_t stays bounded (no RoPE-table hard stop). Only under "recache": in
655
+ # "last_step_writes" the committed keys are noisy-input keys and a clean rebuild would be a
656
+ # different key kind.
657
+
658
+ @torch.no_grad()
659
+ def reprefill(self) -> dict:
660
+ if self._abs_t is None or self._z0_gauss is None:
661
+ raise RuntimeError("[summary-stream] reprefill() before start()")
662
+ if self.spec.cache_mode != "recache":
663
+ raise RuntimeError(f"[summary-stream] reprefill needs cache_mode='recache'; got {self.spec.cache_mode!r}")
664
+ hist = list(self._hist)
665
+ n = len(hist)
666
+ if n > int(self.W):
667
+ raise RuntimeError(f"[summary-stream] history {n} > W={self.W}")
668
+ if self.device.type == "cuda":
669
+ torch.cuda.synchronize(self.device)
670
+ t0 = time.perf_counter()
671
+ kv = self.visual_kv
672
+ if bool(getattr(kv, "_body_open", False)):
673
+ raise RuntimeError("[summary-stream] reprefill with an open (uncommitted) frame")
674
+ old_abs_t, old_rot = int(self._abs_t), self._chaser.describe()
675
+
676
+ # 1. Empty the buffer in place (same static tensors), recency on the empty buffer, fresh chaser.
677
+ kv.reset()
678
+ kv.enable_recency(self.spec.recency)
679
+ self.recency = kv.recency
680
+ self._chaser = self._new_chaser()
681
+
682
+ # 2. Replay the history into the empty buffer.
683
+ self._reprefill_sequential(hist)
684
+
685
+ # 3. Counters follow the rebuilt buffer.
686
+ self._n_body, self._abs_t, self._since_reprefill = n, n + 1, 0
687
+ self.n_reprefills += 1
688
+ expect_r = min(n, int(self.Y) + 1)
689
+ expect_s = min(max(0, n - (int(self.Y) + 1)), max(0, int(self.W) - int(self.Y)))
690
+ if int(kv.filled_r) != expect_r or int(kv.filled_s) != expect_s or int(kv.n_committed) != n or not kv.z0_written:
691
+ raise RuntimeError(
692
+ f"[summary-stream] reprefill bookkeeping: filled_r={kv.filled_r} (want {expect_r}) "
693
+ f"filled_s={kv.filled_s} (want {expect_s}) n_committed={kv.n_committed} (want {n}) z0_written={kv.z0_written}"
694
+ )
695
+ if self.device.type == "cuda":
696
+ torch.cuda.synchronize(self.device)
697
+ ms = (time.perf_counter() - t0) * 1e3
698
+ self.last_reprefill = {"frames": n, "ms": ms, "abs_t_before": old_abs_t, "abs_t_after": n + 1}
699
+ print(
700
+ f"[reprefill] rebuilt KV from z0 + {n} clean frames in {ms:.0f} ms | abs_t {old_abs_t} -> {n + 1} | "
701
+ f"{old_rot} -> {self._chaser.describe()} | {kv.describe()}",
702
+ flush=True,
703
+ )
704
+ return self.last_reprefill
705
+
706
+ def _reprefill_sequential(self, hist: list) -> None:
707
+ """z0 clean warm at id 0, then every stored frame as the clean t=0 write the recache pass makes (ids 1..n),
708
+ begin_frame / commit around each. n <= W so the sink never rotates inside the replay."""
709
+ kv = self.visual_kv
710
+ cond0 = self._cond(self._z0_fps, z0_focus_region=self.focus_region)
711
+ with self._autocast():
712
+ warm_z0_clean(self.generator, kv, cond0, self._z0_gauss.unsqueeze(1))
713
+ for i, (x0, action, fps) in enumerate(hist):
714
+ if self._chaser.rotation_before_frame(i):
715
+ raise RuntimeError(f"[summary-stream] reprefill: sink would rotate at replay frame {i} (n={len(hist)}, W={self.W})")
716
+ cond = self._cond(fps, self._action_to_device(action))
717
+ kv.begin_frame()
718
+ self._t_dev.fill_(0.0)
719
+ self._body_call(x0.unsqueeze(1), self._t_dev, cond, abs_t=i + 1)
720
+ kv.commit_current_frame()
721
+
722
+ def _chase_sink(self) -> None:
723
+ """Rotate the one Z0 slot before body frame i (``n_committed`` = frames already committed).
724
+
725
+ ``T = chaser.rotate(kv, freqs, i)`` with ``i`` the number of body frames committed so far.
726
+ ``T == 0`` means the gap has not reached ``sink_gap_max``.
727
+ """
728
+ T = self._chaser.rotate(self.visual_kv, self.model.rope_table, self._n_body)
729
+ if T:
730
+ print(f"[sink] T={T} ({self._chaser.describe()} n_body={self._n_body})", flush=True)
731
+
732
+ @torch.no_grad()
733
+ def start(self, z0_raw_bchw, *, fps, focus_region=FOCUS_DEFAULT) -> torch.Tensor:
734
+ """New game. GT-warm z0 (t=0 write, never generated) under this fps clock, SAE bootstrap
735
+ -> rgb0 ``[1,1,3,H,W]`` in ``[0,1]``. Next abs_t = 1.
736
+
737
+ ``focus_region``: ``FOCUS_DEFAULT`` = the ckpt's served region (spec); ``None`` = none this game; a Bool
738
+ ``[1, h, w]`` = the client's custom region for this game (the z0 warm AND every reprefill of it)."""
739
+ z0_raw = self._coerce_bchw(z0_raw_bchw, name="z0_raw")
740
+ if focus_region is FOCUS_DEFAULT:
741
+ self.focus_region = self.focus_region_default
742
+ else:
743
+ self.focus_region = _coerce_focus_region(focus_region, self.spec, self.device)
744
+ if self.sphere_mode == "all":
745
+ # A first frame that is not encoder output is put on the sphere before the KV
746
+ # warm. For an encoder z0 this is the identity up to eps.
747
+ z0_raw = sphere_project_raw(z0_raw.float(), cdim=1)
748
+ fps = _normalize_fps(fps)
749
+ self.reset()
750
+ self._rng = torch.Generator(device=self.device)
751
+ self._rng.manual_seed(int(torch.randint(0, 2**31 - 1, (1,)).item()))
752
+
753
+ cond = self._cond(fps, z0_focus_region=self.focus_region)
754
+ self._fps_logged = fps
755
+ z0 = self._gauss_in(z0_raw, which="z0")
756
+ with self._autocast():
757
+ warm_z0_clean(self.generator, self.visual_kv, cond, z0.unsqueeze(1))
758
+ with self._autocast(self.sae_dtype):
759
+ rgb0, self._sae_cache = self.sae.decode_bootstrap(self._gauss_out(z0, which="z0"))
760
+ self.last_x0, self._abs_t, self._n_body = z0, 1, 0
761
+ self._z0_gauss, self._z0_fps = z0.detach().float().clone(), fps
762
+ self._hist.clear()
763
+ print(
764
+ f"[kv-boundary] z0 warmed (GT, t=0, fps={fps}) {self.visual_kv.describe()} "
765
+ f"z0 mean={float(z0.mean()):.3f} std={float(z0.std()):.3f} "
766
+ f"focus_region={'off' if self.focus_region is None else f'{int(self.focus_region.sum().item())} tokens'}",
767
+ flush=True,
768
+ )
769
+ return self._rgb_out(rgb0, frames=1)
770
+
771
+ @torch.no_grad()
772
+ def step(self, action_b15, *, fps) -> torch.Tensor:
773
+ """One body latent frame under this fps clock (None/NaN = no clock) + action -> rgb4 ``[1,4,3,H,W]``."""
774
+ if self._abs_t is None or self._sae_cache is None:
775
+ raise RuntimeError("[summary-stream] step() before start()")
776
+ if not (isinstance(action_b15, torch.Tensor) and tuple(action_b15.shape) == (1, 1, 5)):
777
+ raise RuntimeError(f"[summary-stream] action_b15 must be [1,1,5]; got {getattr(action_b15, 'shape', None)}")
778
+ fps = _normalize_fps(fps)
779
+ every = int(self.reprefill_every or 0)
780
+ if every > 0 and self._since_reprefill >= every:
781
+ self.reprefill() # renumbers abs_t: read it after
782
+ self._since_reprefill += 1
783
+ t = int(self._abs_t)
784
+ if t >= int(self.model.rope_table.size(0)):
785
+ raise RuntimeError(
786
+ f"[summary-stream] HARD STOP: abs_t={t} >= RoPE table rows {int(self.model.rope_table.size(0))}; "
787
+ f"end the game, do not wrap"
788
+ )
789
+ self._chase_sink()
790
+ cond = self._cond(fps, self._action_to_device(action_b15))
791
+ if fps != self._fps_logged:
792
+ print(f"[fps] clock {self._fps_logged} -> {fps} from abs_t={t}", flush=True)
793
+ self._fps_logged = fps
794
+
795
+ x0 = self._timed("model", lambda: self._denoise_frame(cond, abs_t=t))
796
+ with self._autocast(self.sae_dtype):
797
+ rgb4, self._sae_cache = self._timed(
798
+ "sae", lambda: self._decode_steady()(self._gauss_out(x0[:, 0], which="rest"), self._sae_cache),
799
+ )
800
+ xf = x0[:, 0].float()
801
+ stats_dev = torch.stack([
802
+ xf.mean(), xf.std(), xf.abs().amax(),
803
+ torch.isfinite(xf).all().float(), torch.isnan(xf).sum().float(),
804
+ ])
805
+ x_mean, x_std, x_absmax, x_finite, x_nan = stats_dev.tolist()
806
+ if self.device.type == "cuda":
807
+ torch.cuda.synchronize(self.device)
808
+ ms = self._collect_ms()
809
+ if x_finite < 1.0:
810
+ raise RuntimeError(f"[summary-stream] x0 at abs_t={t} is not finite (nan={int(x_nan)})")
811
+
812
+ self._n_body += 1
813
+ # Closed frame (commit already ran; the next begin_frame has not). RAW holds min(n, Y+1)
814
+ # records. SUM receives a donation only once RAW is full, at the start of the frame that
815
+ # overwrites the oldest slot, so after n commits it holds min(max(0, n-(Y+1)), W-Y).
816
+ n = int(self._n_body)
817
+ expect_r = min(n, int(self.Y) + 1)
818
+ expect_s = min(max(0, n - (int(self.Y) + 1)), max(0, int(self.W) - int(self.Y)))
819
+ if int(self.visual_kv.filled_r) != expect_r:
820
+ raise RuntimeError(
821
+ f"[summary-stream] RAW holds {self.visual_kv.filled_r} records after frame {t} "
822
+ f"(n_body={n}, expected {expect_r})"
823
+ )
824
+ if int(self.visual_kv.filled_s) != expect_s:
825
+ raise RuntimeError(
826
+ f"[summary-stream] SUM holds {self.visual_kv.filled_s} summaries after frame {t} "
827
+ f"(n_body={n}, expected {expect_s})"
828
+ )
829
+ n_rgb = int(rgb4.size(1))
830
+ tot_ms = sum(ms.values())
831
+ self._peak_ema = tot_ms if self._peak_ema is None else 0.9 * self._peak_ema + 0.1 * tot_ms
832
+ print(
833
+ f"[perf] abs_t={t} " + " ".join(f"{k}={v:.1f}ms" for k, v in ms.items())
834
+ + f" total={tot_ms:.1f}ms"
835
+ + f" | peak model+sae={1000.0 / tot_ms:.1f} lat/s = {n_rgb * 1000.0 / tot_ms:.1f} rgb fps"
836
+ + f" (ema {n_rgb * 1000.0 / self._peak_ema:.1f})"
837
+ + f" | x0 mean={x_mean:.3f} std={x_std:.3f} absmax={x_absmax:.2f} {self._chaser.describe()}",
838
+ flush=True,
839
+ )
840
+ self.last_x0, self._abs_t, self.last_ms = xf, t + 1, dict(ms, total=tot_ms)
841
+ return self._rgb_out(rgb4, frames=4)
842
+
843
+ @torch.no_grad()
844
+ def reset(self) -> None:
845
+ """Between players (and inside start()). Zeros the one buffer in place; re-enables recency; new SinkChaser."""
846
+ kv = self.visual_kv
847
+ kv.reset()
848
+ kv.enable_recency(self.spec.recency)
849
+ self.recency = kv.recency
850
+ self._chaser = self._new_chaser()
851
+ if kv.filled_r or kv.filled_s or kv.n_committed or kv.z0_written:
852
+ raise RuntimeError("[summary-stream] reset left cache state behind")
853
+ self._rng = None
854
+ self._abs_t, self._n_body, self._sae_cache, self.last_x0 = None, 0, None, None
855
+ self._hist.clear()
856
+ self._z0_gauss = None
857
+ self._since_reprefill = 0
858
+ self.n_reprefills = 0
859
+ self.last_reprefill = None
860
+ self._fps_logged = "unset"
861
+ self._peak_ema = None
862
+ self._mode_log.clear()
863
+ print("[kv-boundary] reset visual=zeroed sae=dropped recency+chaser=rebuilt", flush=True)
864
+
865
+ @torch.no_grad()
866
+ def retarget(self, spec: StageSpec) -> None:
867
+ """Same generator / buffer geometry; new ckpt's timesteps, stats, cache_mode, sink gap, recency, focus."""
868
+ if not isinstance(spec, StageSpec):
869
+ raise TypeError(f"[summary-stream] retarget spec must be StageSpec; got {type(spec)}")
870
+ _check_spec_against_model(self.model, spec)
871
+ if (spec.h, spec.w) != (self.spec.h, self.spec.w):
872
+ raise RuntimeError(
873
+ f"[summary-stream] retarget: hw {spec.h}x{spec.w} != session {self.spec.h}x{self.spec.w}; "
874
+ f"release() and rebuild"
875
+ )
876
+ new_on = spec.recency is not None and bool(spec.recency.get("enabled", True))
877
+ old_on = self.recency is not None
878
+ if new_on != old_on and self._any_generator_compiled:
879
+ raise RuntimeError(
880
+ "[summary-stream] retarget: recency on<->off changes the compiled graph; release() and rebuild"
881
+ )
882
+ self.spec = spec
883
+ self.focus_region_default = self.focus_region = _coerce_focus_region(spec.focus_region, spec, self.device)
884
+ self._stats_dev = {
885
+ "z0": _stats_to_device(spec.stats_z0, self.device),
886
+ "rest": _stats_to_device(spec.stats_rest, self.device),
887
+ }
888
+ self._sqrt_ab, self._sqrt_om = _sched_tables(spec.samp, self.device)
889
+ self.reset()
890
+ print(
891
+ f"[summary-stream] retargeted cache_mode={spec.cache_mode} {sink_gaps_describe(spec.sink_gap_max)} "
892
+ f"{self._focus_region_desc()}",
893
+ flush=True,
894
+ )
895
+
896
+ @torch.no_grad()
897
+ def release(self) -> None:
898
+ """Drop every device tensor this session owns so a switch can allocate a different buffer."""
899
+ try:
900
+ self.reset()
901
+ except Exception:
902
+ pass
903
+ if getattr(self, "visual_kv", None) is not None:
904
+ self.visual_kv.release()
905
+ self.visual_kv = None
906
+ self.recency = None
907
+ self._sae_cache = None
908
+ self._stats_dev = {}
909
+ self._sqrt_ab = self._sqrt_om = None
910
+ self._abs_t_dev = self._t_dev = self._fps_dev = self._action_dev = self._action_pin = None
911
+ self._rgb_mean = self._rgb_std = None
912
+ self._ev = {}
913
+ print("[kv-boundary] released visual=dropped sae=dropped", flush=True)
914
+
915
+
916
+ def build_session_from_runtime(
917
+ generator,
918
+ sae_decoder,
919
+ spec,
920
+ device,
921
+ *,
922
+ rgb_hw,
923
+ forward_body_compiled=None,
924
+ decode_steady_compiled=None,
925
+ use_compiled_sae_in_steady_state: bool = True,
926
+ ) -> SummaryStreamSession:
927
+ """Server: one call per served checkpoint (startup + every switch), on the CUDA thread."""
928
+ return SummaryStreamSession(
929
+ generator=generator,
930
+ sae_decoder=sae_decoder,
931
+ spec=spec,
932
+ device=device,
933
+ rgb_hw=rgb_hw,
934
+ forward_body_compiled=forward_body_compiled,
935
+ decode_steady_compiled=decode_steady_compiled,
936
+ use_compiled_sae_in_steady_state=use_compiled_sae_in_steady_state,
937
+ )
summaryformer.py ADDED
@@ -0,0 +1,533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The world model: one transformer trunk over one stream of frames, two token kinds per frame.
2
+
3
+ record(t) = [ raw(t) : H*W tokens, embed(x_t) ] ++ [ sum(t) : X tokens, the learned init S ]
4
+
5
+ ``raw`` tokens are the frame's latent grid at full resolution. ``sum`` tokens are X learned, grid-free queries
6
+ appended to every frame; after the trunk they hold a compact summary of that frame. Memory is ONE key/value buffer
7
+ per block (``SummaryKVCache``): the last Y frames stay as whole records, older frames inside the window W survive
8
+ only as their X summary tokens, and frame 0 (``z0``, the seed image) is never evicted.
9
+
10
+ Generation is autoregressive, one frame per call, with no attention mask: a frame attends whatever the buffer
11
+ holds. ``_forward_kv_cached_z0`` runs the seed frame and ``_forward_kv_cached_z_rest`` one body frame. The seed
12
+ frame and the body frames each have their own token embed and their own output head (``embed_z0`` / ``head_z0``
13
+ vs ``embed_rest`` / ``head_rest``): the seed is a still image, the body is video. The public surface is
14
+ ``SummaryformerWrapper``.
15
+ """
16
+ import math
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+
21
+ from gta_streaming_kv_cache import SummaryKVCache, SummaryKVPlan
22
+ from summaryformer_utils.latent_head import LatentHead
23
+ from summaryformer_utils.rope import (
24
+ RopeFactors,
25
+ RopeTable,
26
+ SpatialBases,
27
+ build_rope_table,
28
+ build_summary_rope_factors,
29
+ build_visual_rope_factors,
30
+ clear_rope_spatial_base_cache,
31
+ get_rope_spatial_bases_cached,
32
+ spatial_bases_from_complex,
33
+ validate_level_planes_dead,
34
+ )
35
+ # Block classes + the attention-kernel switch live in transformer_block.py; re-exported so
36
+ # `from summaryformer import SelfAttention, set_streaming_attention_backend` works.
37
+ from summaryformer_utils.transformer_block import ( # noqa: F401
38
+ FILM_SLOTS,
39
+ FrameConditioning,
40
+ SelfAttention,
41
+ TransformerBlock,
42
+ get_streaming_attention_backend,
43
+ set_streaming_attention_backend,
44
+ )
45
+ from summaryformer_utils.z0_focus_mask import apply_z0_focus_region_embedding, coerce_z0_region
46
+
47
+ # The per-token additive "hold THIS subject" embedding on z0: ``z0_focus_region`` (Bool [B,hs,ws]) ADDS this
48
+ # embedding to the z0 tokens where True. A checkpoint may lack it (zeros == no marker).
49
+ Z0_FOCUS_REGION_EMBED_NAME = "z0_focus_embedding"
50
+ Z0_FOCUS_REGION_EMBED_ALLOWED_MISSING = (Z0_FOCUS_REGION_EMBED_NAME, f"model.{Z0_FOCUS_REGION_EMBED_NAME}")
51
+
52
+ __all__ = [
53
+ "Summaryformer",
54
+ "SelfAttention",
55
+ "TransformerBlock",
56
+ "set_streaming_attention_backend",
57
+ "get_streaming_attention_backend",
58
+ ]
59
+
60
+
61
+ class Summaryformer(nn.Module):
62
+ """One trunk, one frame per forward, one KV buffer per block.
63
+
64
+ ``summary_tokens`` (X) is the number of learned summary tokens appended to every frame.
65
+ ``raw_window_frames`` (Y) is how many past frames stay in memory as whole records.
66
+ ``summary_window_frames`` (W) is the total memory span in frames, raw window included (``W >= Y``).
67
+ """
68
+
69
+ # Autoencoder latent width. The seed frame and the body frames share it and share the /16 spatial grid;
70
+ # one body latent frame is 4 RGB frames.
71
+ LATENT_CHANNELS = 48
72
+ # Width of the sinusoidal features fed to the timestep MLP.
73
+ TIMESTEP_FEATURES = 256
74
+ # Action sentinel: a frame whose action vector contains this value has no action conditioning.
75
+ NO_ACTION = -69
76
+
77
+ def __init__(
78
+ self,
79
+ dim: int = 1280,
80
+ ffn_dim: int = 5120,
81
+ num_heads: int = 20,
82
+ num_layers: int = 28,
83
+ *,
84
+ summary_tokens: int,
85
+ raw_window_frames: int,
86
+ summary_window_frames: int,
87
+ ):
88
+ super().__init__()
89
+ self.dim = int(dim)
90
+ self.ffn_dim = int(ffn_dim)
91
+ self.num_heads = int(num_heads)
92
+ self.num_layers = int(num_layers)
93
+ self.summary_tokens = int(summary_tokens)
94
+ self.raw_window_frames = int(raw_window_frames)
95
+ self.summary_window_frames = int(summary_window_frames)
96
+ if self.num_layers < 1:
97
+ raise ValueError(f"num_layers must be >= 1; got {self.num_layers}.")
98
+ if self.dim % self.num_heads != 0 or (self.dim // self.num_heads) % 2 != 0:
99
+ raise ValueError(f"dim={self.dim} must split into {self.num_heads} heads of even width.")
100
+ if self.summary_tokens < 1:
101
+ raise ValueError(f"summary_tokens must be >= 1; got {self.summary_tokens}.")
102
+ if self.raw_window_frames < 0:
103
+ raise ValueError(f"raw_window_frames must be >= 0; got {self.raw_window_frames}.")
104
+ if self.summary_window_frames < 1:
105
+ raise ValueError(f"summary_window_frames must be >= 1; got {self.summary_window_frames}.")
106
+ dim, channels = self.dim, self.LATENT_CHANNELS
107
+
108
+ # Timestep -> embedding (also read by the output heads) -> the FiLM table every block reads
109
+ # ([FILM_SLOTS, dim]; transformer_block.py says which row does what).
110
+ self.timestep_mlp = nn.Sequential(nn.Linear(self.TIMESTEP_FEATURES, dim), nn.SiLU(), nn.Linear(dim, dim))
111
+ self.timestep_to_film = nn.Sequential(nn.SiLU(), nn.Linear(dim, dim * FILM_SLOTS))
112
+
113
+ self.blocks = nn.ModuleList(
114
+ [TransformerBlock(dim, ffn_dim, num_heads) for _ in range(self.num_layers)]
115
+ )
116
+
117
+ # Seed frame (z0) and body frames (z_rest): separate per-token embeds and separate read-outs.
118
+ # One token per latent cell, so the embed is a plain linear on the cell's channels.
119
+ self.embed_z0 = nn.Linear(channels, dim)
120
+ self.embed_rest = nn.Linear(channels, dim)
121
+ self.head_z0 = LatentHead(dim, channels)
122
+ self.head_rest = LatentHead(dim, channels)
123
+ # ADDED to the z0 tokens inside `z0_focus_region` (Bool [B,hs,ws]): "this is the subject to hold".
124
+ # Zeros add nothing, so a model that is never handed a region is unchanged.
125
+ self.z0_focus_embedding = nn.Parameter(torch.zeros(dim))
126
+ # The learned summary init: X grid-free tokens, appended to every frame as sum(t).
127
+ self.S = nn.Parameter(torch.zeros(self.summary_tokens, dim))
128
+
129
+ # Per-frame conditioning, each projected to its own FiLM table [FILM_SLOTS, dim] that every block adds
130
+ # through its own learned gate: the action, the grid's aspect ratio / size (separate MLPs for the seed
131
+ # frame and the body), and the frame rate.
132
+ self.action_proj = self._to_film_mlp(5, dim)
133
+ self.aspect_ratio_proj = self._to_film_mlp(2, dim)
134
+ self.aspect_ratio_proj_z0 = self._to_film_mlp(2, dim)
135
+ self.fps_embedder_mlp = nn.Sequential(nn.Linear(1, dim), nn.SiLU(), nn.Linear(dim, dim))
136
+ self.fps_embedder_outs = nn.Sequential(nn.SiLU(), nn.Linear(dim, dim * FILM_SLOTS))
137
+ # Frame rate is encoded relative to this anchor; fps == anchor is the neutral input (0.0).
138
+ self.fps_anchor = 12.0
139
+
140
+ # RoPE table. Plain tensors on purpose, not registered buffers: a buffer follows `module.to(dtype=...)`,
141
+ # and the table must stay complex / fp32 whatever dtype the weights are cast to. `_apply` moves it
142
+ # between devices.
143
+ self.set_rope_table(build_rope_table(dim // self.num_heads))
144
+ # Summary tokens carry their kind on two dead temporal planes (rope.LEVEL_PLANES). Fail at construction
145
+ # if the table ever makes those planes rotate for raw tokens.
146
+ validate_level_planes_dead(freqs=self.rope_table)
147
+
148
+ @staticmethod
149
+ def _to_film_mlp(in_dim: int, dim: int) -> nn.Module:
150
+ return nn.Sequential(
151
+ nn.Linear(in_dim, dim), nn.GELU(approximate='tanh'),
152
+ nn.Linear(dim, dim * FILM_SLOTS),
153
+ )
154
+
155
+ # -- RoPE table ---------------------------------------------------------------------------------------
156
+ def set_rope_table(self, table: torch.Tensor) -> None:
157
+ """Install the complex RoPE table ``[rows, head_dim / 2]`` and its fp32 cos / sin copies.
158
+
159
+ Drops the spatial-base memo: the bases are slices of the table.
160
+ """
161
+ self.rope_table = table
162
+ self.rope_cos = table.real.to(torch.float32)
163
+ self.rope_sin = table.imag.to(torch.float32)
164
+ # (h, w) -> raw SpatialBases. The dynamo-DISABLED base builder is a graph break; a hit here keeps
165
+ # `_record_rope` inside ONE compiled graph.
166
+ self._stage_spatial_memo: dict[tuple[int, int], SpatialBases] = {}
167
+
168
+ def _apply(self, fn, *args, **kwargs):
169
+ """Device moves carry the RoPE table along (it is not a buffer; see ``__init__``).
170
+
171
+ PyTorch calls ``_apply`` for every ``.to()`` / ``.cuda()``, also when it is called on a parent module.
172
+ The table keeps its own dtype: complex128 is narrowed to complex64, and a ``dtype=`` cast of the weights
173
+ never reaches it.
174
+ """
175
+ out = super()._apply(fn, *args, **kwargs)
176
+ device = self.embed_rest.weight.device
177
+ table = self.rope_table
178
+ dtype = torch.complex64 if table.dtype == torch.complex128 else table.dtype
179
+ if table.device != device or table.dtype != dtype:
180
+ table = table.to(device=device, dtype=dtype)
181
+ self.rope_table = table
182
+ self.rope_cos = table.real.to(device=device, dtype=torch.float32)
183
+ self.rope_sin = table.imag.to(device=device, dtype=torch.float32)
184
+ # The spatial-base cache is keyed by device and table storage: drop this device's entries and the memo.
185
+ clear_rope_spatial_base_cache(device=device)
186
+ self._stage_spatial_memo = {}
187
+ return out
188
+
189
+ @torch._dynamo.disable
190
+ def _get_rope_spatial_bases(
191
+ self,
192
+ *,
193
+ h_p: int,
194
+ w_p: int,
195
+ ) -> tuple[torch.Tensor, torch.Tensor]:
196
+ """
197
+ Get cached spatial RoPE bases on the model device:
198
+ - h_freqs_base: [1,1,H,1,Dh]
199
+ - w_freqs_base: [1,1,1,W,Dw]
200
+ """
201
+ if int(h_p) <= 0 or int(w_p) <= 0:
202
+ raise RuntimeError(
203
+ "RoPE spatial bases require positive runtime h_p/w_p."
204
+ )
205
+ device = self.embed_rest.weight.device
206
+ kw = dict(
207
+ freqs=self.rope_table, h_p=int(h_p), w_p=int(w_p),
208
+ dim=int(self.dim), num_heads=int(self.num_heads), device=device,
209
+ )
210
+ h_base, w_base = get_rope_spatial_bases_cached(**kw)
211
+ # A base first built under inference_mode is an inference tensor; rebuild it as a normal one.
212
+ if bool(h_base.is_inference()) or bool(w_base.is_inference()):
213
+ clear_rope_spatial_base_cache(device=device)
214
+ with torch.inference_mode(False):
215
+ h_base, w_base = get_rope_spatial_bases_cached(**kw)
216
+ return h_base, w_base
217
+
218
+ @torch._dynamo.disable
219
+ def _memo_stage_spatial_bases(self, h_p: int, w_p: int) -> SpatialBases:
220
+ """Slow path of `_stage_spatial_bases`: integer-lattice bases at the actual grid."""
221
+ key = (int(h_p), int(w_p))
222
+ raw_spatial = spatial_bases_from_complex(*self._get_rope_spatial_bases(h_p=key[0], w_p=key[1]))
223
+ validate_level_planes_dead(freqs=self.rope_table)
224
+ if not any(t.is_inference() for t in raw_spatial):
225
+ self._stage_spatial_memo[key] = raw_spatial
226
+ return raw_spatial
227
+
228
+ def _stage_spatial_bases(self, h_p: int, w_p: int) -> SpatialBases:
229
+ hit = self._stage_spatial_memo.get((int(h_p), int(w_p)))
230
+ if hit is not None:
231
+ return hit
232
+ return self._memo_stage_spatial_bases(int(h_p), int(w_p))
233
+
234
+ def _record_rope(self, *, frame_ids: torch.Tensor, h_p: int, w_p: int, n_raw: int) -> RopeFactors:
235
+ """RoPE for ONE frame's record ``[raw (h_p·w_p) | X summaries]`` at temporal id(s) ``frame_ids [B, 1]``.
236
+
237
+ raw : the frame's temporal id + the integer H/W lattice of the grid
238
+ summary : the same temporal id, no spatial position, + the level-plane marker
239
+ """
240
+ table = RopeTable(cos=self.rope_cos, sin=self.rope_sin)
241
+ raw = build_visual_rope_factors(
242
+ frame_ids=frame_ids, spatial=self._stage_spatial_bases(int(h_p), int(w_p)), table=table,
243
+ )
244
+ summary = build_summary_rope_factors(
245
+ frame_ids=frame_ids, summary_tokens=int(self.summary_tokens), table=table,
246
+ )
247
+ if int(raw.cos.size(1)) != int(n_raw) or int(summary.cos.size(1)) != int(self.summary_tokens):
248
+ raise RuntimeError(
249
+ f"record RoPE tape mismatch: raw {int(raw.cos.size(1))} vs {int(n_raw)}; "
250
+ f"summary {int(summary.cos.size(1))} vs X={int(self.summary_tokens)}."
251
+ )
252
+ return RopeFactors(
253
+ cos=torch.cat([raw.cos, summary.cos], dim=1),
254
+ sin=torch.cat([raw.sin, summary.sin], dim=1),
255
+ )
256
+
257
+ # -- conditioning -> FiLM tables ------------------------------------------------------------------------
258
+ def _timestep_features(self, t: torch.Tensor) -> torch.Tensor:
259
+ """``t [N]`` -> ``[N, TIMESTEP_FEATURES]``: cos | sin of ``t * 10000^(-i / half)``, in float64."""
260
+ half = self.TIMESTEP_FEATURES // 2
261
+ t = t.to(torch.float64)
262
+ rates = torch.pow(10000, -(torch.arange(half, device=t.device, dtype=torch.float64) / half))
263
+ angles = t.unsqueeze(1) * rates.unsqueeze(0)
264
+ return torch.cat([torch.cos(angles), torch.sin(angles)], dim=1)
265
+
266
+ def _timestep_film(self, t: torch.Tensor, *, dtype: torch.dtype) -> tuple[torch.Tensor, torch.Tensor]:
267
+ """One frame's timestep ``t`` (``[B]`` or ``[B, 1]``) -> ``(t_emb [B, dim], film [B, FILM_SLOTS, dim])``.
268
+
269
+ ``t_emb`` goes to the output head; ``film`` is the FiLM table every block reads. The two MLPs always run
270
+ in fp32, whatever dtype the trunk is in.
271
+ """
272
+ with torch.autocast(t.device.type, enabled=False):
273
+ t_emb = self.timestep_mlp(self._timestep_features(t.flatten()).to(torch.float32))
274
+ film = self.timestep_to_film(t_emb)
275
+ return t_emb.to(dtype=dtype), film.to(dtype=dtype).unflatten(1, (FILM_SLOTS, self.dim))
276
+
277
+ def _action_film(self, action: torch.Tensor | None, *, device: torch.device, dtype: torch.dtype) -> torch.Tensor | None:
278
+ """One frame's action ``[B, 1, 5]`` -> FiLM table ``[B, FILM_SLOTS, dim]`` (None when no action is given).
279
+
280
+ A sample whose action contains ``NO_ACTION`` gets an all-zero table: no action conditioning for it.
281
+ """
282
+ if action is None:
283
+ return None
284
+ if not (isinstance(action, torch.Tensor) and action.dim() == 3 and tuple(action.shape[1:]) == (1, 5)):
285
+ raise TypeError(
286
+ f"action_context must be a Tensor shaped [B, 1, 5] (one frame); got {getattr(action, 'shape', None)}."
287
+ )
288
+ with torch.autocast(device.type, enabled=False):
289
+ film = self.action_proj(action.to(torch.float32))
290
+ film = film.to(dtype=dtype, device=device).view(int(action.size(0)), FILM_SLOTS, self.dim)
291
+ has_action = ~(action == self.NO_ACTION).any(dim=-1) # [B, 1]
292
+ return film * has_action.to(dtype=dtype, device=device).unsqueeze(-1)
293
+
294
+ def _grid_film(self, proj: nn.Module, *, batch: int, h_p: int, w_p: int, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
295
+ """The frame's grid shape -> FiLM table ``[B, FILM_SLOTS, dim]`` through ``proj``.
296
+
297
+ The input is ``[log(W/H), log(H*W)]`` in tokens. ``proj`` is ``aspect_ratio_proj`` for body frames and
298
+ ``aspect_ratio_proj_z0`` for the seed frame.
299
+ """
300
+ b, h, w = int(batch), int(h_p), int(w_p)
301
+ if b <= 0 or h <= 0 or w <= 0:
302
+ raise RuntimeError(f"Invalid grid for conditioning: B={b}, H_p={h}, W_p={w}.")
303
+ geom = torch.tensor(
304
+ [math.log(float(w) / float(h)), math.log(float(h * w))],
305
+ device=device,
306
+ dtype=torch.float32,
307
+ ).view(1, 1, 2).expand(b, 1, 2)
308
+ with torch.autocast(device.type, enabled=False):
309
+ film = proj(geom)
310
+ return film.to(dtype=dtype, device=device).view(b, FILM_SLOTS, self.dim)
311
+
312
+ def _fps_film(self, fps: int | float | torch.Tensor, *, batch: int, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
313
+ """Frame rate -> FiLM table ``[B, FILM_SLOTS, dim]``.
314
+
315
+ The input is ``log(fps / fps_anchor)``: 0 at the anchor, symmetric for multiplicative changes (6 vs 24
316
+ around 12). ``fps`` is a number or a tensor (scalar, ``[1]``, ``[B]`` or ``[B, 1]``). A NaN entry means
317
+ that sample has no clock: its table is exactly zero. NaN is deliberate, it cannot be mistaken for a real
318
+ frame rate.
319
+ """
320
+ b = int(batch)
321
+ if isinstance(fps, torch.Tensor):
322
+ fps_t = fps.to(device=device, dtype=torch.float32)
323
+ if fps_t.dim() > 2 or (fps_t.dim() == 2 and int(fps_t.size(1)) != 1) or int(fps_t.numel()) not in (1, b):
324
+ raise RuntimeError(
325
+ f"fps tensor must be scalar, [1], [B], or [B,1]; got shape={tuple(fps_t.shape)} for B={b}."
326
+ )
327
+ fps_t = fps_t.reshape(-1).expand(b)
328
+ else:
329
+ fps_t = torch.full((b,), float(fps), device=device, dtype=torch.float32)
330
+ anchor = float(self.fps_anchor)
331
+ has_fps = ~torch.isnan(fps_t) # [B]
332
+ # Device-side assert: a Python `if torch.any(...)` here would be a host sync in every forward and a
333
+ # dynamo graph break.
334
+ torch._assert_async(
335
+ ~torch.any(has_fps & (fps_t <= 0)),
336
+ "fps must be positive (or NaN = no fps) for fps conditioning.",
337
+ )
338
+ # NaN samples run the MLP on the anchor (finite, no NaN propagation) and are zeroed after.
339
+ rel = torch.log(torch.where(has_fps, fps_t, torch.full_like(fps_t, anchor)) / anchor)
340
+ with torch.autocast(device.type, enabled=False):
341
+ film = self.fps_embedder_outs(self.fps_embedder_mlp(rel.view(b, 1, 1)))
342
+ film = film.to(dtype=dtype, device=device).view(b, FILM_SLOTS, self.dim)
343
+ return film * has_fps.to(film.dtype).view(b, 1, 1)
344
+
345
+ # -- tokens in, tokens out --------------------------------------------------------------------------------
346
+ def _embed_frame(self, x: torch.Tensor, embed: nn.Module, *, what: str) -> tuple[torch.Tensor, int, int]:
347
+ """One frame of latents ``[B, C, 1, H, W]`` -> raw tokens ``[B, H*W, dim]`` (row-major) and ``(H, W)``."""
348
+ c = int(self.LATENT_CHANNELS)
349
+ if not (isinstance(x, torch.Tensor) and x.dim() == 5 and int(x.size(1)) == c and int(x.size(2)) == 1):
350
+ raise TypeError(
351
+ f"{what} must be Tensor[B, C={c}, 1, H, W] (one frame); got shape={getattr(x, 'shape', None)}."
352
+ )
353
+ h_p, w_p = int(x.shape[3]), int(x.shape[4])
354
+ cells = x.to(device=embed.weight.device, dtype=embed.weight.dtype).flatten(2).transpose(1, 2) # [B, H*W, C]
355
+ return embed(cells), h_p, w_p
356
+
357
+ def _append_summary_tokens(self, x_raw: torch.Tensor) -> torch.Tensor:
358
+ """``[B, raw | X]``: the learned init ``S`` appended to one frame's raw tokens."""
359
+ B = int(x_raw.size(0))
360
+ x_sum = self.S.to(device=x_raw.device, dtype=x_raw.dtype).expand(B, int(self.summary_tokens), int(self.dim))
361
+ return torch.cat([x_raw, x_sum], dim=1)
362
+
363
+ def _decode_frame(self, raw_tokens: torch.Tensor, head: nn.Module, t_emb: torch.Tensor, h_p: int, w_p: int) -> torch.Tensor:
364
+ """A frame's raw tokens ``[B, H*W, dim]`` -> latents ``[B, C, 1, H, W]``. Summary tokens are not decoded."""
365
+ out = head(raw_tokens.contiguous(), t_emb)
366
+ B, c = int(out.size(0)), int(self.LATENT_CHANNELS)
367
+ return out.view(B, int(h_p), int(w_p), c).permute(0, 3, 1, 2).unsqueeze(2).contiguous()
368
+
369
+ def _resolve_visual_kv_cache(self, kv_cache) -> SummaryKVCache:
370
+ """A forward needs a built ``SummaryKVCache`` whose geometry is this model's."""
371
+ if not isinstance(kv_cache, SummaryKVCache):
372
+ raise TypeError(
373
+ "A forward needs a SummaryKVCache (use wrapper.new_visual_kv_cache())."
374
+ )
375
+ if kv_cache.layers is None:
376
+ raise RuntimeError("SummaryKVCache.build(...) must run before any KV forward.")
377
+ if int(len(kv_cache.layers)) != int(self.num_layers):
378
+ raise RuntimeError(
379
+ f"KV cache .layers has {int(len(kv_cache.layers))} slots; "
380
+ f"model num_layers={int(self.num_layers)}."
381
+ )
382
+ if (
383
+ int(kv_cache.summary_tokens) != int(self.summary_tokens)
384
+ or int(kv_cache.raw_window_frames) != int(self.raw_window_frames)
385
+ or int(kv_cache.summary_window_frames) != int(self.summary_window_frames)
386
+ ):
387
+ raise RuntimeError(
388
+ "KV cache geometry (X, Y, W)="
389
+ f"({kv_cache.summary_tokens}, {kv_cache.raw_window_frames}, {kv_cache.summary_window_frames}) "
390
+ f"!= model ({self.summary_tokens}, {self.raw_window_frames}, {self.summary_window_frames})."
391
+ )
392
+ return kv_cache
393
+
394
+ def _run_blocks(
395
+ self,
396
+ x: torch.Tensor,
397
+ cond: FrameConditioning,
398
+ *,
399
+ kv_cache: SummaryKVCache,
400
+ kv_plan: SummaryKVPlan,
401
+ visual_rope: RopeFactors,
402
+ ) -> torch.Tensor:
403
+ """All trunk blocks over ONE frame's record ``x [B, REC, dim]`` against the one-buffer cache."""
404
+ if int(x.size(1)) != int(kv_plan.query_tokens):
405
+ raise RuntimeError(
406
+ f"KV plan ({kv_plan.kind}) record width {int(kv_plan.query_tokens)} != x L={int(x.size(1))}."
407
+ )
408
+ if int(visual_rope.cos.size(1)) != int(x.size(1)):
409
+ raise RuntimeError(
410
+ f"RoPE tape L={int(visual_rope.cos.size(1))} != x L={int(x.size(1))}."
411
+ )
412
+ for block_index in range(int(self.num_layers)):
413
+ x = self.blocks[block_index](
414
+ x, cond, kv_cache=kv_cache.layers[block_index], kv_plan=kv_plan, visual_rope=visual_rope,
415
+ )
416
+ return x
417
+
418
+ # -- the two forwards -------------------------------------------------------------------------------------
419
+ def _forward_kv_cached_z_rest(
420
+ self,
421
+ x_rest: torch.Tensor,
422
+ t_rest: torch.Tensor,
423
+ kv_cache=None,
424
+ action_context: torch.Tensor | None = None,
425
+ fps: int | float | torch.Tensor | None = None,
426
+ absolute_start_frames: int | torch.Tensor | None = None,
427
+ ) -> torch.Tensor:
428
+ """ONE body frame through the one-buffer cache: record(t) = ``[embed_rest(x_t) | S]``.
429
+
430
+ The first call of a frame runs ``begin_frame`` (donation of the slot about to be overwritten; later
431
+ denoising passes of the same frame are a no-op). Every call writes the whole record at that RAW slot
432
+ and attends ``buffer[0 : end]``. The caller commits after the clean (t=0) pass with
433
+ ``kv_cache.commit_current_frame()`` (cursor advance, no copy).
434
+
435
+ ``x_rest [B, C, 1, H, W]``, ``t_rest [B, 1]``, ``absolute_start_frames``: this frame's temporal id
436
+ (>= 1; z0 is 0), int or 0-d int64 device tensor (compiled streaming form, which also switches the plan
437
+ to device ends). Returns the v-pred ``[B, C, 1, H, W]``.
438
+ """
439
+ cache = self._resolve_visual_kv_cache(kv_cache)
440
+ if absolute_start_frames is None:
441
+ raise TypeError("_forward_kv_cached_z_rest requires absolute_start_frames (this frame's temporal id >= 1).")
442
+ x_raw, h_p, w_p = self._embed_frame(x_rest, self.embed_rest, what="x_rest")
443
+ B, tf = int(x_raw.size(0)), int(x_raw.size(1))
444
+ device = x_raw.device
445
+ if not (isinstance(t_rest, torch.Tensor) and tuple(t_rest.shape) == (B, 1)):
446
+ raise TypeError(f"KV body forward expects t_rest Tensor[B={B}, 1]; got {getattr(t_rest, 'shape', None)}.")
447
+ if tf != int(cache.frame_tokens):
448
+ raise RuntimeError(
449
+ f"KV cache was built for frame_tokens={int(cache.frame_tokens)} but this frame has {tf} "
450
+ f"(grid {h_p}x{w_p}); rebuild the cache for this bucket."
451
+ )
452
+ x = self._append_summary_tokens(x_raw)
453
+
454
+ t_emb, time_film = self._timestep_film(t_rest, dtype=x.dtype)
455
+ cond = FrameConditioning(
456
+ time=time_film,
457
+ action=self._action_film(action_context, device=device, dtype=x.dtype),
458
+ grid=self._grid_film(self.aspect_ratio_proj, batch=B, h_p=h_p, w_p=w_p, device=device, dtype=x.dtype),
459
+ fps=self._fps_film(fps, batch=B, device=device, dtype=x.dtype) if fps is not None else None,
460
+ )
461
+
462
+ # Donation once per frame, before the write. plan_body calls begin_frame too; the second call is a no-op.
463
+ cache.begin_frame()
464
+ if isinstance(absolute_start_frames, torch.Tensor):
465
+ if absolute_start_frames.dim() != 0:
466
+ raise TypeError("absolute_start_frames tensor must be 0-d (one id for the whole batch).")
467
+ frame_ids = absolute_start_frames.to(device=device, dtype=torch.long).view(1, 1).expand(B, 1)
468
+ plan = cache.plan_body(device_ends=True)
469
+ else:
470
+ if int(absolute_start_frames) < 1:
471
+ raise ValueError(f"body frame id must be >= 1 (0 is z0); got {int(absolute_start_frames)}.")
472
+ frame_ids = torch.full((B, 1), int(absolute_start_frames), dtype=torch.long, device=device)
473
+ plan = cache.plan_body(device_ends=False)
474
+ visual_rope = self._record_rope(frame_ids=frame_ids, h_p=h_p, w_p=w_p, n_raw=tf)
475
+
476
+ x = self._run_blocks(x, cond, kv_cache=cache, kv_plan=plan, visual_rope=visual_rope)
477
+ return self._decode_frame(x[:, :tf], self.head_rest, t_emb, h_p, w_p)
478
+
479
+ def _forward_kv_cached_z0(
480
+ self,
481
+ x_z0: torch.Tensor,
482
+ t_z0: torch.Tensor,
483
+ *,
484
+ kv_cache,
485
+ action_context: torch.Tensor | None = None,
486
+ fps: int | float | torch.Tensor | None = None,
487
+ z0_focus_region: torch.Tensor | None = None,
488
+ ) -> torch.Tensor:
489
+ """The seed frame: record(0) = ``[embed_z0(x_z0) | S]`` at temporal id 0.
490
+
491
+ Every call writes record(0) into the Z0 slot and every query attends ``[0 : REC_z0]`` (raw(0) and sum(0)
492
+ share that key set). The caller marks the slot valid after the clean pass with ``kv_cache.note_z0_written()``.
493
+ ``action_context`` / ``fps`` are accepted for signature symmetry with the body pass and ignored (z0 has no
494
+ action / fps FiLM). ``z0_focus_region`` (Bool ``[B, H, W]``, None = off) adds the focus embedding to the
495
+ marked tokens. ``x_z0 [B, C, H, W]`` or ``[B, C, 1, H, W]``, ``t_z0 [B]``. Returns the v-pred
496
+ ``[B, C, 1, H, W]``.
497
+ """
498
+ cache = self._resolve_visual_kv_cache(kv_cache)
499
+ if not cache.has_sink:
500
+ raise RuntimeError("KV z0 forward on a cache built with z0_tokens=0 (no Z0 slot).")
501
+ z0_lat = x_z0.unsqueeze(2) if (isinstance(x_z0, torch.Tensor) and x_z0.dim() == 4) else x_z0
502
+ x_raw, z0_h_p, z0_w_p = self._embed_frame(z0_lat, self.embed_z0, what="x_z0")
503
+ B, z0_L = int(x_raw.size(0)), int(x_raw.size(1))
504
+ device = x_raw.device
505
+ if not (isinstance(t_z0, torch.Tensor) and tuple(t_z0.shape) == (B,)):
506
+ raise TypeError(f"KV z0 forward expects t_z0 Tensor[B={B}]; got {getattr(t_z0, 'shape', None)}.")
507
+ if z0_L != int(cache.z0_tokens):
508
+ raise RuntimeError(
509
+ f"KV cache was built for z0_tokens={int(cache.z0_tokens)} but this z0 has {z0_L} tokens "
510
+ f"(grid {z0_h_p}x{z0_w_p}); rebuild the cache for this bucket."
511
+ )
512
+ if z0_focus_region is not None:
513
+ region = coerce_z0_region(z0_focus_region, batch=B, height=z0_h_p, width=z0_w_p, device=x_raw.device)
514
+ x_raw = apply_z0_focus_region_embedding(x_raw, region, self.z0_focus_embedding)
515
+ x = self._append_summary_tokens(x_raw)
516
+
517
+ t_emb, time_film = self._timestep_film(t_z0, dtype=x.dtype)
518
+ cond = FrameConditioning(
519
+ time=time_film,
520
+ grid=self._grid_film(self.aspect_ratio_proj_z0, batch=B, h_p=z0_h_p, w_p=z0_w_p, device=device, dtype=x.dtype),
521
+ seed=True,
522
+ )
523
+ frame_ids = torch.zeros((B, 1), dtype=torch.long, device=device)
524
+ visual_rope = self._record_rope(frame_ids=frame_ids, h_p=z0_h_p, w_p=z0_w_p, n_raw=z0_L)
525
+
526
+ x = self._run_blocks(x, cond, kv_cache=cache, kv_plan=cache.plan_z0(), visual_rope=visual_rope)
527
+ return self._decode_frame(x[:, :z0_L], self.head_z0, t_emb, z0_h_p, z0_w_p)
528
+
529
+ def forward(self, *args, **kwargs):
530
+ raise TypeError(
531
+ "Summaryformer has no generic forward. Use _forward_kv_cached_z0 / _forward_kv_cached_z_rest "
532
+ "via SummaryformerWrapper (forward_z0 / forward_body)."
533
+ )
summaryformer_utils/fast_flash_kv.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The "flash" attention kernel: KV-cache reads via ``flash_attn_with_kvcache`` (CUDA, fp16 / bf16, forward only).
3
+
4
+ The KV-cached decode attends a short query (one frame's record, ``Lq = REC`` tokens) against the
5
+ one buffer's prefix. A general attention kernel is tuned for ``seqlen_q ~= seqlen_k`` and, in this
6
+ short-q / long-kv regime, both under-utilizes the GPU and forces a ``cat`` of ``[history, current]``
7
+ every step.
8
+
9
+ ``flash_attn_with_kvcache`` is purpose-built for exactly this:
10
+ * flash-decoding split-K -> saturates SMs even when ``Lq`` is small;
11
+ * reads the buffer in place -> no ``cat``, no ``[:, :end]`` materialize;
12
+ * ``cache_seqlens`` bounds the attended region to ``[0:end]`` so rows past ``end`` are ignored
13
+ while the prefix fills.
14
+
15
+ The current record is written by the caller at a CONSTANT slot offset, so the attended length is
16
+ an explicit scalar and never ``write_pos + Lq``. One buffer, one prefix. This module exposes that
17
+ PURE READ (``attend_buffer_prefix``): ``end`` as a Python int, or as a 0-d device tensor for the
18
+ compiled streaming form. No write helper.
19
+
20
+ There is no fallback in here: off CUDA, in fp32, or without ``flash_attn`` installed, the block uses the
21
+ other kernel (``rollout_flex_attention.py``) and never calls this module.
22
+
23
+ Layout contract (matches ``SelfAttention._attend_with_cache``):
24
+ q : ``[B, Lq, H, D]`` (the whole record, ALREADY RoPE'd)
25
+ k_buf/v_buf: the one buffer ``[B, cap, H, D]``
26
+ returns : ``[B, Lq, H, D]``
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import os
32
+
33
+ import torch
34
+
35
+ try:
36
+ from flash_attn import flash_attn_with_kvcache as _fa_kvcache_raw
37
+
38
+ _RAW_AVAILABLE = True
39
+ except Exception: # pragma: no cover - depends on the deployed flash_attn build
40
+ _fa_kvcache_raw = None
41
+ _RAW_AVAILABLE = False
42
+
43
+
44
+ def _register_flash_kvcache_ops():
45
+ """Register the two live flash reads. There is no write op and no third attend op.
46
+
47
+ ``lucid::flash_attn_kvcache_read`` takes ``cache_seqlens`` as a Python int.
48
+ ``lucid::flash_attn_kvcache_read_dev`` takes it as a device tensor. Both are pure reads
49
+ (``mutates_args=()``). ``flash_attn_with_kvcache`` itself has no fake kernel, so each op
50
+ carries an explicit fake that returns ``empty(q.shape)``.
51
+ """
52
+ # `flash_attn_with_kvcache` bottoms out in a pybind C extension
53
+ # (`flash_attn_2_cuda.fwd_kvcache`) with NO meta/fake kernel, so TorchDynamo can
54
+ # neither trace into it (it reads a data_ptr off a FakeTensor) nor `allow_in_graph`
55
+ # it (fake-tensor prop fails). The supported fix is to wrap it as an OPAQUE custom op
56
+ # with an explicit fake (meta) implementation: dynamo keeps it in-graph as one extern
57
+ # call, uses the fake for shape prop, and inductor calls the real kernel at runtime --
58
+ # no graph break, no fake-tensor crash.
59
+ #
60
+ # Declared functional (mutates_args=()): we only ever do a PURE READ here (k=None);
61
+ # the current frame's K/V is written into the buffer by a separate traced copy before
62
+ # this op, so the op itself does not mutate its inputs.
63
+ @torch.library.custom_op("lucid::flash_attn_kvcache_read", mutates_args=())
64
+ def read(
65
+ q: torch.Tensor,
66
+ k_cache: torch.Tensor,
67
+ v_cache: torch.Tensor,
68
+ cache_seqlens: int,
69
+ ) -> torch.Tensor:
70
+ return _fa_kvcache_raw(
71
+ q, k_cache, v_cache, cache_seqlens=int(cache_seqlens), causal=False
72
+ )
73
+
74
+ @read.register_fake
75
+ def _(q, k_cache, v_cache, cache_seqlens):
76
+ # flash_attn_with_kvcache returns a contiguous [B, Lq, H, D] tensor.
77
+ return torch.empty(q.shape, dtype=q.dtype, device=q.device)
78
+
79
+ # Same read with the attended length as a DEVICE tensor [B] int32 (the kernel's native form). The length
80
+ # is then a graph INPUT VALUE, not a Python int baked into the graph: one static graph serves every fill
81
+ # level of the prefix (``flash_kvcache_read_prefix_dev`` / ``lucid::flash_attn_kvcache_read_dev``).
82
+ @torch.library.custom_op("lucid::flash_attn_kvcache_read_dev", mutates_args=())
83
+ def read_dev(
84
+ q: torch.Tensor,
85
+ k_cache: torch.Tensor,
86
+ v_cache: torch.Tensor,
87
+ cache_seqlens: torch.Tensor,
88
+ ) -> torch.Tensor:
89
+ return _fa_kvcache_raw(q, k_cache, v_cache, cache_seqlens=cache_seqlens, causal=False)
90
+
91
+ @read_dev.register_fake
92
+ def _(q, k_cache, v_cache, cache_seqlens):
93
+ return torch.empty(q.shape, dtype=q.dtype, device=q.device)
94
+
95
+ return read, read_dev
96
+
97
+
98
+ FLASH_KVCACHE_AVAILABLE = False
99
+ _flash_kvcache_read = None
100
+ _flash_kvcache_read_dev = None
101
+
102
+ if _RAW_AVAILABLE:
103
+ try:
104
+ _flash_kvcache_read, _flash_kvcache_read_dev = _register_flash_kvcache_ops()
105
+ FLASH_KVCACHE_AVAILABLE = True
106
+ except Exception: # pragma: no cover - registration depends on torch version
107
+ _flash_kvcache_read = None
108
+ _flash_kvcache_read_dev = None
109
+ FLASH_KVCACHE_AVAILABLE = False
110
+
111
+ # A/B kill switch: set LUCID_DISABLE_FLASH_KVCACHE=1 to force FLASH_KVCACHE_AVAILABLE off so every
112
+ # read goes through the flex kernel without a code change.
113
+ if os.environ.get("LUCID_DISABLE_FLASH_KVCACHE", "0") == "1":
114
+ FLASH_KVCACHE_AVAILABLE = False
115
+
116
+
117
+ def attend_buffer_prefix(q: torch.Tensor, k_buf: torch.Tensor, v_buf: torch.Tensor, end: "int | torch.Tensor") -> torch.Tensor:
118
+ """One dense read of ``buffer[0 : end]`` on the ONE KV buffer. No write, no bias, no second call.
119
+
120
+ ``end`` is a Python int or a 0-d int64 device tensor (``SummaryKVCache.end_dev``). The length is
121
+ never ``write_pos + Lq``: the current record was already written at its constant slot.
122
+
123
+ * int ``end`` -> ``flash_kvcache_read_prefix`` (``lucid::flash_attn_kvcache_read``, ``cache_seqlens``
124
+ a Python int).
125
+ * device ``end`` -> ``flash_kvcache_read_prefix_dev`` (``lucid::flash_attn_kvcache_read_dev``).
126
+
127
+ Flash only: CUDA, fp16 / bf16, ``flash_attn`` installed; anything else raises. ``SelfAttention._attend_prefix``
128
+ checks that before calling and sends every other read (CPU, fp32, the ``"flex"`` backend, any read with the
129
+ recency bias attached) to the flex kernel instead.
130
+ """
131
+ if isinstance(end, torch.Tensor):
132
+ return flash_kvcache_read_prefix_dev(q, k_buf, v_buf, end)
133
+ return flash_kvcache_read_prefix(q, k_buf, v_buf, int(end))
134
+
135
+
136
+ def flash_kvcache_read_prefix(q: torch.Tensor, k_buf: torch.Tensor, v_buf: torch.Tensor, end: int) -> torch.Tensor:
137
+ """Flash-decoding read of the dense prefix ``[0 : end)`` of ONE buffer (no write; the caller has already
138
+ written the current record at its constant geometry offset, and compile orders that copy before this read
139
+ through the ``k_buf`` / ``v_buf`` data dependency).
140
+
141
+ ``end`` is a Python int (the eager form). Non-causal, ``1/sqrt(head_dim)`` scale, so it matches the flex
142
+ kernel numerically up to bf16 reduction order.
143
+ """
144
+ _require_flash(q)
145
+ return _flash_kvcache_read(q, k_buf, v_buf, int(end))
146
+
147
+
148
+ def flash_kvcache_read_prefix_dev(q: torch.Tensor, k_buf: torch.Tensor, v_buf: torch.Tensor, end: torch.Tensor) -> torch.Tensor:
149
+ """Same read with ``end`` a 0-d int64 DEVICE tensor (``SummaryKVCache.end_dev``): the
150
+ attended length is a graph INPUT VALUE, so ONE static graph (dynamic=False, cudagraph-able) serves the prefix fill
151
+ and the steady state.
152
+ """
153
+ if not (isinstance(end, torch.Tensor) and end.dim() == 0):
154
+ raise TypeError(f"end must be a 0-d device tensor; got {type(end)} shape={getattr(end, 'shape', None)}")
155
+ _require_flash(q)
156
+ return _flash_kvcache_read_dev(q, k_buf, v_buf, end.to(torch.int32).view(1).expand(int(q.size(0))).contiguous())
157
+
158
+
159
+ def _require_flash(q: torch.Tensor) -> None:
160
+ """The flash kernel exists only on CUDA in fp16 / bf16. No silent substitute: the caller picks flex instead."""
161
+ if not FLASH_KVCACHE_AVAILABLE:
162
+ raise RuntimeError("flash_attn_with_kvcache is unavailable (install flash_attn), or it was disabled; use the flex kernel.")
163
+ if not (q.is_cuda and q.dtype in (torch.float16, torch.bfloat16)):
164
+ raise RuntimeError(f"the flash kernel needs CUDA fp16 / bf16 queries; got {q.device} {q.dtype}. Use the flex kernel.")
summaryformer_utils/latent_head.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+
5
+ class LatentHead(nn.Module):
6
+ """Tokens of ONE frame -> that frame's latent channels, conditioned on its timestep embedding.
7
+
8
+ out = to_latent( LN(tokens) * (1 + scale) + shift ), (shift, scale) = shift_scale + t_emb
9
+
10
+ The model owns two of these: one for the seed frame (z0) and one for body frames (z_rest). They share
11
+ nothing; the seed frame is a still image and the body frames are video, so each gets its own read-out.
12
+ """
13
+
14
+ def __init__(self, dim: int, latent_channels: int):
15
+ super().__init__()
16
+ self.norm = nn.LayerNorm(dim, elementwise_affine=False)
17
+ # Row 0 = shift, row 1 = scale. Learned offsets on top of the timestep embedding.
18
+ self.shift_scale = nn.Parameter(torch.zeros(2, dim))
19
+ self.to_latent = nn.Linear(dim, latent_channels)
20
+
21
+ def forward(self, tokens: torch.Tensor, t_emb: torch.Tensor) -> torch.Tensor:
22
+ """``tokens [B, L, dim]`` (one frame, row-major), ``t_emb [B, dim]`` -> ``[B, L, latent_channels]``."""
23
+ if t_emb.dim() != 2 or int(t_emb.size(0)) != int(tokens.size(0)):
24
+ raise RuntimeError(
25
+ f"LatentHead wants one timestep embedding per sample: tokens {tuple(tokens.shape)}, "
26
+ f"t_emb {tuple(t_emb.shape)}."
27
+ )
28
+ film = self.shift_scale + t_emb.unsqueeze(1) # [B, 2, dim]
29
+ shift, scale = film[:, 0:1], film[:, 1:2] # [B, 1, dim] each, broadcast over the L tokens
30
+ return self.to_latent(self.norm(tokens) * (1 + scale) + shift)
summaryformer_utils/recency_bias.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Recency Forcing for the KV-cached model ("softmax recency decay").
2
+
3
+ Paper: Recency Forcing (arXiv 2609.19729). A buffer that evicts creates a discontinuity the first time it drops a
4
+ frame the model leaned on ("KV eviction mismatch"). The fix is an additive, NON-POSITIVE, content-free bias on the
5
+ pre-softmax logits of history keys as a function of the temporal distance
6
+ Δ = (current frame index) - (key's frame index):
7
+
8
+ softmax( q.k / sqrt(d) + B(Δ) ) B(Δ) <= 0, same for every head / layer / token of a frame
9
+
10
+ so a frame's attention weight is already ~0 by the time it reaches the eviction edge and dropping it changes nothing.
11
+ No parameters and no kernel shapes change (the paper's "BAR" head-dim+1 trick is only a FlashAttention workaround;
12
+ here the biased attend is a FlexAttention `score_mod`, on every device).
13
+
14
+ SHAPE (this module): flat, then a power ramp to a floor, in units of past frames::
15
+
16
+ B(Δ) = 0 Δ <= flat_until (recent: untouched)
17
+ B(Δ) = -beta * ((Δ - flat_until) / (decay_end - flat_until)) ** gamma
18
+ flat_until < Δ < decay_end
19
+ B(Δ) = -beta Δ >= decay_end (floor; exp(-beta) weight)
20
+
21
+ `decay_end` should be the served eviction distance, so w(evicted-next) = exp(-beta) ~ 0. Δ is the FRAME INDEX
22
+ distance, not the RoPE distance: the sink rotation does not touch it. The bias is Δ-only for now (the paper also
23
+ makes it depend on the denoising t; hook: make `recency_logit_bias` take t and call `refresh` per pass).
24
+
25
+ WHERE THE BIAS LIVES (one buffer): `RecencyBiasState` is owned by `SummaryKVCache`. It keeps
26
+ ONE fp32 tensor `token_bias[capacity]` over that whole buffer. `enable_recency` points `ring_start` at the SUM
27
+ region, `ring_frames` at the SUM slot count (W−Y), and `frame_tokens` at X. `refresh` writes B(Δ) only on those
28
+ SUM rows; Z0 and RAW stay 0, including the current record in `RAW[cursor_r]`. The cache attaches that same tensor
29
+ to every layer as `layer[RECENCY_BIAS_KEY]` next to `{"k","v"}`. One prefix read means every query — raw and
30
+ summary — sees it; zeros outside SUM are what leave Z0 and RAW keys unbiased. The compiled server reads the whole
31
+ buffer with keys `>= end` masked (`attend_full_buffer_with_kv_bias`). The live refresh is
32
+ `SummaryKVCache.begin_frame`: it writes `slot_frame` for the donated summary and calls `refresh`. In-place refresh
33
+ plus a persistent tensor is a static address for the compiled server (marked with the KV tensors).
34
+ """
35
+ from __future__ import annotations
36
+
37
+ import math
38
+ import os
39
+ from dataclasses import asdict, dataclass
40
+
41
+ import torch
42
+
43
+ RECENCY_BIAS_KEY = "recency_bias"
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class RecencyBiasConfig:
48
+ flat_until: int # Δ <= flat_until: no bias (past frames the world model may lean on freely)
49
+ decay_end: int # Δ >= decay_end: bias = -beta. Served eviction distance (a summary leaves SUM at Δ = W+1).
50
+ beta: float # bias magnitude at the floor, in logit units: the frame's weight is scaled by exp(-beta)
51
+ gamma: float = 2.0 # ramp power; 1 = linear in Δ, 2 = quadratic (gentle at flat_until, steep near decay_end)
52
+
53
+ def __post_init__(self):
54
+ if not (isinstance(self.flat_until, int) and isinstance(self.decay_end, int)):
55
+ raise TypeError(f"recency: flat_until / decay_end must be ints; got {self.flat_until!r} / {self.decay_end!r}")
56
+ if not 0 <= self.flat_until < self.decay_end:
57
+ raise ValueError(f"recency: need 0 <= flat_until < decay_end; got flat_until={self.flat_until} decay_end={self.decay_end}")
58
+ if not (math.isfinite(self.beta) and self.beta > 0.0):
59
+ raise ValueError(f"recency: beta must be finite and > 0; got {self.beta}")
60
+ if not (math.isfinite(self.gamma) and self.gamma > 0.0):
61
+ raise ValueError(f"recency: gamma must be finite and > 0; got {self.gamma}")
62
+
63
+ def to_dict(self) -> dict:
64
+ return asdict(self)
65
+
66
+ @staticmethod
67
+ def from_dict(d) -> "RecencyBiasConfig | None":
68
+ """None / falsy -> None (bias off). Accepts an existing config. Unknown keys are an error (a typo would
69
+ silently serve a different bias than the one asked for)."""
70
+ if d is None:
71
+ return None
72
+ if isinstance(d, RecencyBiasConfig):
73
+ return d
74
+ if not isinstance(d, dict):
75
+ raise TypeError(f"recency config must be a dict or None; got {type(d).__name__}")
76
+ if not bool(d.get("enabled", True)):
77
+ return None
78
+ keys = set(d) - {"enabled"}
79
+ want = {"flat_until", "decay_end", "beta", "gamma"}
80
+ if not keys <= want or not {"flat_until", "decay_end", "beta"} <= keys:
81
+ raise KeyError(f"recency config keys {sorted(keys)}; expected flat_until, decay_end, beta[, gamma]")
82
+ return RecencyBiasConfig(flat_until=int(d["flat_until"]), decay_end=int(d["decay_end"]),
83
+ beta=float(d["beta"]), gamma=float(d.get("gamma", 2.0)))
84
+
85
+ def describe(self) -> str:
86
+ w = [(dd, math.exp(float(recency_logit_bias(torch.tensor([dd]), self)[0]))) for dd in self.probe_deltas()]
87
+ return (f"recency(flat<= {self.flat_until}, ramp -> {self.decay_end}, beta={self.beta:g}, gamma={self.gamma:g}) "
88
+ f"weights " + " ".join(f"Δ{d}:{x:.3g}" for d, x in w))
89
+
90
+ def probe_deltas(self) -> list[int]:
91
+ a, b = self.flat_until, self.decay_end
92
+ return sorted({a, a + max(1, (b - a) // 4), (a + b) // 2, b - max(1, (b - a) // 4), b})
93
+
94
+
95
+ def recency_logit_bias(delta: torch.Tensor, cfg: RecencyBiasConfig) -> torch.Tensor:
96
+ """Δ (any int/float tensor, frames) -> additive logit bias, fp32, <= 0. Pure; Δ <= flat_until -> exactly 0."""
97
+ d = delta.to(torch.float32)
98
+ u = ((d - float(cfg.flat_until)) / float(cfg.decay_end - cfg.flat_until)).clamp_(0.0, 1.0)
99
+ return -float(cfg.beta) * u.pow(float(cfg.gamma))
100
+
101
+
102
+ class RecencyBiasState:
103
+ """Slot -> frame bookkeeping + the per-row logit bias of the one buffer's SUM region (see module docstring).
104
+
105
+ `token_bias` is allocated once (or handed in, so a KV pool keeps one static address across `build` calls) and only
106
+ ever updated IN PLACE. `ring_start` / `ring_frames` / `frame_tokens` describe the SUM region (X rows per slot,
107
+ W−Y slots), not a second buffer. `n_committed` is the index of the frame about to be denoised (body frame 0 =
108
+ first frame after z0); the frame in a SUM slot has Δ = n_committed - slot_frame. Rows outside
109
+ `[ring_start, ring_start + ring_frames * frame_tokens)` stay 0, so Z0 and RAW are unbiased.
110
+ """
111
+
112
+ def __init__(self, cfg: RecencyBiasConfig, *, ring_frames: int, ring_start: int, frame_tokens: int, capacity: int,
113
+ device: torch.device, token_bias: torch.Tensor | None = None):
114
+ self.cfg = cfg
115
+ self.ring_frames, self.ring_start, self.frame_tokens, self.capacity = int(ring_frames), int(ring_start), int(frame_tokens), int(capacity)
116
+ if self.ring_start + self.ring_frames * self.frame_tokens > self.capacity:
117
+ raise RuntimeError(f"recency: ring [{self.ring_start}, +{self.ring_frames}x{self.frame_tokens}) exceeds capacity {self.capacity}")
118
+ if token_bias is not None and (tuple(token_bias.shape) != (self.capacity,) or token_bias.dtype != torch.float32
119
+ or token_bias.device != torch.device(device)):
120
+ raise RuntimeError(f"recency: cannot reuse token_bias {tuple(token_bias.shape)}/{token_bias.dtype}/{token_bias.device} "
121
+ f"for capacity {self.capacity} on {device}")
122
+ self.token_bias = torch.zeros((self.capacity,), dtype=torch.float32, device=device) if token_bias is None else token_bias
123
+ self.slot_frame = torch.full((max(self.ring_frames, 1),), -1, dtype=torch.long, device=device)
124
+ self.n_committed = 0
125
+ self.reset()
126
+
127
+ def reset(self) -> None:
128
+ self.slot_frame.fill_(-1)
129
+ self.n_committed = 0
130
+ self.token_bias.zero_()
131
+
132
+ def refresh(self) -> None:
133
+ """Recompute `token_bias` in place for query frame `n_committed`.
134
+
135
+ Only `[ring_start, ring_end)` is written (the SUM region). Every other row, including Z0 and RAW, stays 0.
136
+ Empty slots (`slot_frame < 0`) are 0.
137
+ """
138
+ if self.ring_frames <= 0:
139
+ return
140
+ delta = float(self.n_committed) - self.slot_frame.to(torch.float32)
141
+ bias = torch.where(self.slot_frame >= 0, recency_logit_bias(delta, self.cfg), torch.zeros_like(delta))
142
+ s = self.ring_start
143
+ e = s + self.ring_frames * self.frame_tokens
144
+ self.token_bias[s:e].copy_(bias.repeat_interleave(self.frame_tokens))
145
+
146
+ def slot_bias(self) -> torch.Tensor:
147
+ """[ring_frames] fp32 bias per slot for the frame about to run (tests / logs)."""
148
+ if self.ring_frames <= 0:
149
+ return torch.zeros((0,), dtype=torch.float32)
150
+ return self.token_bias[self.ring_start:self.ring_start + self.ring_frames * self.frame_tokens].view(self.ring_frames, self.frame_tokens)[:, 0].detach().cpu()
151
+
152
+
153
+ # ------------------------------------------------------------------------------------------------------------------
154
+ # Biased attends. Layout everywhere: q/k/v [B, L, H, D]; bias fp32 [L_kv] (shared over batch, heads, query tokens).
155
+ # ------------------------------------------------------------------------------------------------------------------
156
+ # Built at import, NOT lazily. torch.compile(...) here is only a wrapper (nothing compiles until the first call), and
157
+ # a lazy `if _flex_compiled is None:` became a dynamo guard on this module global inside the server's compiled
158
+ # forward_body: the first trace saw None, the call set it, the guard failed, and frame 1 compiled twice. Same recipe
159
+ # as rollout_flex_attention: dynamic KV length (the prefix fills), no cudagraphs here (the compiled server wraps the
160
+ # whole forward and inlines this call).
161
+ from torch.nn.attention.flex_attention import flex_attention as _flex_attention_fn
162
+
163
+ _flex_compiled = torch.compile(_flex_attention_fn, mode="max-autotune-no-cudagraphs", dynamic=True)
164
+
165
+
166
+ def _flex():
167
+ return _flex_compiled
168
+
169
+
170
+ def _check_bias(bias: torch.Tensor, n_kv: int) -> None:
171
+ if not (isinstance(bias, torch.Tensor) and bias.dim() == 1 and bias.dtype == torch.float32):
172
+ raise TypeError(f"recency bias must be a 1-D fp32 tensor; got {getattr(bias, 'shape', None)} {getattr(bias, 'dtype', None)}")
173
+ if int(bias.numel()) != int(n_kv):
174
+ raise RuntimeError(f"recency bias covers {int(bias.numel())} keys, attended context has {int(n_kv)}")
175
+ if bias.requires_grad:
176
+ raise RuntimeError("recency bias must not require grad")
177
+
178
+
179
+ def attend_with_kv_bias(q: torch.Tensor, k_ctx: torch.Tensor, v_ctx: torch.Tensor, bias_kv: torch.Tensor) -> torch.Tensor:
180
+ """softmax(q k^T / sqrt(d) + bias_kv[j]) v over an already-built context (flex ``score_mod``)."""
181
+ _check_bias(bias_kv, k_ctx.size(1))
182
+ bias = bias_kv
183
+
184
+ def score_mod(score, b, h, q_idx, kv_idx):
185
+ _ = b, h, q_idx
186
+ return score + bias[kv_idx]
187
+
188
+ out = _flex()(query=q.transpose(1, 2), key=k_ctx.transpose(1, 2), value=v_ctx.transpose(1, 2), block_mask=None, score_mod=score_mod)
189
+ return out.transpose(1, 2)
190
+
191
+
192
+ # ------------------------------------------------------------------------------------------------------------------
193
+ # Serve-time full-buffer attend: route through inductor's flex DECODING kernel (split-KV flash decoding).
194
+ #
195
+ # WHY. Inductor's general flex kernel tiles queries (BLOCK_M=64) and launches one CTA per (head, q-tile); every CTA
196
+ # streams the WHOLE prefix for its head, so K/V are re-read once per tile. Inductor's decode kernel (flex_decoding.py)
197
+ # puts ALL queries of a KV head in ONE tile (BLOCK_M = next_pow2(Lq * G)), splits the KEY range over SPLIT_KV CTAs and
198
+ # merges the partial softmaxes, so K/V are read once per split. It only engages for Lq < 128 (and static B / H). A
199
+ # frame's record is REC = Tf + X queries, above that, so the general kernel would re-read the prefix. FOLD: view the Lq
200
+ # queries as G groups of Lq/G (G = smallest power of 2 with Lq/G < 128) and hand them to
201
+ # flex as G query heads per KV head (enable_gqa): query head h*G+g = tokens [g*Lq/G, (g+1)*Lq/G) of head h. The
202
+ # score_mod reads only kv_idx (bias + end mask), so the head remap changes nothing; the output is unfolded back.
203
+ # SPLIT_KV: inductor's default is num_SM // (B*Hkv) * 2; we target ~4 waves of CTAs. Fully-masked splits (all keys
204
+ # >= end) give m=-inf partials; the merge handles them (masked_rows).
205
+ # LUCID_RECENCY_FLEX_DECODE=0 -> the old general kernel (A/B); LUCID_FLEX_DECODE_SPLIT_KV=<int> pins the split count.
206
+ # ------------------------------------------------------------------------------------------------------------------
207
+ _FLEX_DECODE_WAVES = 4
208
+ _flex_static_compiled = None
209
+ # (cap, B, Hkv, Lq) -> SPLIT_KV. Filled by `prepare_flex_decode` (session build, outside any trace) or lazily on the
210
+ # first eager call. The hot attend only does a dict lookup: no device queries / env reads / prints inside a traced graph
211
+ # (the server inlines this function into ONE compiled forward; a print there is a graph break per block).
212
+ _SPLIT_KV_PLAN: dict[tuple[int, int, int, int], int] = {}
213
+
214
+
215
+ def _flex_static():
216
+ """Static-shape compile for the full-buffer form: the buffer is always the whole capacity, so there is nothing
217
+ dynamic, and the decode lowering needs static B / H to pick itself (dynamic=True would hide them as symbols)."""
218
+ global _flex_static_compiled
219
+ if _flex_static_compiled is None:
220
+ from torch.nn.attention.flex_attention import flex_attention
221
+ _flex_static_compiled = torch.compile(flex_attention, mode="max-autotune-no-cudagraphs", dynamic=False)
222
+ return _flex_static_compiled
223
+
224
+
225
+ def _flex_supports_backend_option() -> bool:
226
+ """torch >= 2.10-ish: kernel_options["BACKEND"] = "TRITON_DECODE" FORCES the decode lowering (and raises with the
227
+ reason when it cannot be used) instead of silently falling back to the general kernel."""
228
+ try:
229
+ from torch._inductor.kernel.flex import flex_attention as _fa
230
+ return hasattr(_fa, "_sanitize_kernel_options_for_triton")
231
+ except Exception:
232
+ return False
233
+
234
+
235
+ _FLEX_HAS_BACKEND_OPTION = _flex_supports_backend_option()
236
+ # ON only where the decode lowering can be FORCED (torch with kernel_options["BACKEND"]). On older torch (2.9: the
237
+ # heuristic quietly rejects the folded serve shape and runs the general kernel) the fold buys nothing, so the read
238
+ # stays on the general kernel. LUCID_RECENCY_FLEX_DECODE=1 forces the fold on anyway, =0 off. CUDA only.
239
+ _env_fd = os.environ.get("LUCID_RECENCY_FLEX_DECODE", "auto").strip().lower()
240
+ _FLEX_DECODE_ENABLED = (_FLEX_HAS_BACKEND_OPTION if _env_fd in ("", "auto") else _env_fd not in ("0", "off", "false"))
241
+
242
+
243
+ def decode_kernel_options(split: int) -> dict:
244
+ opts: dict = {"SPLIT_KV": int(split)}
245
+ if _FLEX_HAS_BACKEND_OPTION:
246
+ opts["BACKEND"] = "TRITON_DECODE"
247
+ return opts
248
+
249
+
250
+ def decode_fold_groups(lq: int) -> int | None:
251
+ """G (power of 2) so that lq / G < 128 and G | lq; None = the frame cannot be folded (odd token counts >= 128)."""
252
+ g = 1
253
+ while lq // g >= 128:
254
+ g *= 2
255
+ return g if lq % g == 0 else None
256
+
257
+
258
+ def decode_split_kv(cap: int, batch: int, kv_heads: int, device: torch.device) -> int:
259
+ env = os.environ.get("LUCID_FLEX_DECODE_SPLIT_KV", "").strip()
260
+ if env:
261
+ return max(1, int(env))
262
+ n_sm = int(torch.cuda.get_device_properties(device).multi_processor_count)
263
+ s = math.ceil(_FLEX_DECODE_WAVES * n_sm / max(1, batch * kv_heads))
264
+ return max(1, min(s, max(1, cap // 256))) # keep >= 4 KV blocks of 64 per split
265
+
266
+
267
+ def prepare_flex_decode(*, cap: int, batch: int, kv_heads: int, frame_tokens: int, device: torch.device) -> str:
268
+ """Plan the decode fold for one buffer geometry (call at session build, before the first forward / compile) and
269
+ return a one-line description for the log. Idempotent."""
270
+ if not (_FLEX_DECODE_ENABLED and device.type == "cuda"):
271
+ if device.type != "cuda":
272
+ return f"general flex kernel (decode fold is CUDA only; device is {device.type})"
273
+ return ("general flex kernel (decode fold OFF: LUCID_RECENCY_FLEX_DECODE=0)" if _FLEX_HAS_BACKEND_OPTION else
274
+ f"general flex kernel (decode fold OFF: torch {torch.__version__} cannot force the decode lowering; LUCID_RECENCY_FLEX_DECODE=1 to try anyway)")
275
+ g = decode_fold_groups(int(frame_tokens))
276
+ if g is None:
277
+ return f"general flex kernel (Lq={frame_tokens} has no power-of-2 fold below 128 queries)"
278
+ key = (int(cap), int(batch), int(kv_heads), int(frame_tokens))
279
+ split = _SPLIT_KV_PLAN.get(key)
280
+ if split is None:
281
+ split = _SPLIT_KV_PLAN[key] = decode_split_kv(int(cap), int(batch), int(kv_heads), device)
282
+ return (f"flex DECODING: Lq={frame_tokens} folded as {g} x {frame_tokens // g} query groups per KV head (one {_next_pow2(frame_tokens)}-row "
283
+ f"tile), B*Hkv={batch * kv_heads} x SPLIT_KV={split} CTAs over cap={cap} keys ({cap // split} keys per split), K/V read once per split"
284
+ f"{' [BACKEND=TRITON_DECODE forced]' if _FLEX_HAS_BACKEND_OPTION else ' [torch too old to force the decode backend: inductor heuristics decide]'}")
285
+
286
+
287
+ def _next_pow2(n: int) -> int:
288
+ return 1 << max(0, int(n) - 1).bit_length()
289
+
290
+
291
+ def _fold_queries(q_blhd: torch.Tensor, g: int) -> torch.Tensor:
292
+ """[B, L, H, D] -> [B, H*G, L/G, D]: query head h*G + k holds tokens [k*L/G, (k+1)*L/G) of head h."""
293
+ b, l, h, d = q_blhd.shape
294
+ return q_blhd.view(b, g, l // g, h, d).permute(0, 3, 1, 2, 4).reshape(b, h * g, l // g, d)
295
+
296
+
297
+ def _unfold_queries(o_bhgld: torch.Tensor, g: int) -> torch.Tensor:
298
+ """[B, H*G, L/G, D] -> [B, L, H, D] (inverse of _fold_queries)."""
299
+ b, hg, lg, d = o_bhgld.shape
300
+ return o_bhgld.view(b, hg // g, g, lg, d).permute(0, 2, 3, 1, 4).reshape(b, g * lg, hg // g, d)
301
+
302
+
303
+ def attend_full_buffer_with_kv_bias(q: torch.Tensor, k_buf: torch.Tensor, v_buf: torch.Tensor, bias_buf: torch.Tensor,
304
+ end: torch.Tensor) -> torch.Tensor:
305
+ """Streaming static-compile form: attend the WHOLE buffer, keys >= `end` (0-d device int) masked to -inf, plus the
306
+ per-row bias. No Python int of the fill level enters the graph (same contract as
307
+ ``fast_flash_kv.flash_kvcache_read_prefix_dev``).
308
+ On CUDA this goes through the flex DECODING kernel via the query fold described above; elsewhere the general
309
+ flex kernel."""
310
+ _check_bias(bias_buf, k_buf.size(1))
311
+ if not (isinstance(end, torch.Tensor) and end.dim() == 0):
312
+ raise TypeError("end must be a 0-d device tensor")
313
+ cap = int(k_buf.size(1))
314
+ bias, end_l = bias_buf, end.to(torch.long)
315
+
316
+ def score_mod(score, b, h, q_idx, kv_idx):
317
+ _ = b, h, q_idx
318
+ return torch.where(kv_idx < end_l, score + bias[kv_idx], torch.full_like(score, float("-inf")))
319
+
320
+ g = decode_fold_groups(int(q.size(1))) if (_FLEX_DECODE_ENABLED and q.is_cuda) else None
321
+ if g is None:
322
+ out = _flex()(query=q.transpose(1, 2), key=k_buf.transpose(1, 2), value=v_buf.transpose(1, 2), block_mask=None, score_mod=score_mod)
323
+ return out.transpose(1, 2)
324
+ key = (cap, int(q.size(0)), int(q.size(2)), int(q.size(1)))
325
+ split = _SPLIT_KV_PLAN.get(key)
326
+ if split is None: # eager / test call without prepare_flex_decode; the server prepares at build, outside the trace
327
+ split = _SPLIT_KV_PLAN[key] = decode_split_kv(cap, int(q.size(0)), int(q.size(2)), q.device)
328
+ out = _flex_static()(query=_fold_queries(q, g), key=k_buf.transpose(1, 2), value=v_buf.transpose(1, 2), block_mask=None,
329
+ score_mod=score_mod, enable_gqa=True, kernel_options=decode_kernel_options(split))
330
+ return _unfold_queries(out, g)
summaryformer_utils/rollout_flex_attention.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The "flex" attention kernel: FlexAttention reads over the KV buffer. Runs on any device and dtype, and is what
3
+ every read uses unless the flash kernel (``fast_flash_kv.py``) is selected and available.
4
+
5
+ Layout contract (matches ``SelfAttention._attend_with_cache``):
6
+ q, k, v : ``[B, L, H, D]`` (batch, seq, heads, head_dim)
7
+ returns : ``[B, Lq, H, D]``
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import torch
13
+ from torch.nn.attention.flex_attention import flex_attention
14
+
15
+
16
+ # Compile once. dynamic=True: Lq (current-frame query tokens) is fixed, but the
17
+ # attended KV length grows while the buffer fills before saturating at
18
+ # capacity, so the kernel must tolerate a changing KV_LEN without recompiling
19
+ # every frame. No cudagraphs here: a compiled server wraps the whole forward.
20
+ _flex_attention_compiled = torch.compile(
21
+ flex_attention, mode="max-autotune-no-cudagraphs", dynamic=True
22
+ )
23
+
24
+
25
+ def flex_attend_full(
26
+ q: torch.Tensor,
27
+ k: torch.Tensor,
28
+ v: torch.Tensor,
29
+ ) -> torch.Tensor:
30
+ """Plain (un-masked) FlexAttention over an already-built KV context.
31
+
32
+ ``q, k, v`` are ``[B, L, H, D]`` where ``k``/``v`` already span the full attended
33
+ context ``[0:current_end]`` of the one buffer. No mask / no ``score_mod`` -- the
34
+ causal window is enforced by the cache geometry (we only ever pass valid history +
35
+ the current frame), so this attends densely over exactly those keys, the same key
36
+ set the flash kernel reads. No cudagraphs, dynamic KV_LEN.
37
+ """
38
+ out = _flex_attention_compiled(
39
+ query=q.transpose(1, 2),
40
+ key=k.transpose(1, 2),
41
+ value=v.transpose(1, 2),
42
+ block_mask=None,
43
+ score_mod=None,
44
+ )
45
+ return out.transpose(1, 2)
46
+
47
+
48
+ def flex_attend_full_dev(q: torch.Tensor, k_buf: torch.Tensor, v_buf: torch.Tensor, end: torch.Tensor) -> torch.Tensor:
49
+ """``flex_attend_full`` over the WHOLE buffer with keys ``>= end`` (0-d device int) masked to -inf.
50
+
51
+ The compiled-streaming form of the unbiased prefix read for the "flex" backend: no Python int of the fill
52
+ level enters the graph, so one static graph serves every fill level (mirrors
53
+ ``fast_flash_kv.flash_kvcache_read_prefix_dev`` and ``recency_bias.attend_full_buffer_with_kv_bias``).
54
+ ``q, k_buf, v_buf`` are ``[B, L, H, D]``; any dtype flex supports (fp32 included, unlike the flash kernel).
55
+ """
56
+ if not (isinstance(end, torch.Tensor) and end.dim() == 0):
57
+ raise TypeError(f"end must be a 0-d device tensor; got {type(end)} shape={getattr(end, 'shape', None)}")
58
+ end_l = end.to(torch.long)
59
+
60
+ def score_mod(score, b, h, q_idx, kv_idx):
61
+ _ = b, h, q_idx
62
+ return torch.where(kv_idx < end_l, score, torch.full_like(score, float("-inf")))
63
+
64
+ out = _flex_attention_compiled(
65
+ query=q.transpose(1, 2),
66
+ key=k_buf.transpose(1, 2),
67
+ value=v_buf.transpose(1, 2),
68
+ block_mask=None,
69
+ score_mod=score_mod,
70
+ )
71
+ return out.transpose(1, 2)
summaryformer_utils/rope.py ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Rotary positions for the world model: one T | H | W table, plus a "level" axis that marks summary tokens.
2
+
3
+ Credit. The 3-D rotary scheme used here (one complex table with T | H | W bands, each axis rotating its own slice of
4
+ every attention head's Q and K) is adapted from Wan2.1 (https://github.com/Wan-Video/Wan2.1, Apache-2.0,
5
+ Copyright 2024-2025 The Alibaba Wan Team Authors). Changed from upstream: theta=64 on the two spatial bands, real
6
+ (cos, sin) tapes built once per forward and gathered by absolute frame id, one fused Q/K apply, and the level planes
7
+ described below, which upstream does not have.
8
+ """
9
+ import math
10
+ from typing import NamedTuple
11
+
12
+ import torch
13
+ import torch._dynamo
14
+
15
+ # One frequency table. Tokens differ only by temporal id and the current
16
+ # spatial coordinate system (the integer H/W lattice of the full-res stream).
17
+ # z0 is t=0. z_rest is t>=1.
18
+ #
19
+ # ---------------------------------------------------------------------------
20
+ # Band layout (head_dim=64 -> 32 complex planes, see build_rope_table):
21
+ #
22
+ # plane index : 0 .. 11 | 12 .. 21 | 22 .. 31
23
+ # band : T (12) | H (10) | W (10)
24
+ # theta : 10000 | 64 | 64
25
+ #
26
+ # - temporal: theta=10000. Absolute frame ids keep growing during long
27
+ # streaming, so the low-frequency headroom is actually used.
28
+ # - H/W: theta=64. Tokens sit on the autoencoder's /16 grid (typically
29
+ # ~20-36 cells per axis). At theta=10000 the slowest spatial bands barely
30
+ # rotate across that grid; theta=64 keeps every band geometrically spread.
31
+ #
32
+ # Summary tokens: X grid-free learned queries per frame.
33
+ # Temporal band as raw (same-frame table gather); H/W identity (spatial
34
+ # position 0: cos 1, sin 0); level planes (10, 11) get the summary-vs-raw
35
+ # kind marker (pi/2) via apply_level_rotation so "summary at t" != "pixel
36
+ # at t". Slot identity is the learned init S, not a position — every X
37
+ # token of a frame is rotation-identical. Builder: build_summary_rope_factors()
38
+ # — table gather + elementwise, no per-token Python loop. The model runs
39
+ # validate_level_planes_dead() once at build time.
40
+ #
41
+ # The two lowest temporal frequencies are unused for any range this model
42
+ # can see: omega_10 ~= 4.6e-4 rad/frame and omega_11 ~= 2.2e-4 rotate by
43
+ # only 0.48 / 0.22 rad across the whole 1024-row table. Every raw token
44
+ # therefore has ~identity rotation on planes 10 and 11. Summary tokens get
45
+ # an exact extra rotation of pi/2 on those two planes: a dedicated,
46
+ # collision-free 4-real-dim-per-head subspace that says "this key is a
47
+ # summary", with > 1.07 rad of margin at worst (worst raw key: z0 seen
48
+ # from frame 1023, |drift| < 0.5 rad).
49
+ # -> apply_level_rotation(), guarded by validate_level_planes_dead()
50
+ #
51
+ # Why this is safe for the T/H/W formulation:
52
+ # * H and W bands are untouched for raw tokens.
53
+ # * Temporal planes 0..9 are untouched, so every temporal relation between
54
+ # raw tokens is preserved. Planes 10/11 are ~identity for raw tokens
55
+ # (|rotation| < 0.5 rad over the table); rotating them for summaries
56
+ # only adds a signal on dims that carry no position.
57
+ # * Nothing is stolen from the table itself: raw tokens still index the
58
+ # same 1024x32 table. The level rotation is applied to the (cos, sin)
59
+ # factors of summary tokens only, after the normal build.
60
+ # * validate_level_planes_dead() fails at build time if anyone changes
61
+ # theta / head_dim / table length such that the level planes stop being
62
+ # dead. Do not weaken it.
63
+ # ---------------------------------------------------------------------------
64
+
65
+ ROPE_TABLE_ROWS: int = 1024
66
+ TEMPORAL_THETA: float = 10000.0
67
+ SPATIAL_THETA: float = 64.0
68
+
69
+ # Level axis: complex planes (inside the TEMPORAL band) that carry token kind
70
+ # (summary vs raw), not a spatial or temporal coordinate.
71
+ LEVEL_PLANES: tuple[int, ...] = (10, 11)
72
+ # Rotation given to SUMMARY tokens on LEVEL_PLANES. pi/2 (not pi): with a quarter
73
+ # turn the same query can read Re() on raw keys and Im() on summary keys, so it
74
+ # can weight the two kinds independently; pi would only negate, a weaker one-bit flag.
75
+ LEVEL_ANGLE_SUMMARY: float = math.pi / 2
76
+ # A level plane is "dead" if |pos * omega| stays below this over the whole table.
77
+ # 0.5 rad leaves >= 1.07 rad (cos 0.48) between summary and raw keys at worst case.
78
+ LEVEL_DEAD_MAX_RAD: float = 0.5
79
+
80
+
81
+ class RopeFactors(NamedTuple):
82
+ """Block-invariant rotary factors for one visual prefix. Dynamo-friendly."""
83
+
84
+ cos: torch.Tensor # [B, real_visual_L, 1, D]
85
+ sin: torch.Tensor
86
+
87
+
88
+ class SpatialBases(NamedTuple):
89
+ """Integer-grid H/W bases for the full-res raw stream."""
90
+
91
+ h_cos: torch.Tensor # [1, 1, H, 1, Dh]
92
+ h_sin: torch.Tensor
93
+ w_cos: torch.Tensor # [1, 1, 1, W, Dw]
94
+ w_sin: torch.Tensor
95
+
96
+
97
+ class RopeTable(NamedTuple):
98
+ """Real view of the single T/H/W frequency table."""
99
+
100
+ cos: torch.Tensor # [T_max, D_complex]
101
+ sin: torch.Tensor
102
+
103
+
104
+ def _axis_phases(rows: int, real_dims: int, theta: float) -> torch.Tensor:
105
+ """One axis of the table: ``polar(1, pos * theta^(-2i/real_dims))``, complex128 ``[rows, real_dims / 2]``."""
106
+ real_dims = int(real_dims)
107
+ if real_dims <= 0 or real_dims % 2 != 0:
108
+ raise ValueError(f"a RoPE band needs a positive even number of real dims; got {real_dims}")
109
+ exponent = torch.arange(0, real_dims, 2).to(torch.float64).div(real_dims)
110
+ angle = torch.outer(torch.arange(int(rows)), 1.0 / torch.pow(theta, exponent))
111
+ return torch.polar(torch.ones_like(angle), angle)
112
+
113
+
114
+ def build_rope_table(head_dim: int, rows: int = ROPE_TABLE_ROWS) -> torch.Tensor:
115
+ """The one complex table ``[rows, head_dim / 2]``, bands T | H | W (head_dim=64 -> 12 | 10 | 10 planes).
116
+
117
+ Each row depends on its own position only, so a longer table is row-for-row identical on the shared rows.
118
+ """
119
+ head_dim = int(head_dim)
120
+ if head_dim <= 0 or head_dim % 2 != 0:
121
+ raise ValueError(f"head_dim must be positive and even; got {head_dim}")
122
+ spatial = 2 * (head_dim // 6)
123
+ temporal = head_dim - 2 * spatial
124
+ return torch.cat(
125
+ [
126
+ _axis_phases(rows, temporal, TEMPORAL_THETA),
127
+ _axis_phases(rows, spatial, SPATIAL_THETA),
128
+ _axis_phases(rows, spatial, SPATIAL_THETA),
129
+ ],
130
+ dim=1,
131
+ )
132
+
133
+
134
+ _ROPE_SPATIAL_BASE_CACHE: dict[tuple, tuple[torch.Tensor, torch.Tensor]] = {}
135
+
136
+
137
+ def _device_key(device: torch.device | str) -> str:
138
+ d = torch.device(device)
139
+ if d.type == "cuda":
140
+ return f"cuda:{0 if d.index is None else int(d.index)}"
141
+ return str(d)
142
+
143
+
144
+ def _freqs_table_id(freqs: torch.Tensor) -> tuple[int, int, str, int, int]:
145
+ """Identity for a RoPE frequency table (shape alone is not enough)."""
146
+ if not isinstance(freqs, torch.Tensor):
147
+ raise TypeError(f"freqs must be a Tensor, got {type(freqs)}")
148
+ return (
149
+ int(freqs.data_ptr()),
150
+ int(freqs._version),
151
+ str(freqs.dtype),
152
+ int(freqs.shape[0]),
153
+ int(freqs.shape[1]),
154
+ )
155
+
156
+
157
+ def _split_thw_complex(complex_dim: int) -> tuple[int, int, int]:
158
+ complex_dim = int(complex_dim)
159
+ if complex_dim <= 0:
160
+ raise ValueError(f"complex_dim must be positive, got {complex_dim}")
161
+ dh = dw = complex_dim // 3
162
+ dt = complex_dim - 2 * dh
163
+ if dt <= 0 or dh <= 0 or dw <= 0:
164
+ raise ValueError(
165
+ f"Invalid T/H/W complex split for complex_dim={complex_dim}: dt={dt}, dh={dh}, dw={dw}"
166
+ )
167
+ if int(dt + dh + dw) != int(complex_dim):
168
+ raise RuntimeError(
169
+ f"T/H/W split does not cover complex_dim: dt+dh+dw={dt + dh + dw} vs {complex_dim}"
170
+ )
171
+ return int(dt), int(dh), int(dw)
172
+
173
+
174
+ def clear_rope_spatial_base_cache(*, device: torch.device | str | None = None) -> None:
175
+ """
176
+ Clear cached spatial RoPE bases.
177
+
178
+ If `device` is provided, only entries for that device are removed.
179
+ """
180
+ global _ROPE_SPATIAL_BASE_CACHE
181
+ if device is None:
182
+ _ROPE_SPATIAL_BASE_CACHE = {}
183
+ return
184
+ dk = _device_key(device)
185
+ to_delete = [k for k in _ROPE_SPATIAL_BASE_CACHE.keys() if k[0] == dk]
186
+ for k in to_delete:
187
+ _ROPE_SPATIAL_BASE_CACHE.pop(k, None)
188
+
189
+
190
+ @torch._dynamo.disable
191
+ def get_rope_spatial_bases_cached(
192
+ *,
193
+ freqs: torch.Tensor,
194
+ h_p: int,
195
+ w_p: int,
196
+ dim: int,
197
+ num_heads: int,
198
+ device: torch.device | str,
199
+ ) -> tuple[torch.Tensor, torch.Tensor]:
200
+ """
201
+ Build/get cached spatial RoPE factors for VIDEO tokens:
202
+ - h_freqs_base: [1,1,H,1,Dh]
203
+ - w_freqs_base: [1,1,1,W,Dw]
204
+ """
205
+ h_p = int(h_p)
206
+ w_p = int(w_p)
207
+ dim = int(dim)
208
+ num_heads = int(num_heads)
209
+ if h_p <= 0 or w_p <= 0:
210
+ raise ValueError(f"Expected positive h_p/w_p, got h_p={h_p}, w_p={w_p}.")
211
+ if num_heads <= 0 or (dim % num_heads) != 0:
212
+ raise ValueError(f"Invalid dim/num_heads: dim={dim}, num_heads={num_heads}.")
213
+ if not isinstance(freqs, torch.Tensor) or freqs.dim() != 2:
214
+ raise TypeError(f"freqs must be Tensor[T_max, D_complex], got shape={getattr(freqs, 'shape', None)}")
215
+
216
+ dkey = _device_key(device)
217
+ sig = (
218
+ dkey,
219
+ int(h_p),
220
+ int(w_p),
221
+ int(dim),
222
+ int(num_heads),
223
+ *_freqs_table_id(freqs),
224
+ )
225
+ cached = _ROPE_SPATIAL_BASE_CACHE.get(sig, None)
226
+ if cached is not None:
227
+ h_base, w_base = cached
228
+ if h_base.device == torch.device(device) and w_base.device == torch.device(device):
229
+ return h_base, w_base
230
+
231
+ d = int(dim // max(1, num_heads))
232
+ c = int(d // 2)
233
+ if int(freqs.size(1)) != int(c):
234
+ raise RuntimeError(
235
+ f"Video freqs width {int(freqs.size(1))} != head_dim/2={int(c)} "
236
+ f"(dim={dim}, num_heads={num_heads})."
237
+ )
238
+ if int(freqs.size(0)) < max(int(h_p), int(w_p)):
239
+ raise RuntimeError(
240
+ f"Video freqs table length {int(freqs.size(0))} shorter than spatial grid "
241
+ f"H={int(h_p)}, W={int(w_p)}."
242
+ )
243
+ dt, dh, dw = _split_thw_complex(c)
244
+ _t_f, h_f, w_f = freqs.split([dt, dh, dw], dim=1)
245
+ _ = _t_f
246
+ h_base = h_f[:h_p].view(1, 1, h_p, 1, -1).to(device=device)
247
+ w_base = w_f[:w_p].view(1, 1, 1, w_p, -1).to(device=device)
248
+ _ROPE_SPATIAL_BASE_CACHE[sig] = (h_base, w_base)
249
+ return h_base, w_base
250
+
251
+
252
+ def spatial_bases_from_complex(
253
+ h_base: torch.Tensor,
254
+ w_base: torch.Tensor,
255
+ ) -> SpatialBases:
256
+ """Real cos/sin view of cached complex H/W bases. No new frequency math."""
257
+ if not (isinstance(h_base, torch.Tensor) and isinstance(w_base, torch.Tensor)):
258
+ raise TypeError("spatial_bases_from_complex expects complex H/W base tensors.")
259
+ return SpatialBases(
260
+ h_cos=h_base.real.to(torch.float32),
261
+ h_sin=h_base.imag.to(torch.float32),
262
+ w_cos=w_base.real.to(torch.float32),
263
+ w_sin=w_base.imag.to(torch.float32),
264
+ )
265
+
266
+ _LEVEL_PLANES_VALIDATED: set[tuple] = set()
267
+
268
+
269
+ @torch._dynamo.disable
270
+ def validate_level_planes_dead(
271
+ *,
272
+ freqs: torch.Tensor,
273
+ planes: tuple[int, ...] = LEVEL_PLANES,
274
+ max_rad: float = LEVEL_DEAD_MAX_RAD,
275
+ ) -> None:
276
+ """
277
+ HARD CONTRACT for the level axis: every plane in `planes` must be a TEMPORAL plane
278
+ whose accumulated rotation over the whole table stays below `max_rad`.
279
+
280
+ If this trips, the level axis would collide with real temporal relations. Fix the
281
+ table (theta / length) or pick other planes; never lower `max_rad`.
282
+
283
+ Memoized per (table identity, planes, max_rad): the `.item()` host syncs run once
284
+ per table, not once per forward. Eager-only (dynamo disabled) like the other guards.
285
+ """
286
+ if not isinstance(freqs, torch.Tensor) or freqs.dim() != 2 or not torch.is_complex(freqs):
287
+ raise TypeError("validate_level_planes_dead expects the complex table Tensor[T_max, D_complex].")
288
+ memo_key = (*_freqs_table_id(freqs), tuple(int(p) for p in planes), float(max_rad))
289
+ if memo_key in _LEVEL_PLANES_VALIDATED:
290
+ return
291
+ c = int(freqs.size(1))
292
+ dt, _dh, _dw = _split_thw_complex(c)
293
+ if len(planes) == 0:
294
+ raise ValueError("level axis needs at least one plane.")
295
+ if len(set(int(p) for p in planes)) != len(planes):
296
+ raise ValueError(f"level planes must be distinct, got {planes}.")
297
+ for p in planes:
298
+ p = int(p)
299
+ if not (0 <= p < dt):
300
+ raise ValueError(
301
+ f"[rope][FATAL] level plane {p} is not a temporal plane (temporal planes are 0..{dt - 1}). "
302
+ "The level axis must never touch H/W."
303
+ )
304
+ # angle() of the LAST row is the accumulated rotation (table is polar(1, pos*omega)
305
+ # and only wraps if pos*omega > pi, which max_rad < pi already forbids).
306
+ last = float(torch.angle(freqs[-1, p]).abs().item())
307
+ one_step = float(torch.angle(freqs[1, p]).abs().item())
308
+ if one_step * (int(freqs.size(0)) - 1) > math.pi:
309
+ raise RuntimeError(
310
+ f"[rope][FATAL] level plane {p} wraps within the table "
311
+ f"(omega={one_step:.3e}, T_max={int(freqs.size(0))}); it is NOT dead."
312
+ )
313
+ if last >= float(max_rad):
314
+ raise RuntimeError(
315
+ f"[rope][FATAL] level plane {p} rotates {last:.3f} rad over the table "
316
+ f"(>= {float(max_rad)} rad); it is NOT dead. omega={one_step:.3e}. "
317
+ "Choose lower-frequency planes or a longer temporal theta."
318
+ )
319
+ _LEVEL_PLANES_VALIDATED.add(memo_key)
320
+
321
+
322
+ def apply_level_rotation(
323
+ rope: RopeFactors,
324
+ *,
325
+ planes: tuple[int, ...] = LEVEL_PLANES,
326
+ angle: float = LEVEL_ANGLE_SUMMARY,
327
+ ) -> RopeFactors:
328
+ """
329
+ Add a constant rotation `angle` on the given complex planes of an already-built
330
+ (cos, sin) tape. Used for summary tokens (the summary-vs-raw kind marker);
331
+ raw visual tapes are never passed here.
332
+
333
+ Layout contract: `rope.cos/sin` are [B, L, 1, D_complex] and plane p pairs with the
334
+ real head dims (2p, 2p+1) inside apply_rope_qk. Planes are
335
+ indexed in the T|H|W order of the table, so `planes` in 0..dt-1 are temporal.
336
+
337
+ (c + i s) * (cos a + i sin a) = (c cos a - s sin a) + i (s cos a + c sin a)
338
+ """
339
+ if not isinstance(rope, RopeFactors):
340
+ raise TypeError(f"apply_level_rotation expects RopeFactors, got {type(rope)}")
341
+ cos, sin = rope.cos, rope.sin
342
+ if cos.dim() != 4 or sin.dim() != 4 or cos.shape != sin.shape:
343
+ raise TypeError("RopeFactors must be cos/sin [B, L, 1, D_complex] with equal shapes.")
344
+ d_complex = int(cos.size(-1))
345
+ for p in planes:
346
+ if not (0 <= int(p) < d_complex):
347
+ raise ValueError(f"level plane {int(p)} out of range for D_complex={d_complex}.")
348
+ ca = math.cos(float(angle))
349
+ sa = math.sin(float(angle))
350
+ idx = torch.as_tensor([int(p) for p in planes], device=cos.device, dtype=torch.long)
351
+ c_sel = cos.index_select(-1, idx)
352
+ s_sel = sin.index_select(-1, idx)
353
+ new_cos = cos.index_copy(-1, idx, c_sel * ca - s_sel * sa)
354
+ new_sin = sin.index_copy(-1, idx, s_sel * ca + c_sel * sa)
355
+ return RopeFactors(cos=new_cos, sin=new_sin)
356
+
357
+
358
+ def build_visual_rope_factors(
359
+ *,
360
+ frame_ids: torch.Tensor,
361
+ spatial: SpatialBases,
362
+ table: RopeTable,
363
+ ) -> RopeFactors:
364
+ """
365
+ One (cos, sin) tape for the raw tokens of the given frames. Allows temporal id 0 (z0).
366
+
367
+ `frame_ids` is [B, n_maps]. Spatial bases are the full-res integer H/W lattice.
368
+ """
369
+ if not isinstance(spatial, SpatialBases):
370
+ raise TypeError(f"build_visual_rope_factors expects SpatialBases, got {type(spatial)}")
371
+ if not isinstance(table, RopeTable):
372
+ raise TypeError(f"build_visual_rope_factors expects RopeTable, got {type(table)}")
373
+ if not (isinstance(frame_ids, torch.Tensor) and frame_ids.dim() == 2):
374
+ raise TypeError("frame_ids must be Tensor[B, n_maps].")
375
+ if int(frame_ids.size(1)) <= 0:
376
+ raise ValueError("frame_ids must contain at least one map.")
377
+ cos, sin = _raw_rope_tape(frame_ids=frame_ids, spatial=spatial, table=table)
378
+ return RopeFactors(cos=cos, sin=sin)
379
+
380
+
381
+ def build_summary_rope_factors(
382
+ *,
383
+ frame_ids: torch.Tensor,
384
+ summary_tokens: int,
385
+ table,
386
+ ) -> RopeFactors:
387
+ """
388
+ One (cos, sin) tape for grid-free summary tokens, frame-major (all X of
389
+ frame 0, then frame 1, ...). Same layout as build_visual_rope_factors
390
+ for n_frames * H * W tokens, so a TransformerBlock can apply it on the
391
+ same path.
392
+
393
+ Temporal band: the same table gather as a raw token of the same frame.
394
+ H/W bands: identity (spatial position 0 — cos 1, sin 0). Slot identity
395
+ is the learned init, not a position; every X token of a frame is
396
+ rotation-identical. Level planes (10, 11) get the summary-vs-raw kind
397
+ marker via apply_level_rotation. Does not call validate_level_planes_dead
398
+ (the model runs that once at build time).
399
+ """
400
+ if not isinstance(table, RopeTable):
401
+ raise TypeError(f"build_summary_rope_factors expects RopeTable, got {type(table)}")
402
+ if not (isinstance(frame_ids, torch.Tensor) and frame_ids.dim() == 2):
403
+ raise TypeError("frame_ids must be Tensor[B, n_maps].")
404
+ if int(frame_ids.size(1)) <= 0:
405
+ raise ValueError("frame_ids must contain at least one map.")
406
+ x = int(summary_tokens)
407
+ if x <= 0:
408
+ raise ValueError(f"summary_tokens must be positive, got {x}")
409
+ c = int(table.cos.size(1))
410
+ dt, dh, dw = _split_thw_complex(c)
411
+ t_table_cos = table.cos[:, :dt]
412
+ t_table_sin = table.sin[:, :dt]
413
+ b = int(frame_ids.size(0))
414
+ f = int(frame_ids.size(1))
415
+ seq_len = int(f * x)
416
+ tids = frame_ids.to(device=table.cos.device, dtype=torch.long).reshape(-1)
417
+ t_cos = t_table_cos.index_select(0, tids).view(b, f, 1, -1).expand(b, f, x, -1)
418
+ t_sin = t_table_sin.index_select(0, tids).view(b, f, 1, -1).expand(b, f, x, -1)
419
+ h_cos = table.cos.new_ones(1, 1, 1, dh).expand(b, f, x, -1)
420
+ h_sin = table.sin.new_zeros(1, 1, 1, dh).expand(b, f, x, -1)
421
+ w_cos = table.cos.new_ones(1, 1, 1, dw).expand(b, f, x, -1)
422
+ w_sin = table.sin.new_zeros(1, 1, 1, dw).expand(b, f, x, -1)
423
+ cos = torch.cat([t_cos, h_cos, w_cos], dim=-1).reshape(b, seq_len, 1, -1)
424
+ sin = torch.cat([t_sin, h_sin, w_sin], dim=-1).reshape(b, seq_len, 1, -1)
425
+ return apply_level_rotation(
426
+ RopeFactors(cos=cos, sin=sin),
427
+ planes=LEVEL_PLANES,
428
+ angle=LEVEL_ANGLE_SUMMARY,
429
+ )
430
+
431
+
432
+ def _raw_rope_tape(
433
+ *,
434
+ frame_ids: torch.Tensor,
435
+ spatial: SpatialBases,
436
+ table: RopeTable,
437
+ ) -> tuple[torch.Tensor, torch.Tensor]:
438
+ """
439
+ Compile-friendly (cos, sin) tape for raw tokens: one temporal gather per frame, the
440
+ cached full-res spatial bases broadcast over (F, H, W). Shape metadata + tensor ops only.
441
+ """
442
+ c = int(table.cos.size(1))
443
+ dt, _dh, _dw = _split_thw_complex(c)
444
+ t_table_cos = table.cos[:, :dt]
445
+ t_table_sin = table.sin[:, :dt]
446
+ b = int(frame_ids.size(0))
447
+ f = int(frame_ids.size(1))
448
+ h = int(spatial.h_cos.size(2))
449
+ w = int(spatial.w_cos.size(3))
450
+ seq_len = int(f * h * w)
451
+ tids = frame_ids.to(device=table.cos.device, dtype=torch.long).reshape(-1) # [B*n_maps]
452
+ t_cos = t_table_cos.index_select(0, tids).view(b, f, 1, 1, -1).expand(b, f, h, w, -1)
453
+ t_sin = t_table_sin.index_select(0, tids).view(b, f, 1, 1, -1).expand(b, f, h, w, -1)
454
+ h_cos = spatial.h_cos.expand(b, f, h, w, -1)
455
+ h_sin = spatial.h_sin.expand(b, f, h, w, -1)
456
+ w_cos = spatial.w_cos.expand(b, f, h, w, -1)
457
+ w_sin = spatial.w_sin.expand(b, f, h, w, -1)
458
+ cos = torch.cat([t_cos, h_cos, w_cos], dim=-1).reshape(b, seq_len, 1, -1)
459
+ sin = torch.cat([t_sin, h_sin, w_sin], dim=-1).reshape(b, seq_len, 1, -1)
460
+ return cos, sin
461
+
462
+
463
+ def apply_rope_qk(
464
+ q: torch.Tensor,
465
+ k: torch.Tensor,
466
+ *,
467
+ cos: torch.Tensor,
468
+ sin: torch.Tensor,
469
+ ) -> tuple[torch.Tensor, torch.Tensor]:
470
+ """
471
+ Rotate Q and K ``[B, L, H, D]`` by PRECOMPUTED rotary factors, in one fused pass.
472
+
473
+ `cos`/`sin` (shape [B, L, 1, D/2]) are built once per forward
474
+ (`build_visual_rope_factors` for raw tokens, `build_summary_rope_factors` for summaries)
475
+ and shared across every block. Q and K are concatenated on the head axis, rotated
476
+ together in fp32, then split. No complex math.
477
+ """
478
+ if not isinstance(cos, torch.Tensor) or not isinstance(sin, torch.Tensor):
479
+ raise ValueError("apply_rope_qk requires precomputed `cos`/`sin`; build them via build_visual_rope_factors().")
480
+ if int(cos.size(1)) != int(q.size(1)) or int(q.size(1)) != int(k.size(1)):
481
+ raise RuntimeError(
482
+ f"RoPE tape covers {int(cos.size(1))} tokens; q has {int(q.size(1))}, k has {int(k.size(1))}."
483
+ )
484
+ num_heads = q.size(2)
485
+ qk = torch.cat([q, k], dim=2).to(torch.float32) # [B, L, 2H, D]
486
+ pair = qk.reshape(qk.size(0), qk.size(1), qk.size(2), -1, 2)
487
+ even, odd = pair[..., 0], pair[..., 1]
488
+ rotated = torch.stack((even * cos - odd * sin, odd * cos + even * sin), dim=-1).flatten(3)
489
+ return rotated[:, :, :num_heads].type_as(q), rotated[:, :, num_heads:].type_as(k)
summaryformer_utils/streaming_sink.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Long-horizon streaming: one Z0 sink slot chases the one buffer, and the RoPE table gets long enough to stream.
2
+
3
+ z0 (frame 0, the sink) is ONE permanent slot in the SummaryKVCache: the Z0 region, the whole record
4
+ ``raw(0) ++ sum(0)``. Everything else rotates inside that same buffer. One dense read of the prefix means one
5
+ temporal id for that slot — one RoPE rotation of its K.
6
+
7
+ One buffer, one softmax, one gap (``sink_gap_max: int``). The buffer keeps the last W committed frames (Y as
8
+ whole records in RAW, W−Y as X-row summaries in SUM). ``SinkChaser.oldest_alive(n_committed)`` is
9
+ ``first_id + max(0, n_committed − W)``; once ``n_committed >= W`` that frame sits in SUM. The gap from the sink id
10
+ to the oldest alive frame should stay small; a long stream would grow it without bound. Policy (``SinkChaser``):
11
+ when that gap reaches ``sink_gap_max``, rotate the Z0 slot forward by ``gap - 1``, back to gap 1. Chasing only the
12
+ oldest RAW frame would put the sink at a temporal id later than summaries still alive in SUM, so the gap is
13
+ measured to the oldest frame in the whole buffer.
14
+
15
+ In place, on the temporal RoPE band of that one slot only, V untouched (no RoPE on V). `SinkChaser` is THE policy;
16
+ every stream session goes through it.
17
+
18
+ Why rotating stored K by T frames == having written it at id + T: the table is polar(1, id * omega), so
19
+ row[id + T] == row[id] * row[T] exactly; a K written at id `p` multiplied by row[T] is the K that would have been
20
+ written at `p + T`. The z0 slot is written at id 0 (identity rotation), so the slot holds that K as written and every
21
+ rotation is one bf16 round trip on top of fp32 math. Round-off accumulates over repeated rotations; it is one
22
+ rotation per `gap_max - 1` frames.
23
+
24
+ Nothing in `rope.py` is edited or called for the rotation. The band layout is restated here from `rope.py`'s header
25
+ (temporal planes first, interleaved (re, im) pairs, `dt = C - 2 * (C // 3)` planes); the rotation uses the same
26
+ formula as `rope.apply_rope_qk`.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import torch
31
+
32
+ from summaryformer_utils import rope as _rope
33
+ from summaryformer_utils.rope import LEVEL_DEAD_MAX_RAD, LEVEL_PLANES, build_rope_table, validate_level_planes_dead
34
+
35
+
36
+ def _temporal_planes(freqs: torch.Tensor) -> int:
37
+ """Number of TEMPORAL complex planes: rope.py's `_split_thw_complex` rule, restated (not imported: private)."""
38
+ if not (isinstance(freqs, torch.Tensor) and freqs.dim() == 2 and torch.is_complex(freqs)):
39
+ raise TypeError("expected the complex RoPE table Tensor[T_max, D_complex]")
40
+ c = int(freqs.size(1))
41
+ dt = c - 2 * (c // 3)
42
+ if dt <= 0:
43
+ raise RuntimeError(f"[sink] bad RoPE table width {c}")
44
+ return dt
45
+
46
+
47
+ def _sink_rotation_cos_sin(rope_freqs: torch.Tensor, T: int, head_dim: int) -> tuple[torch.Tensor, torch.Tensor, int]:
48
+ T = int(T)
49
+ if T <= 0:
50
+ raise ValueError(f"[sink] T must be >= 1 (got {T}); do not call this for a no-op")
51
+ if T >= int(rope_freqs.size(0)):
52
+ raise RuntimeError(f"[sink] T={T} has no row in the RoPE table ({int(rope_freqs.size(0))} rows)")
53
+ dt = _temporal_planes(rope_freqs)
54
+ if 2 * dt > int(head_dim):
55
+ raise RuntimeError(f"[sink] temporal band {2 * dt} real dims > head_dim {head_dim}")
56
+ row = rope_freqs[T, :dt] # polar(1, T * omega_t), the FORWARD phase
57
+ return row.real.to(torch.float32).view(1, 1, 1, dt), row.imag.to(torch.float32).view(1, 1, 1, dt), dt
58
+
59
+
60
+ def _rotate_span_inplace(k_buf: torch.Tensor, span: tuple[int, int], cos: torch.Tensor, sin: torch.Tensor, dt: int) -> None:
61
+ s, e = int(span[0]), int(span[1])
62
+ if e <= s:
63
+ return
64
+ k_ref = k_buf[:, s:e, :, : 2 * dt] # [B, rows, H, 2*dt] view into the buffer
65
+ k = k_ref.to(torch.float32).unflatten(-1, (dt, 2))
66
+ k0, k1 = k[..., 0], k[..., 1]
67
+ rot = torch.stack((k0 * cos - k1 * sin, k1 * cos + k0 * sin), dim=-1).flatten(-2) # same formula as rope apply
68
+ k_ref.copy_(rot.to(dtype=k_ref.dtype))
69
+
70
+
71
+ @torch.no_grad()
72
+ def rotate_sink_keys_forward(kv_cache, *, rope_freqs: torch.Tensor, T: int) -> None:
73
+ """Rotate the ONE Z0 slot's cached K forward by ``T`` frames, in place, all layers.
74
+
75
+ The summary tokens' level planes (rope.LEVEL_PLANES) are temporal planes too and rotate with the band; by
76
+ ``validate_level_planes_dead`` they move < LEVEL_DEAD_MAX_RAD over the table, so the kind marker survives.
77
+ After this the sink attends as if it had been written at (old id + T). V is not touched (no RoPE on V).
78
+ ``T <= 0`` is a programming error (do not call this for a no-op).
79
+ """
80
+ T = int(T)
81
+ if T <= 0:
82
+ raise ValueError(f"[sink] T={T}: nothing to rotate; do not call this for a no-op")
83
+ span = kv_cache.z0_span()
84
+ if span[1] <= span[0]:
85
+ raise RuntimeError("[sink] cache was built with z0_tokens=0: there is no sink to rotate")
86
+ cos, sin, dt = _sink_rotation_cos_sin(rope_freqs, T, int(kv_cache.head_dim))
87
+ for layer in kv_cache.layers:
88
+ _rotate_span_inplace(layer["k"], span, cos, sin, dt)
89
+
90
+
91
+ def sink_gaps_from_config(v) -> int | None:
92
+ """Normalise a `sink_gap_max` config value to `int | None` (one buffer, one gap).
93
+
94
+ Accepted: `None` (never chase; the caller must cap the stream) or an int >= 2 (gap 1 is where a rotation
95
+ lands; a trigger of 1 would rotate every frame).
96
+ """
97
+ if v is None:
98
+ return None
99
+ if isinstance(v, bool) or not isinstance(v, int) or int(v) < 2:
100
+ raise RuntimeError(f"[sink] sink_gap_max={v!r} must be None or an int >= 2")
101
+ return int(v)
102
+
103
+
104
+ def sink_gaps_describe(gap_max) -> str:
105
+ return f"sink_gap_max={gap_max}"
106
+
107
+
108
+ class SinkChaser:
109
+ """One gap policy for the ONE Z0 slot (module docstring).
110
+
111
+ One instance per session. Before body frame ``i`` (``n_committed = i`` frames already committed), ``rotate``
112
+ measures ``gap = oldest alive frame id - sink id`` and, when it reaches ``gap_max``, rotates the slot's K forward by
113
+ ``gap - 1`` (back to gap 1). ``advance(T)`` is the bookkeeping half of ``rotate``.
114
+
115
+ Ids: body frames are ``first_id + i`` (first_id = 1); the sink starts
116
+ at temporal id 0. The buffer keeps the last ``W`` committed frames (``Y`` as records, ``W - Y`` as summaries), so the
117
+ oldest alive after ``n_committed`` commits is ``first_id + max(0, n_committed - W)``. A chased stream must keep
118
+ ``1 <= gap <= gap_max``; anything else means a frame or a rotation was skipped and is an error.
119
+ """
120
+
121
+ def __init__(self, *, raw_window: int, summary_window: int, gaps, first_id: int = 1):
122
+ self.Y, self.W = int(raw_window), int(summary_window)
123
+ if self.W < self.Y:
124
+ raise ValueError(f"[sink] summary_window={self.W} < raw_window={self.Y}: W is the total memory span")
125
+ self.gap_max = sink_gaps_from_config(gaps)
126
+ self.first_id = int(first_id)
127
+ self.sink_id = 0 # the Z0 slot's current temporal id (RoPE); 0 = as written
128
+ self.n_rotations = 0
129
+
130
+ @property
131
+ def gaps(self):
132
+ """Back-compat spelling of ``gap_max`` for log lines (``sink_gaps_describe(chaser.gaps)``)."""
133
+ return self.gap_max
134
+
135
+ def oldest_alive(self, n_committed: int) -> int:
136
+ return self.first_id + max(0, int(n_committed) - self.W)
137
+
138
+ def rotation_before_frame(self, n_committed: int) -> int:
139
+ """Frames to rotate the sink by before body frame ``n_committed`` (0 = none)."""
140
+ if self.gap_max is None:
141
+ return 0
142
+ gap = self.oldest_alive(n_committed) - self.sink_id
143
+ if not 1 <= gap <= self.gap_max:
144
+ raise RuntimeError(f"[sink] gap={gap} outside [1, {self.gap_max}] (sink={self.sink_id}, "
145
+ f"oldest={self.oldest_alive(n_committed)}, n_committed={n_committed}): "
146
+ "a frame or a rotation was skipped")
147
+ return gap - 1 if gap >= self.gap_max else 0
148
+
149
+ def advance(self, T: int) -> None:
150
+ """Move the sink id by ``T`` (bookkeeping only; the K was rotated by the caller or by ``rotate``)."""
151
+ T = int(T)
152
+ if T:
153
+ self.sink_id += T
154
+ self.n_rotations += 1
155
+
156
+ def rotate(self, kv_cache, rope_freqs: torch.Tensor, n_committed: int) -> int:
157
+ """rotation_before_frame + in-place rotation of the Z0 slot + advance. Returns T (0 = nothing done)."""
158
+ T = self.rotation_before_frame(n_committed)
159
+ if T:
160
+ rotate_sink_keys_forward(kv_cache, rope_freqs=rope_freqs, T=T)
161
+ self.advance(T)
162
+ return T
163
+
164
+ def max_relative_frames(self) -> int:
165
+ """Largest |query id - key id| the stream can produce under this policy (for extend_rope_table_for_streaming):
166
+ the current frame vs the sink just before a rotation = W + gap_max. Unchased streams have no bound."""
167
+ if self.gap_max is None:
168
+ raise RuntimeError("[sink] max_relative_frames needs a chase (sink_gap_max set)")
169
+ return self.W + int(self.gap_max)
170
+
171
+ def describe(self) -> str:
172
+ return f"sink(id={self.sink_id} gap_max={self.gap_max} rot={self.n_rotations})"
173
+
174
+
175
+ def extend_rope_table_for_streaming(model, *, table_len: int, max_relative_frames: int) -> None:
176
+ """Swap `model.rope_table` (+ its fp32 real copies) for a longer table so absolute ids can run to `table_len`.
177
+
178
+ `max_relative_frames` is the largest |query id - key id| the STREAM can produce (W + sink_gap_max); the caller
179
+ guarantees it (sink rotation + hard stop). The level-plane contract (`validate_level_planes_dead`: the
180
+ summary-vs-raw kind marker on temporal planes 10/11, `rope.LEVEL_PLANES`) is about RELATIVE phase; the model's
181
+ per-forward guard measures it over the
182
+ WHOLE table because, without a chasing sink, table length == max relative distance. With one it is not: a 4096-row
183
+ table fails the whole-table check (plane 10: 1.9 rad) while the stream never produces |dt| > `span` (0.06 rad). So
184
+ the contract is validated here over `span` rows and the full table's memo key is registered so the per-forward guard
185
+ accepts it. That memo is keyed on the table's storage: extend AFTER the final `.to(device)` (a later device move
186
+ rebuilds the table, the guard runs again on the whole table and fails loudly -- fail-fast, not silent) and BEFORE
187
+ torch.compile (the table is a graph constant).
188
+ """
189
+ table_len, span = int(table_len), int(max_relative_frames)
190
+ old = model.rope_table
191
+ if table_len <= int(old.size(0)):
192
+ raise ValueError(f"[sink] table_len={table_len} must exceed the current {int(old.size(0))} rows")
193
+ if not 1 < span < table_len:
194
+ raise ValueError(f"[sink] max_relative_frames={span} must be in (1, {table_len})")
195
+ # Same builder as the model's own table: each row depends on its own id only, so the shared rows must match.
196
+ head_dim = int(model.dim) // int(model.num_heads)
197
+ new = build_rope_table(head_dim, rows=table_len).to(device=old.device, dtype=old.dtype)
198
+ if not torch.equal(new[: int(old.size(0))], old):
199
+ raise RuntimeError("[sink] rebuilt RoPE table differs from the model's on the existing rows; refusing")
200
+ validate_level_planes_dead(freqs=new[: span + 1])
201
+ _rope._LEVEL_PLANES_VALIDATED.add((*_rope._freqs_table_id(new), tuple(int(p) for p in LEVEL_PLANES), float(LEVEL_DEAD_MAX_RAD)))
202
+ # Also drops the spatial-base memo (the bases are slices of the table, cached on its storage).
203
+ model.set_rope_table(new)
204
+ print(f"[sink] RoPE table {int(old.size(0))} -> {table_len} rows (level planes re-validated over |dt| <= {span})", flush=True)
summaryformer_utils/transformer_block.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Summaryformer transformer block: visual self-attn over the one-buffer KV cache -> FFN.
2
+
3
+ A block is told its RoPE tape, the frame's conditioning, and a ``SummaryKVCache`` layer dict + ``SummaryKVPlan``.
4
+
5
+ VISUAL SELF-ATTENTION (`SelfAttention.forward` -> `_attend_with_cache`)
6
+ =======================================================================
7
+ The query of one KV-cached forward is ONE frame's record ``[raw(t) : Tf | sum(t) : X]`` (z0 pass: ``Z``
8
+ raw rows). Per layer the cache is ONE buffer (layout in gta_streaming_kv_cache.py). The forward is:
9
+
10
+ write buffer[write : write+REC] <- k, v of the whole record (RAW slot cursor_r; z0 pass: the Z0 slot)
11
+ read out = attend_buffer_prefix(q, buffer[0 : end]) ALL REC queries, one call
12
+
13
+ ``end`` is explicit (a Python int, or the cache's one 0-d device tensor in the compiled form). The write
14
+ is not at the tip of the prefix (the slot rotates), so the length is never ``write + Lq``. Both query
15
+ groups see the same key set: there is no second read and no split of ``out``.
16
+
17
+ KERNELS. One read, two kernels: FlexAttention (``rollout_flex_attention.py``) and FlashAttention's
18
+ ``flash_attn_with_kvcache`` (``fast_flash_kv.py``). There is no third path. Recency is OFF unless the cache
19
+ attached ``layer["recency_bias"]`` (a per-key bias over the whole buffer, zeros outside SUM):
20
+ * bias attached -> flex with a ``score_mod``: ``attend_with_kv_bias`` (int end) /
21
+ ``attend_full_buffer_with_kv_bias`` (device end). The flash kernel takes no bias.
22
+ * bias off, backend "flash", CUDA fp16/bf16 with flash_attn installed -> ``attend_buffer_prefix``.
23
+ * bias off, anything else (backend "flex", CPU, fp32) -> ``flex_attend_full`` / ``flex_attend_full_dev``.
24
+ Flip ``set_streaming_attention_backend("flex")`` (or ``LUCID_STREAMING_ATTN_BACKEND=flex``) to make every
25
+ unbiased read flex.
26
+
27
+ Invariants:
28
+ * K is stored RoPE'd with ABSOLUTE frame ids; V raw. Buffer dtype = model compute dtype, [B, cap, H, D].
29
+ * Every denoising pass of a frame writes the same RAW slot. ``begin_frame`` donates before the first write;
30
+ ``commit_current_frame`` only advances the cursor. A pass always writes: the slot is the prefix.
31
+ * Ring order differs from frame order; a dense softmax does not see that. No duplicate keys.
32
+ * Inference only: every forward runs under ``torch.no_grad()``.
33
+ """
34
+ from __future__ import annotations
35
+
36
+ import os
37
+ from typing import NamedTuple
38
+
39
+ import torch
40
+ import torch.nn as nn
41
+
42
+ from summaryformer_utils.rollout_flex_attention import flex_attend_full, flex_attend_full_dev
43
+ from summaryformer_utils.fast_flash_kv import (
44
+ attend_buffer_prefix,
45
+ FLASH_KVCACHE_AVAILABLE,
46
+ )
47
+ from summaryformer_utils.recency_bias import (
48
+ RECENCY_BIAS_KEY,
49
+ attend_full_buffer_with_kv_bias,
50
+ attend_with_kv_bias,
51
+ )
52
+ from summaryformer_utils.visual_mlp import VisualSwiGLUFFN
53
+ from summaryformer_utils.rope import RopeFactors, apply_rope_qk
54
+
55
+ # -------------------------------------------------------------------------------------- #
56
+ # Streaming KV-cached attention backend controller.
57
+ #
58
+ # Applies to the UNBIASED prefix read. "flash" = FlashAttention `flash_attn_with_kvcache` (CUDA fp16 / bf16; flex
59
+ # anywhere else), "flex" = `flex_attend_full`. A read with the recency hook attached is always flex (module docstring).
60
+ # Default mirrors the env var so it can be flipped without code edits.
61
+ _STREAMING_ATTENTION_BACKEND = os.environ.get("LUCID_STREAMING_ATTN_BACKEND", "flash").lower()
62
+
63
+
64
+ def set_streaming_attention_backend(backend: str) -> str:
65
+ """Select the KV-cached streaming attention kernel: "flash" (default) or "flex".
66
+
67
+ Returns the normalized backend actually set. Raises on an unknown value.
68
+ """
69
+ global _STREAMING_ATTENTION_BACKEND
70
+ b = str(backend).lower().strip()
71
+ if b not in ("flash", "flex"):
72
+ raise ValueError(f"streaming attention backend must be 'flash' or 'flex'; got {backend!r}.")
73
+ _STREAMING_ATTENTION_BACKEND = b
74
+ print(f"[attn][streaming-backend] set to '{b}'")
75
+ return b
76
+
77
+
78
+ def get_streaming_attention_backend() -> str:
79
+ return _STREAMING_ATTENTION_BACKEND
80
+
81
+
82
+ class SelfAttention(nn.Module):
83
+ """Visual self-attention: one buffer write and one prefix read per forward.
84
+
85
+ ``kv_plan`` is a ``SummaryKVPlan`` (``kind``, ``raw_tokens``, ``summary_tokens``, ``write``, ``end``,
86
+ ``query_tokens``). The current record is written once into ``RAW[cursor_r]`` (``plan.write``; the z0 pass
87
+ writes the Z0 slot at offset 0) and every query is one ``attend_buffer_prefix`` over ``buffer[0:end]``.
88
+ Raw and summary rows share that key set.
89
+ """
90
+
91
+ def __init__(self, dim, num_heads):
92
+ assert dim % num_heads == 0
93
+ super().__init__()
94
+ self.dim = dim
95
+ self.num_heads = num_heads
96
+ self.head_dim = dim // num_heads
97
+
98
+ self.visual_qkv = nn.Linear(dim, 3 * dim)
99
+ self.visual_out = nn.Linear(dim, dim)
100
+ # QK norm before the reshape into heads: RMSNorm(dim).
101
+ self.visual_q_rms_norm = nn.RMSNorm(dim, elementwise_affine=True)
102
+ self.visual_k_rms_norm = nn.RMSNorm(dim, elementwise_affine=True)
103
+
104
+ @staticmethod
105
+ def _attend_prefix(
106
+ q: torch.Tensor,
107
+ k_buf: torch.Tensor,
108
+ v_buf: torch.Tensor,
109
+ end: "int | torch.Tensor",
110
+ bias: torch.Tensor | None,
111
+ *,
112
+ use_flex: bool,
113
+ ) -> torch.Tensor:
114
+ """ONE dense read of ``buffer[0 : end]``. ``q [B, Lq, H, D] -> [B, Lq, H, D]``.
115
+
116
+ Two kernels, flex and flash (module docstring). The flash kernel only exists on CUDA in fp16 / bf16;
117
+ every other read is flex.
118
+ ``end`` int: the kernel sees the prefix ``[0 : end]``.
119
+ ``end`` 0-d device tensor (compiled streaming): the kernel sees the whole buffer with keys ``>= end``
120
+ masked, so no Python int of the fill level enters the graph. ``bias`` (recency hook, zeros outside SUM)
121
+ is a flex ``score_mod``; the flash kernel takes no bias.
122
+ """
123
+ use_flash = (
124
+ not use_flex and FLASH_KVCACHE_AVAILABLE and q.is_cuda and q.dtype in (torch.float16, torch.bfloat16)
125
+ )
126
+ if isinstance(end, torch.Tensor):
127
+ if bias is not None:
128
+ return attend_full_buffer_with_kv_bias(q, k_buf, v_buf, bias, end).to(q.dtype)
129
+ if use_flash:
130
+ return attend_buffer_prefix(q, k_buf, v_buf, end)
131
+ return flex_attend_full_dev(q, k_buf, v_buf, end)
132
+ end = int(end)
133
+ if bias is not None:
134
+ return attend_with_kv_bias(q, k_buf[:, :end], v_buf[:, :end], bias[:end]).to(q.dtype)
135
+ if use_flash:
136
+ return attend_buffer_prefix(q, k_buf, v_buf, end)
137
+ return flex_attend_full(q, k_buf[:, :end], v_buf[:, :end])
138
+
139
+ def _attend_with_cache(
140
+ self,
141
+ q: torch.Tensor,
142
+ k: torch.Tensor,
143
+ v: torch.Tensor,
144
+ *,
145
+ kv_cache: dict,
146
+ kv_plan,
147
+ ) -> torch.Tensor:
148
+ """ONE write of the current record into ``RAW[cursor_r]``, then ONE ``attend_buffer_prefix`` read of ``[0:end]``.
149
+
150
+ ``kv_plan`` is a ``SummaryKVPlan`` from ``plan_z0`` / ``plan_body``: ``kind`` (``"z0"`` | ``"body"``),
151
+ ``raw_tokens``, ``summary_tokens``, ``write`` (the row of ``RAW[cursor_r]``; the z0 pass writes the Z0
152
+ slot at 0), ``end`` (a Python int, or the cache's one 0-d ``end_dev`` when ``ends_are_device``), and
153
+ ``query_tokens`` (``raw_tokens + summary_tokens``, must equal ``k.size(1)``). ``kv_cache`` is that
154
+ layer's dict ``{"k","v"[, "recency_bias"]}``. ``q/k/v`` are the record ``[B, REC, H, D]``,
155
+ already RoPE'd, raw rows then the X summary rows. Every query reads the same prefix. There is no second
156
+ read.
157
+ """
158
+ lq = int(k.size(1))
159
+ if lq != int(kv_plan.query_tokens):
160
+ raise RuntimeError(
161
+ f"KV plan ({kv_plan.kind}) expects a record of {int(kv_plan.query_tokens)} tokens; "
162
+ f"the block received L={lq}."
163
+ )
164
+ k_buf, v_buf = kv_cache["k"], kv_cache["v"]
165
+ w = int(kv_plan.write)
166
+ k_buf[:, w:w + lq] = k.to(k_buf.dtype)
167
+ v_buf[:, w:w + lq] = v.to(v_buf.dtype)
168
+ # z0's prefix is only the Z0 slot (bias there is 0). Body passes pick up the hook when it is on.
169
+ bias = None if kv_plan.kind == "z0" else kv_cache.get(RECENCY_BIAS_KEY)
170
+ return self._attend_prefix(
171
+ q, k_buf, v_buf, kv_plan.end, bias, use_flex=_STREAMING_ATTENTION_BACKEND == "flex",
172
+ )
173
+
174
+ def _qkv_roped(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor):
175
+ """QKV projection -> per-tensor RMSNorm on q / k -> RoPE. Returns (q, k, v) in x's dtype family
176
+ (``type_as(v)``)."""
177
+ per_head = (int(x.size(0)), int(x.size(1)), self.num_heads, self.head_dim) # [B, L, H, D]
178
+ q_lin, k_lin, v_lin = self.visual_qkv(x).chunk(3, dim=-1)
179
+ q = self.visual_q_rms_norm(q_lin).view(per_head)
180
+ k = self.visual_k_rms_norm(k_lin).view(per_head)
181
+ v = v_lin.view(per_head)
182
+ q, k = apply_rope_qk(q, k, cos=cos, sin=sin)
183
+ return q.type_as(v), k.type_as(v), v
184
+
185
+ def forward(self, visual_tokens, kv_cache, *, visual_rope: RopeFactors, kv_plan):
186
+ """Visual self-attention over ONE frame's record ``[raw | X summaries]``.
187
+
188
+ ``visual_rope`` is one ``RopeFactors`` over the record in that order (the model concatenates the
189
+ factors). Summary rows are grid-free (X tokens, not ``h·w``). ``kv_cache`` is this layer's
190
+ ``SummaryKVCache`` dict and ``kv_plan`` is a ``SummaryKVPlan`` (``plan_z0`` / ``plan_body``: ``write``
191
+ into ``RAW[cursor_r]`` or the Z0 slot, one ``end``). ``_attend_with_cache`` does that one write plus one
192
+ ``attend_buffer_prefix`` read.
193
+ """
194
+ if kv_cache is None or kv_plan is None:
195
+ raise TypeError("SelfAttention.forward needs kv_cache and kv_plan (SummaryKVCache.plan_z0() / plan_body()).")
196
+ q, k, v = self._qkv_roped(visual_tokens, visual_rope.cos, visual_rope.sin)
197
+ x = self._attend_with_cache(q, k, v, kv_cache=kv_cache, kv_plan=kv_plan)
198
+ return self.visual_out(x.flatten(2))
199
+
200
+
201
+ # -------------------------------------------------------------------------------------- #
202
+ # FiLM. Both sublayers of a block have the form
203
+ #
204
+ # x <- x + gate * f( norm(x) * (1 + scale) + shift )
205
+ #
206
+ # and (shift, scale, gate) are rows of a FiLM table ``[B, FILM_SLOTS, dim]``, one table per frame. A block reads
207
+ # six of the nine rows; rows 3..5 are not read.
208
+ FILM_SLOTS = 9
209
+ ATTN_ROWS = (0, 1, 2) # (shift, scale, gate) of the self-attention sublayer
210
+ FFN_ROWS = (6, 7, 8) # (shift, scale, gate) of the feed-forward sublayer
211
+
212
+
213
+ def _film_in(h: torch.Tensor, n_raw: int, raw: torch.Tensor, summary: torch.Tensor, rows: tuple[int, int, int]) -> torch.Tensor:
214
+ """``h * (1 + scale) + shift`` over one record ``h [B, REC, dim]``: the raw tokens (the first ``n_raw``) read
215
+ the ``raw`` table, the summary tokens read the ``summary`` table (each ``[B, FILM_SLOTS, dim]``)."""
216
+ shift, scale, _ = rows
217
+ return torch.cat([
218
+ h[:, :n_raw] * (1 + raw[:, scale:scale + 1]) + raw[:, shift:shift + 1],
219
+ h[:, n_raw:] * (1 + summary[:, scale:scale + 1]) + summary[:, shift:shift + 1],
220
+ ], dim=1)
221
+
222
+
223
+ def _film_out(y: torch.Tensor, n_raw: int, raw: torch.Tensor, summary: torch.Tensor, rows: tuple[int, int, int]) -> torch.Tensor:
224
+ """``y * gate`` over the same record, split the same way."""
225
+ gate = rows[2]
226
+ return torch.cat([y[:, :n_raw] * raw[:, gate:gate + 1], y[:, n_raw:] * summary[:, gate:gate + 1]], dim=1)
227
+
228
+
229
+ class FrameConditioning(NamedTuple):
230
+ """What ONE frame is conditioned on, each input already projected to a FiLM table ``[B, FILM_SLOTS, dim]``.
231
+
232
+ The model builds this once per forward and every block reads the same one. ``time`` reaches every token of
233
+ the record. ``action`` / ``grid`` / ``fps`` reach the RAW tokens only, each through a gate the block learned
234
+ for it; the summary tokens are conditioned on time alone. ``seed`` says the record is the seed frame, whose
235
+ grid table goes through its own gate.
236
+ """
237
+
238
+ time: torch.Tensor
239
+ action: torch.Tensor | None = None
240
+ grid: torch.Tensor | None = None
241
+ fps: torch.Tensor | None = None
242
+ seed: bool = False
243
+
244
+
245
+ class TransformerBlock(nn.Module):
246
+ """Self-attention over the memory buffer, then a feed-forward, on one frame's record ``[raw | summary]``."""
247
+
248
+ def __init__(self, dim, ffn_dim, num_heads):
249
+ super().__init__()
250
+ self.dim = dim
251
+ self.ffn_dim = ffn_dim
252
+ self.num_heads = num_heads
253
+
254
+ self.before_visual_self_attention = nn.LayerNorm(dim, elementwise_affine=False)
255
+ self.visual_self_attention = SelfAttention(dim, num_heads)
256
+ self.before_visual_feed_forward = nn.LayerNorm(dim, elementwise_affine=False)
257
+ self.visual_feed_forward = VisualSwiGLUFFN(
258
+ dim=int(dim),
259
+ mlp_ratio=(float(ffn_dim) / float(dim)),
260
+ multiple_of=16,
261
+ bias=True,
262
+ )
263
+
264
+ # This block's own FiLM table, added to the frame's, and one gate per row for each kind of conditioning.
265
+ # A gate is sigmoid(parameter); -5 starts it nearly closed.
266
+ self.visual_film_offset = nn.Parameter(torch.zeros(1, FILM_SLOTS, dim))
267
+ self.visual_action_gate = nn.Parameter(torch.full((FILM_SLOTS,), -5.0))
268
+ self.visual_grid_gate = nn.Parameter(torch.full((FILM_SLOTS,), -5.0))
269
+ self.visual_grid_gate_z0 = nn.Parameter(torch.full((FILM_SLOTS,), -5.0))
270
+ self.visual_fps_gate = nn.Parameter(torch.full((FILM_SLOTS,), -5.0))
271
+
272
+ def _film(self, cond: FrameConditioning) -> tuple[torch.Tensor, torch.Tensor]:
273
+ """This block's FiLM tables ``(raw, summary)``, each ``[B, FILM_SLOTS, dim]``.
274
+
275
+ summary = offset + time
276
+ raw = summary + g_action * action + g_grid * grid + g_fps * fps g = sigmoid(gate), per row
277
+ """
278
+ summary = self.visual_film_offset + cond.time
279
+ grid_gate = self.visual_grid_gate_z0 if cond.seed else self.visual_grid_gate
280
+ raw = summary
281
+ for name, table, gate in (
282
+ ("action", cond.action, self.visual_action_gate),
283
+ ("grid", cond.grid, grid_gate),
284
+ ("fps", cond.fps, self.visual_fps_gate),
285
+ ):
286
+ if table is None:
287
+ continue
288
+ if tuple(table.shape) != tuple(summary.shape):
289
+ raise RuntimeError(
290
+ f"{name} FiLM table is {tuple(table.shape)}; the block needs {tuple(summary.shape)} "
291
+ f"([B, {FILM_SLOTS}, dim])."
292
+ )
293
+ g = torch.sigmoid(gate).view(FILM_SLOTS, 1).to(dtype=summary.dtype, device=summary.device)
294
+ raw = raw + g * table.to(dtype=summary.dtype, device=summary.device)
295
+ return raw, summary
296
+
297
+ def forward(self, x, cond: FrameConditioning, *, kv_cache, kv_plan, visual_rope: RopeFactors):
298
+ """One frame's record ``x [B, REC, dim]`` (raw tokens, then the X summary tokens) -> the same shape.
299
+
300
+ ``kv_cache`` is this layer's ``SummaryKVCache`` dict and ``kv_plan`` the frame's ``SummaryKVPlan``
301
+ (it says how many of the tokens are raw).
302
+ """
303
+ n_raw = int(kv_plan.raw_tokens)
304
+ if int(x.size(1)) != int(kv_plan.query_tokens):
305
+ raise RuntimeError(
306
+ f"KV plan ({kv_plan.kind}) expects a record of {int(kv_plan.query_tokens)} tokens; "
307
+ f"the block received L={int(x.size(1))}."
308
+ )
309
+ raw, summary = self._film(cond)
310
+
311
+ # Both sublayers run once over the whole record.
312
+ h = _film_in(self.before_visual_self_attention(x), n_raw, raw, summary, ATTN_ROWS)
313
+ y = self.visual_self_attention(h, kv_cache, visual_rope=visual_rope, kv_plan=kv_plan)
314
+ x = x + _film_out(y, n_raw, raw, summary, ATTN_ROWS)
315
+
316
+ h = _film_in(self.before_visual_feed_forward(x), n_raw, raw, summary, FFN_ROWS)
317
+ return x + _film_out(self.visual_feed_forward(h), n_raw, raw, summary, FFN_ROWS)
summaryformer_utils/visual_mlp.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+
6
+ def _round_to_multiple(x: int, multiple_of: int) -> int:
7
+ multiple_of = int(multiple_of)
8
+ if multiple_of <= 0:
9
+ return int(x)
10
+ x = int(x)
11
+ return int(((x + multiple_of - 1) // multiple_of) * multiple_of)
12
+
13
+
14
+ class VisualSwiGLUFFN(nn.Module):
15
+ """
16
+ Plain pointwise SwiGLU FFN:
17
+
18
+ y = W_o( silu(g) * v ), where [g, v] = W_proj(x)
19
+
20
+ No convolutions, no spatial/temporal mixing, no grid reshapes. Operates on the
21
+ last dim only, so it accepts any token layout ([B, L, C], [B, F, HW, C], ...)
22
+ and returns the same shape. Mixing between tokens is left entirely to attention.
23
+ """
24
+
25
+ def __init__(
26
+ self,
27
+ dim: int,
28
+ mlp_ratio: float = 4.0,
29
+ multiple_of: int = 16,
30
+ bias: bool = True,
31
+ ):
32
+ super().__init__()
33
+ base_hidden = int(dim * mlp_ratio) # e.g. 4d
34
+ hidden = int((2.0 / 3.0) * base_hidden) # 2/3 trick (SwiGLU compute match)
35
+ hidden = _round_to_multiple(hidden, multiple_of)
36
+
37
+ self.hidden_dim = hidden
38
+ self.proj = nn.Linear(dim, 2 * hidden, bias=bias)
39
+ self.out = nn.Linear(hidden, dim, bias=bias)
40
+
41
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
42
+ g, v = self.proj(x).chunk(2, dim=-1)
43
+ return self.out(F.silu(g) * v)
summaryformer_utils/z0_focus_mask.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """z0 focus region: a Bool [B, H, W] grid over the first frame's tokens, True = the subject to hold.
2
+
3
+ The model adds one learned embedding to the z0 tokens inside the region (``apply_z0_focus_region_embedding``).
4
+ ``centered_focus_region`` builds the default region: one blob centred on the grid, no randomness.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import math
9
+
10
+ import torch
11
+
12
+ _SHAPES = ("square", "diamond")
13
+
14
+
15
+ def _square_keep(H: int, W: int, cy: float, cx: float, side: int) -> torch.Tensor:
16
+ side = int(max(1, side))
17
+ half = (side - 1) / 2.0
18
+ if side <= H:
19
+ cy = min(max(cy, half), float(H - 1) - half)
20
+ else:
21
+ cy = (H - 1) / 2.0
22
+ if side <= W:
23
+ cx = min(max(cx, half), float(W - 1) - half)
24
+ else:
25
+ cx = (W - 1) / 2.0
26
+ i0 = int(round(cy - half))
27
+ j0 = int(round(cx - half))
28
+ i0 = max(0, min(i0, H - min(side, H)))
29
+ j0 = max(0, min(j0, W - min(side, W)))
30
+ i1 = min(H, i0 + side)
31
+ j1 = min(W, j0 + side)
32
+ keep = torch.zeros((H, W), dtype=torch.bool)
33
+ keep[i0:i1, j0:j1] = True
34
+ return keep
35
+
36
+
37
+ def _diamond_keep(H: int, W: int, cy: float, cx: float, radius: int) -> torch.Tensor:
38
+ radius = int(max(0, radius))
39
+ # Clamp the center so a ball of this r stays mostly on-grid (same reason as the square).
40
+ if radius < H:
41
+ cy = min(max(cy, float(radius) * 0.5), float(H - 1) - float(radius) * 0.5)
42
+ else:
43
+ cy = (H - 1) / 2.0
44
+ if radius < W:
45
+ cx = min(max(cx, float(radius) * 0.5), float(W - 1) - float(radius) * 0.5)
46
+ else:
47
+ cx = (W - 1) / 2.0
48
+ ii = torch.arange(H, dtype=torch.float32).view(H, 1)
49
+ jj = torch.arange(W, dtype=torch.float32).view(1, W)
50
+ return (ii - float(cy)).abs() + (jj - float(cx)).abs() <= float(radius)
51
+
52
+
53
+ def _size_for_coverage(shape: str, H: int, W: int, coverage: float) -> int:
54
+ target = float(coverage) * float(H * W)
55
+ if shape == "square":
56
+ return max(1, int(round(math.sqrt(max(target, 1.0)))))
57
+ if shape == "diamond":
58
+ # Infinite-grid Manhattan ball count is 1 + 2 r (r+1). Invert, then the on-grid
59
+ # builder + adjust loop land in-band.
60
+ disc = max(0.0, 1.0 + 2.0 * (target - 1.0))
61
+ return max(0, int(round((-1.0 + math.sqrt(disc)) / 2.0)))
62
+ raise RuntimeError(f"focus region unknown shape {shape!r}")
63
+
64
+
65
+ def _build_keep(shape: str, H: int, W: int, cy: float, cx: float, size: int) -> torch.Tensor:
66
+ if shape == "square":
67
+ return _square_keep(H, W, cy, cx, size)
68
+ if shape == "diamond":
69
+ return _diamond_keep(H, W, cy, cx, size)
70
+ raise RuntimeError(f"focus region unknown shape {shape!r}")
71
+
72
+
73
+ def _adjust_to_band(
74
+ shape: str,
75
+ H: int,
76
+ W: int,
77
+ cy: float,
78
+ cx: float,
79
+ size: int,
80
+ lo: float,
81
+ hi: float,
82
+ ) -> torch.Tensor:
83
+ """Grow/shrink until the covered fraction is in [lo, hi], or the closest discrete count if the band is empty."""
84
+ L = float(H * W)
85
+ size_lo, size_hi = (1, max(H, W)) if shape == "square" else (0, H + W)
86
+ size = min(max(int(size), size_lo), size_hi)
87
+ best = _build_keep(shape, H, W, cy, cx, size)
88
+ best_err = abs(float(best.sum().item()) / L - 0.5 * (lo + hi))
89
+ for _ in range(size_hi - size_lo + 2):
90
+ keep = _build_keep(shape, H, W, cy, cx, size)
91
+ n = int(keep.sum().item())
92
+ frac = float(n) / L
93
+ err = abs(frac - 0.5 * (lo + hi))
94
+ if err < best_err:
95
+ best, best_err = keep, err
96
+ if lo <= frac <= hi:
97
+ return keep
98
+ if n < 1:
99
+ size = min(size + 1, size_hi)
100
+ continue
101
+ if frac < lo:
102
+ nxt = min(size + 1, size_hi)
103
+ else:
104
+ nxt = max(size - 1, size_lo)
105
+ if nxt == size:
106
+ return keep
107
+ size = nxt
108
+ return best
109
+
110
+
111
+ def centered_focus_region(H: int, W: int, *, shape: str = "diamond", coverage: float = 0.20) -> torch.Tensor:
112
+ """Bool [1, H, W], True inside ONE blob centred on the grid covering ~`coverage` of the tokens; no randomness.
113
+
114
+ The default `z0_focus_region`: a UI that has no subject box sends this deterministic centre blob.
115
+ Band = coverage +- 0.02."""
116
+ if shape not in _SHAPES:
117
+ raise ValueError(f"centered_focus_region shape={shape!r} not in {_SHAPES}")
118
+ c = float(coverage)
119
+ if not (0.0 < c < 1.0) or not math.isfinite(c):
120
+ raise ValueError(f"centered_focus_region coverage must be in (0, 1); got {coverage!r}")
121
+ H, W = int(H), int(W)
122
+ if H < 2 or W < 2:
123
+ raise ValueError(f"centered_focus_region needs H, W >= 2; got {(H, W)}")
124
+ cy, cx = (H - 1) / 2.0, (W - 1) / 2.0
125
+ size = _size_for_coverage(shape, H, W, c)
126
+ keep = _adjust_to_band(shape, H, W, cy, cx, size, max(0.0, c - 0.02), min(1.0, c + 0.02))
127
+ if int(keep.sum().item()) < 1:
128
+ raise RuntimeError(f"centered_focus_region produced an empty blob at {(H, W)} coverage={c}")
129
+ return keep.unsqueeze(0).contiguous()
130
+
131
+
132
+ def coerce_z0_region(
133
+ region,
134
+ *,
135
+ batch: int,
136
+ height: int,
137
+ width: int,
138
+ device,
139
+ ) -> torch.Tensor | None:
140
+ """None → no-op. Else Bool [B,H,W] or [B,L=H*W] on ``device``. Wrong shape is a RuntimeError."""
141
+ if region is None:
142
+ return None
143
+ if not isinstance(region, torch.Tensor):
144
+ raise TypeError(
145
+ f"z0_focus_region must be a Bool Tensor or None; got {type(region).__name__}"
146
+ )
147
+ if region.dtype != torch.bool:
148
+ raise RuntimeError(f"z0_focus_region must be Bool; got dtype={region.dtype}")
149
+ B, H, W = int(batch), int(height), int(width)
150
+ L = H * W
151
+ if region.dim() == 2:
152
+ if tuple(region.shape) != (B, L):
153
+ raise RuntimeError(
154
+ f"z0_focus_region [B,L] must be [{B},{L}]; got {tuple(region.shape)}"
155
+ )
156
+ region = region.view(B, H, W)
157
+ elif region.dim() == 3:
158
+ if tuple(region.shape) != (B, H, W):
159
+ raise RuntimeError(
160
+ f"z0_focus_region [B,H,W] must be [{B},{H},{W}]; got {tuple(region.shape)}"
161
+ )
162
+ else:
163
+ raise RuntimeError(
164
+ f"z0_focus_region must be Bool [B,H,W] or [B,L]; got shape={tuple(region.shape)}"
165
+ )
166
+ return region.to(device=device)
167
+
168
+
169
+ def apply_z0_focus_region_embedding(
170
+ tokens: torch.Tensor,
171
+ region: torch.Tensor,
172
+ embedding: torch.Tensor,
173
+ ) -> torch.Tensor:
174
+ """ADD ``embedding`` to the z0 tokens inside ``region`` (Bool [B,H,W], True = subject). Tokens outside are
175
+ untouched; no token is ever replaced. Zero embedding = exact no-op."""
176
+ if not (isinstance(tokens, torch.Tensor) and tokens.dim() == 3):
177
+ raise TypeError(f"apply_z0_focus_region_embedding tokens must be Tensor[B,L,D]; got shape={getattr(tokens, 'shape', None)}")
178
+ if not (isinstance(region, torch.Tensor) and region.dim() == 3 and region.dtype == torch.bool):
179
+ raise TypeError(f"apply_z0_focus_region_embedding region must be Bool [B,H,W]; got "
180
+ f"shape={getattr(region, 'shape', None)} dtype={getattr(region, 'dtype', None)}")
181
+ if not (isinstance(embedding, torch.Tensor) and embedding.dim() == 1):
182
+ raise TypeError(f"apply_z0_focus_region_embedding embedding must be Tensor[D]; got shape={getattr(embedding, 'shape', None)}")
183
+ B, L, D = int(tokens.size(0)), int(tokens.size(1)), int(tokens.size(2))
184
+ Bh, H, W = int(region.size(0)), int(region.size(1)), int(region.size(2))
185
+ if Bh != B or H * W != L:
186
+ raise RuntimeError(f"apply_z0_focus_region_embedding shape mismatch: tokens [{B},{L},{D}] region [{Bh},{H},{W}] (need L=H*W={H * W})")
187
+ if int(embedding.size(0)) != D:
188
+ raise RuntimeError(f"apply_z0_focus_region_embedding embedding dim {int(embedding.size(0))} != token D={D}")
189
+ emb = embedding.to(device=tokens.device, dtype=tokens.dtype).view(1, 1, D)
190
+ return tokens + region.reshape(B, L).unsqueeze(-1).to(tokens.dtype) * emb
summaryformer_wrapper.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ from gta_streaming_kv_cache import SummaryKVCache
6
+ from summaryformer import Summaryformer
7
+
8
+
9
+ def _unpack_kv_conditional_dict(conditional_dict: dict) -> dict:
10
+ """Model kwargs from ``conditional_dict``.
11
+
12
+ All keys are optional: ``action_context``, ``fps``, ``z0_focus_region``.
13
+ ``z0_focus_region`` (Bool [B,hs,ws], True = subject) ADDS the focus embedding to those z0 tokens;
14
+ missing / None = no-op. Wrong type/shape is a RuntimeError at the model.
15
+ """
16
+ if not isinstance(conditional_dict, dict):
17
+ raise TypeError("conditional_dict must be a dict.")
18
+ out: dict = {}
19
+ action_context = conditional_dict.get("action_context", None)
20
+ if action_context is not None:
21
+ out["action_context"] = action_context
22
+ fps = conditional_dict.get("fps", None)
23
+ if fps is not None:
24
+ out["fps"] = fps
25
+ z0_focus_region = conditional_dict.get("z0_focus_region", None)
26
+ if z0_focus_region is not None:
27
+ if not isinstance(z0_focus_region, torch.Tensor):
28
+ raise TypeError(
29
+ f"conditional_dict['z0_focus_region'] must be a Tensor or omitted; "
30
+ f"got {type(z0_focus_region).__name__}"
31
+ )
32
+ out["z0_focus_region"] = z0_focus_region
33
+ return out
34
+
35
+
36
+ class SummaryformerWrapper(nn.Module):
37
+ """Thin wrapper around ``Summaryformer``.
38
+
39
+ One full-res stream, one trunk, KV-cached inference: ``forward_z0`` for the seed
40
+ frame, ``forward_body`` for a body frame.
41
+
42
+ Layout contract at this boundary (the model is BCFHW everywhere):
43
+ z_rest BFCHW ``[B,F,C,H,W]`` — renderer I/O layout, checked, never guessed
44
+ z0 ``[B,C,H,W]`` or F=1 in either 5-D layout
45
+ Outputs are BFCHW.
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ dim=1280,
51
+ ffn_dim=5120,
52
+ num_heads=20,
53
+ num_layers: int = 28,
54
+ *,
55
+ summary_tokens: int,
56
+ raw_window_frames: int,
57
+ summary_window_frames: int,
58
+ ):
59
+ super().__init__()
60
+ self.model = Summaryformer(
61
+ dim=dim,
62
+ ffn_dim=ffn_dim,
63
+ num_heads=num_heads,
64
+ num_layers=int(num_layers),
65
+ summary_tokens=int(summary_tokens),
66
+ raw_window_frames=int(raw_window_frames),
67
+ summary_window_frames=int(summary_window_frames),
68
+ )
69
+
70
+ def new_visual_kv_cache(self) -> SummaryKVCache:
71
+ """Unbuilt ``SummaryKVCache`` (one buffer) with this model's X / Y / W / depth / heads; call
72
+ ``.build(batch=, frame_tokens=Tf, dtype=, device=)`` per session."""
73
+ return SummaryKVCache(self.model)
74
+
75
+ def _as_bcfhw_rest(self, x: torch.Tensor, *, name: str) -> torch.Tensor:
76
+ """BFCHW ``[B,F,C,H,W]`` → BCFHW. C must sit at dim 2; a BCFHW input is an error."""
77
+ c = int(self.model.LATENT_CHANNELS)
78
+ if not (isinstance(x, torch.Tensor) and x.dim() == 5 and int(x.size(2)) == c):
79
+ raise TypeError(
80
+ f"{name} must be Tensor[B,F,C={c},H,W] (BFCHW); got "
81
+ f"shape={getattr(x, 'shape', None)}"
82
+ )
83
+ return x.permute(0, 2, 1, 3, 4).contiguous()
84
+
85
+ def _as_bcfhw_by_c(self, x: torch.Tensor, *, name: str, frames: int | None) -> torch.Tensor:
86
+ """4-D ``[B,C,H,W]`` or 5-D with C at dim 1 (BCFHW) / dim 2 (BFCHW) → BCFHW.
87
+
88
+ Both 5-D layouts are accepted because the model side is BCFHW while the
89
+ caller side is BFCHW; C decides, and when both dims equal C the
90
+ model-side layout (BCFHW) wins. ``frames`` pins F.
91
+ """
92
+ c = int(self.model.LATENT_CHANNELS)
93
+ if not isinstance(x, torch.Tensor):
94
+ raise TypeError(f"{name} must be a Tensor; got {type(x)}")
95
+ if x.dim() == 4 and int(x.size(1)) == c:
96
+ out = x.unsqueeze(2)
97
+ elif x.dim() == 5 and int(x.size(1)) == c:
98
+ out = x
99
+ elif x.dim() == 5 and int(x.size(2)) == c:
100
+ out = x.permute(0, 2, 1, 3, 4)
101
+ else:
102
+ raise TypeError(
103
+ f"{name} expects [B,C={c},H,W], [B,C,F,H,W] or [B,F,C,H,W]; got shape={tuple(x.shape)}"
104
+ )
105
+ if frames is not None and int(out.size(2)) != int(frames):
106
+ raise ValueError(f"{name} expects F={int(frames)}; got shape={tuple(x.shape)}")
107
+ return out.contiguous()
108
+
109
+ def _as_bcfhw_z0(self, x: torch.Tensor | None, *, name: str) -> torch.Tensor | None:
110
+ return None if x is None else self._as_bcfhw_by_c(x, name=name, frames=1)
111
+
112
+ def forward(self, *args, **kwargs):
113
+ raise TypeError("Use forward_z0 (seed frame) / forward_body (one body frame); both need a kv_cache.")
114
+
115
+ def forward_body(
116
+ self,
117
+ conditional_dict: dict,
118
+ x_rest: torch.Tensor,
119
+ t_rest: torch.Tensor,
120
+ *,
121
+ kv_cache,
122
+ absolute_start_frames: int | torch.Tensor,
123
+ ) -> torch.Tensor:
124
+ """KV-cached denoise of ONE body frame. The first pass of a frame donates (``begin_frame``); every pass
125
+ writes that RAW slot and reads ``[0 : end]``.
126
+
127
+ - ``x_rest``: BFCHW ``[B,1,C,H,W]``
128
+ - ``t_rest``: ``[B,1]``
129
+ - ``absolute_start_frames``: this frame's absolute id (>= 1; 0 is z0); a 0-d int64 device
130
+ tensor is the static-compile streaming form
131
+ - Returns BFCHW ``[B,1,C,H,W]``. Call ``kv_cache.commit_current_frame()`` after the clean recache
132
+ (cursor advance, no copy).
133
+ """
134
+ if not isinstance(kv_cache, SummaryKVCache):
135
+ raise RuntimeError(
136
+ "kv_cache must be a SummaryKVCache from wrapper.new_visual_kv_cache()."
137
+ )
138
+ x_rest_bcfhw = self._as_bcfhw_rest(x_rest, name="x_rest")
139
+ pred_rest_bcfhw = self.model._forward_kv_cached_z_rest(
140
+ x_rest=x_rest_bcfhw,
141
+ t_rest=t_rest,
142
+ kv_cache=kv_cache,
143
+ absolute_start_frames=absolute_start_frames if isinstance(absolute_start_frames, torch.Tensor) else int(absolute_start_frames),
144
+ **_unpack_kv_conditional_dict(conditional_dict),
145
+ )
146
+ return pred_rest_bcfhw.permute(0, 2, 1, 3, 4).contiguous()
147
+
148
+ def forward_z0(
149
+ self,
150
+ x_z0: torch.Tensor,
151
+ conditional_dict: dict,
152
+ t_z0: torch.Tensor,
153
+ kv_cache,
154
+ ) -> torch.Tensor:
155
+ """
156
+ KV-cached **z0** denoise (seed / image stream). Writes record(0) into the Z0 slot on every pass and
157
+ reads ``[0 : REC_z0]``; call ``kv_cache.note_z0_written()`` after the clean recache.
158
+
159
+ Image path still carries ``sum(0)`` (within-frame only).
160
+
161
+ - ``x_z0``: ``[B,C,H,W]`` / ``[B,1,C,H,W]`` / ``[B,C,1,H,W]``
162
+ - ``t_z0``: ``[B]``
163
+ - Returns ``[B,1,C,H,W]`` (BFCHW, F=1).
164
+ """
165
+ if not (isinstance(t_z0, torch.Tensor) and t_z0.dim() == 1):
166
+ raise TypeError(
167
+ f"t_z0 must be Tensor[B]; got "
168
+ f"type={type(t_z0)} shape={getattr(t_z0, 'shape', None)}"
169
+ )
170
+ x_bcfhw = self._as_bcfhw_z0(x_z0, name="x_z0")
171
+ if x_bcfhw is None:
172
+ raise TypeError("forward_z0 requires x_z0.")
173
+ if int(t_z0.size(0)) != int(x_bcfhw.size(0)):
174
+ raise RuntimeError(
175
+ f"t_z0 batch mismatch: got B={int(t_z0.size(0))}, "
176
+ f"expected {int(x_bcfhw.size(0))}"
177
+ )
178
+ if not isinstance(kv_cache, SummaryKVCache):
179
+ raise RuntimeError(
180
+ "forward_z0 requires a SummaryKVCache from wrapper.new_visual_kv_cache()."
181
+ )
182
+
183
+ model_kwargs = _unpack_kv_conditional_dict(conditional_dict)
184
+ pred_bcfhw = self.model._forward_kv_cached_z0(
185
+ x_z0=x_bcfhw,
186
+ t_z0=t_z0,
187
+ kv_cache=kv_cache,
188
+ **model_kwargs,
189
+ )
190
+ return pred_bcfhw.permute(0, 2, 1, 3, 4).contiguous()
191
+
192
+ @staticmethod
193
+ def mark_streaming_caches_static(*caches) -> int:
194
+ """Pin leaf addresses of the visual KV cache for cudagraphs.
195
+
196
+ Call once after caches are finalized, before the first compiled forward.
197
+ Accepts a visual KV cache or ``None``.
198
+ """
199
+ marked = 0
200
+ for cache in caches:
201
+ if cache is None:
202
+ continue
203
+ if isinstance(cache, SummaryKVCache):
204
+ # end_dev is a graph input of the compiled stream (one prefix length).
205
+ for scalar in cache.device_scalars():
206
+ torch._dynamo.mark_static_address(scalar)
207
+ marked += 1
208
+ layers = getattr(cache, "layers", cache)
209
+ try:
210
+ layer_iter = list(layers)
211
+ except TypeError:
212
+ continue
213
+ for layer in layer_iter:
214
+ if not isinstance(layer, dict):
215
+ continue
216
+ for t in layer.values():
217
+ if isinstance(t, torch.Tensor):
218
+ torch._dynamo.mark_static_address(t)
219
+ marked += 1
220
+ return marked