File size: 8,435 Bytes
92e95ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# Copyright 2026 The Robbyant Team Authors. All rights reserved.

"""Online streaming with a transactional paged KV cache."""

import numpy as np
import torch
from torch.nn import functional as F

from ..layers.flashinfer_cache import PagedKVCache
from ..layers.rope import apply_rotary_emb
from ..utils.pose_enc import decode_predictions
from .base import finish_global, join_images, pack_tokens, unpack_tokens


def prepare_global(block, tokens, rope):
    batch, frames, patches, channels = tokens.shape
    packed = pack_tokens(tokens, 5)
    frequencies = pack_tokens(rope.reshape(1, 1, frames, patches, -1), 5)
    query, key, value = block.attn.project(block.norm1(packed))
    return (
        packed,
        apply_rotary_emb(query, frequencies),
        apply_rotary_emb(key, frequencies),
        value,
    )


class Stream:
    """One stream owns one model. Only persistent arrivals advance its clock."""

    def __init__(
        self, model, *, output_device="cpu", offload_kv=False, depth_chunk_size=None
    ):
        self.model = model
        self.output_device = model._output_device(output_device)
        self._offload_kv = bool(offload_kv)
        self._depth_chunk_size = depth_chunk_size
        self._pending = []
        self._count = 0
        self._paged = None
        self._camera = None
        self._closed = False

    @property
    def frame_count(self):
        return self._count + len(self._pending)

    @property
    def ready(self):
        return self._count >= self.model.config.scale_frames

    def _check(self):
        if self._closed or self.model._stream is not self:
            raise RuntimeError("stream is closed or no longer owns this model")
        if self.model._native.training:
            raise RuntimeError("model must remain in eval mode")

    @torch.inference_mode()
    def online(self, frame, *, persistent=True):
        self._check()
        if not persistent and not self.ready:
            raise ValueError("the initialization prefix must be persistent")
        if self.frame_count >= self.model.config.max_frames:
            raise ValueError("committed temporal capacity reached; start a new stream")
        if self.model._compiled is not None:
            torch.compiler.cudagraph_mark_step_begin()
        try:
            return self._online(frame, persistent=persistent)
        finally:
            if self._paged is not None:
                self._paged.rollback()

    def _online(self, frame, *, persistent):
        image = self.model.prepare(frame)
        if image.shape[1] != 1:
            raise ValueError("online accepts exactly one frame per call")
        image = image.detach().to(self.model.device, copy=True)
        if not self.ready and len(self._pending) + 1 < self.model.config.scale_frames:
            self._pending.append(image)
            return None
        images = join_images([*self._pending, image])
        count, height, width = images.shape[1], *images.shape[-2:]
        native = self.model._native
        agg = native.aggregator
        needed = {4, 11, 17, 23} if native.depth_head is not None else {23}
        features, prefix_kv = {}, []
        if self._paged is not None:
            self._paged.begin()
        with torch.autocast("cuda", dtype=torch.bfloat16, enabled=images.is_cuda):
            tokens, spatial, temporal = agg.embed(images, self._count)
            patches, channels = tokens.shape[-2:]
            for layer, block in enumerate(agg.global_blocks):
                frame_tokens = agg.frame_blocks[layer](
                    tokens.reshape(count, patches, channels), pos=spatial
                ).reshape(1, count, patches, channels)
                compiled = self.model._compiled
                if compiled is None:
                    packed, query, key, value = prepare_global(
                        block, frame_tokens, temporal
                    )
                else:
                    packed, query, key, value = compiled[layer][0](
                        frame_tokens, temporal
                    )
                if self._paged is None:
                    output = F.scaled_dot_product_attention(query, key, value)
                    output = output[0].transpose(0, 1)
                    k_unpacked = unpack_tokens(key, count, patches, 5)
                    v_unpacked = unpack_tokens(value, count, patches, 5)
                    if self._offload_kv:
                        k_unpacked = k_unpacked.to(device="cpu", dtype=torch.bfloat16)
                        v_unpacked = v_unpacked.to(device="cpu", dtype=torch.bfloat16)
                    prefix_kv.append((k_unpacked, v_unpacked))
                else:
                    dtype = self._paged.dtype
                    natural_key = unpack_tokens(key, 1, patches, 5)[0, :, 0].transpose(
                        0, 1
                    )
                    natural_value = unpack_tokens(value, 1, patches, 5)[
                        0, :, 0
                    ].transpose(0, 1)
                    self._paged.write(
                        layer, natural_key.to(dtype), natural_value.to(dtype)
                    )
                    output = self._paged.run(layer, query[0].transpose(0, 1).to(dtype))
                tokens = (
                    finish_global(block, packed, output)
                    if compiled is None
                    else compiled[layer][1](packed, output)
                )
                tokens = unpack_tokens(tokens, count, patches, 5)
                if layer in needed:
                    features[layer] = torch.cat((frame_tokens, tokens), dim=-1)
        with torch.autocast("cuda", enabled=False):
            poses, camera = native.camera_head(features[23].float(), self._camera)
            output = {"pose_enc": poses}
            if native.depth_head is not None:
                dpt_kwargs = {}
                if self._depth_chunk_size is not None:
                    dpt_kwargs["frames_chunk_size"] = self._depth_chunk_size
                depth, confidence = native.depth_head(
                    [features[i].float() for i in (4, 11, 17, 23)],
                    images=images.float(),
                    patch_start_idx=5,
                    **dpt_kwargs,
                )
                output.update(depth=depth, depth_conf=confidence)
        result = decode_predictions(
            output, (height, width), output_device=self.output_device
        )
        del features, output, poses
        result["frame_indices"] = (
            np.arange(self._count, self._count + count)
            if self.output_device.type == "cpu"
            else torch.arange(
                self._count, self._count + count, device=self.output_device
            )
        )
        if not persistent:
            return result
        pool = self._paged
        if pool is None:
            key = prefix_kv[0][0]
            pool = PagedKVCache(
                layers=len(prefix_kv),
                heads=key.shape[1],
                dim=key.shape[-1],
                patches=patches - 5,
                scale=self.model.config.scale_frames,
                window=self.model.config.sliding_window,
                capacity=self.model.config.max_frames,
                device=images.device,
                offload_kv=self._offload_kv,
            )
            for index in range(count):
                pool.begin()
                for layer in range(len(prefix_kv)):
                    key, value = prefix_kv[layer]
                    pool.write(
                        layer,
                        key[0, :, index].transpose(0, 1).to(pool.dtype),
                        value[0, :, index].transpose(0, 1).to(pool.dtype),
                    )
                    if index == count - 1:
                        prefix_kv[layer] = None
                pool.commit()
            prefix_kv.clear()
        else:
            pool.commit()
        self._paged = pool
        self._camera = camera
        self._count += count
        self._pending.clear()
        return result

    def close(self):
        if self._closed:
            return
        self._paged = self._camera = None
        self._pending.clear()
        self._closed = True
        if self.model._stream is self:
            self.model._stream = None

    def __enter__(self):
        self._check()
        return self

    def __exit__(self, *_exception):
        self.close()