yasserDahou commited on
Commit
4f2517b
·
verified ·
1 Parent(s): 2298175

Initial release: Falcon Perception open-vocabulary segmentation

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ main_fig.jpg filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ pipeline_tag: mask-generation
4
+ library_name: transformers
5
+ tags:
6
+ - falcon
7
+ - segmentation
8
+ - vision-language
9
+ - open-vocabulary
10
+ ---
11
+
12
+ <img src="main_fig.jpg" width="480" alt="Falcon Perception"/>
13
+
14
+
15
+ Falcon Perception is a **dense early-fusion vision-language model** for **open-vocabulary segmentation**. Given an image and a natural-language query, it segments **all matching objects** and returns pixel-accurate masks.
16
+
17
+ The model **jointly processes image patches and text tokens** in a single transformer, then autoregressively predicts **`<|coord|>`**, **`<|size|>`**, and **`<|seg|>`** tokens for each detected object. Each `<|seg|>` token acts as a **mask query**: its hidden state is projected and dot-producted against upsampled image features to produce a binary mask (i.e. no autoregressive polygon generation needed).
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ pip install transformers torch einops pycocotools
23
+ ```
24
+
25
+ Requires **PyTorch 2.5+** (FlexAttention).
26
+
27
+ ## Quick Start
28
+
29
+ ```python
30
+ import torch
31
+ from transformers import AutoModelForCausalLM
32
+ from PIL import Image
33
+
34
+ model = AutoModelForCausalLM.from_pretrained(
35
+ "tiiuae/falcon-perception",
36
+ trust_remote_code=True,
37
+ dtype=torch.bfloat16,
38
+ device_map="cuda",
39
+ )
40
+
41
+ image = Image.open("photo.jpg")
42
+ results = model.generate(image, "cat")
43
+
44
+ for pred in results[0]:
45
+ print(pred["xy"]) # {"x": 0.35, "y": 0.42}
46
+ print(pred["hw"]) # {"h": 0.15, "w": 0.12}
47
+ print(pred["mask_rle"]) # {"counts": "...", "size": [H, W]}
48
+ ```
49
+
50
+ > The first `generate()` call is slower (~15-20 s) because `torch.compile` builds optimized kernels. Subsequent calls run in ~1-2 s.
51
+
52
+
53
+ ### `model.generate(images, queries, **kwargs)`
54
+
55
+ | Parameter | Type | Default | Description |
56
+ |---|---|---|---|
57
+ | `images` | `PIL.Image` or `list` | required | Single image or list of images (PIL, path, or URL) |
58
+ | `queries` | `str` or `list[str]` | required | Query string(s), one per image |
59
+ | `max_new_tokens` | `int` | `2048` | Maximum generation steps |
60
+ | `min_dimension` | `int` | `256` | Minimum image side after resize |
61
+ | `max_dimension` | `int` | `1024` | Maximum image side after resize |
62
+ | `compile` | `bool` | `True` | Auto torch.compile on first call |
63
+ | `segm_threshold` | `float` | `0.5` | Sigmoid threshold for binary masks |
64
+
65
+ **Returns:** `list[list[dict]]` — one list per image, each containing detection dicts:
66
+
67
+ ```python
68
+ {
69
+ "xy": {"x": float, "y": float}, # center (normalized 0-1)
70
+ "hw": {"h": float, "w": float}, # size (normalized 0-1)
71
+ "mask_rle": {"counts": str, "size": [H, W]}, # COCO RLE at original resolution
72
+ }
73
+ ```
74
+
75
+
76
+ ## Visualizing Masks
77
+
78
+ ```python
79
+ import numpy as np
80
+ from pycocotools import mask as mask_utils
81
+ from PIL import Image, ImageDraw
82
+
83
+ def overlay_masks(image, detections, alpha=0.55):
84
+ """Overlay RLE masks on an image with colored fills and black borders."""
85
+ overlay = image.convert("RGBA").copy()
86
+ colors = [
87
+ (255, 60, 60), (60, 220, 60), (50, 120, 255),
88
+ (255, 200, 40), (220, 60, 220), (60, 220, 220),
89
+ ]
90
+ for i, det in enumerate(detections):
91
+ m = mask_utils.decode(det["mask_rle"]).astype(bool)
92
+ r, g, b = colors[i % len(colors)]
93
+ fill = np.zeros((*m.shape, 4), dtype=np.uint8)
94
+ fill[m] = [r, g, b, int(255 * alpha)]
95
+ overlay = Image.alpha_composite(overlay, Image.fromarray(fill))
96
+ # black border around mask
97
+ border = np.zeros((*m.shape, 4), dtype=np.uint8)
98
+ ky = m[1:, :] != m[:-1, :]
99
+ kx = m[:, 1:] != m[:, :-1]
100
+ edge = np.zeros_like(m)
101
+ edge[1:, :] |= ky; edge[:-1, :] |= ky
102
+ edge[:, 1:] |= kx; edge[:, :-1] |= kx
103
+ border[edge] = [0, 0, 0, 200]
104
+ overlay = Image.alpha_composite(overlay, Image.fromarray(border))
105
+ return overlay
106
+
107
+ image = Image.open("photo.jpg")
108
+ results = model.generate(image, "cat")
109
+ overlay_masks(image, results[0]).save("output.png")
110
+ ```
111
+
112
+ ## Performance
113
+
114
+ ### PBench
115
+
116
+
117
+
118
+
119
+ ## Citation
120
+
anyup.py ADDED
@@ -0,0 +1,543 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ AnyUp – flattened into a single module for HuggingFace trust_remote_code compatibility.
3
+
4
+ Original package structure:
5
+ anyup/layers/convolutions.py → ResBlock
6
+ anyup/layers/feature_unification.py → LearnedFeatureUnification
7
+ anyup/layers/positional_encoding.py → RoPE (AnyUp-internal)
8
+ anyup/layers/attention/attention_masking.py → window2d, compute_attention_mask, get_attention_mask_mod
9
+ anyup/layers/attention/chunked_attention.py → FlexCrossAttention, CrossAttentionBlock
10
+ anyup/model.py → AnyUp
11
+ """
12
+
13
+ import torch
14
+ import torch.nn as nn
15
+ import torch.nn.functional as F
16
+ import einops as E
17
+ from typing import Tuple
18
+ from functools import lru_cache
19
+ from torch.nn.attention.flex_attention import flex_attention
20
+ from torch.distributed.tensor import DTensor, distribute_tensor
21
+
22
+ compiled_flex_attn_prefill = torch.compile(flex_attention, dynamic=True)
23
+
24
+ # ---------------------------------------------------------------------------
25
+ # ResBlock (from layers/convolutions.py)
26
+ # ---------------------------------------------------------------------------
27
+
28
+ class ResBlock(nn.Module):
29
+ def __init__(
30
+ self,
31
+ in_channels,
32
+ out_channels,
33
+ kernel_size=3,
34
+ num_groups=8,
35
+ pad_mode="zeros",
36
+ norm_fn=None,
37
+ activation_fn=nn.SiLU,
38
+ use_conv_shortcut=False,
39
+ ):
40
+ super().__init__()
41
+ N = (lambda c: norm_fn(num_groups, c)) if norm_fn else (lambda c: nn.Identity())
42
+ p = kernel_size // 2
43
+ self.block = nn.Sequential(
44
+ N(in_channels),
45
+ activation_fn(),
46
+ nn.Conv2d(
47
+ in_channels,
48
+ out_channels,
49
+ kernel_size,
50
+ padding=p,
51
+ padding_mode=pad_mode,
52
+ bias=False,
53
+ ),
54
+ N(out_channels),
55
+ activation_fn(),
56
+ nn.Conv2d(
57
+ out_channels,
58
+ out_channels,
59
+ kernel_size,
60
+ padding=p,
61
+ padding_mode=pad_mode,
62
+ bias=False,
63
+ ),
64
+ )
65
+ self.shortcut = (
66
+ nn.Conv2d(in_channels, out_channels, 1, bias=False, padding_mode=pad_mode)
67
+ if use_conv_shortcut or in_channels != out_channels
68
+ else nn.Identity()
69
+ )
70
+
71
+ def forward(self, x):
72
+ return self.block(x) + self.shortcut(x)
73
+
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # LearnedFeatureUnification (from layers/feature_unification.py)
77
+ # ---------------------------------------------------------------------------
78
+
79
+ compute_basis_size = {
80
+ "gauss_deriv": lambda order, mirror: ((order + 1) * (order + 2))
81
+ // (1 if mirror else 2)
82
+ }
83
+
84
+
85
+ def herme_vander_torch(z, m):
86
+ He0 = z.new_ones(z.shape)
87
+ if m == 0:
88
+ return He0[:, None]
89
+ H = [He0, z]
90
+ for n in range(1, m):
91
+ H.append(z * H[-1] - n * H[-2])
92
+ return torch.stack(H, 1)
93
+
94
+
95
+ def gauss_deriv(
96
+ max_order,
97
+ device,
98
+ dtype,
99
+ kernel_size,
100
+ sigma=None,
101
+ include_negations=False,
102
+ scale_magnitude=True,
103
+ ):
104
+ sigma = (kernel_size // 2) / 1.645 if sigma is None else sigma
105
+ if kernel_size % 2 == 0:
106
+ raise ValueError("ksize must be odd")
107
+ half = kernel_size // 2
108
+ x = torch.arange(-half, half + 1, dtype=dtype, device=device)
109
+ z = x / sigma
110
+ g = torch.exp(-0.5 * z**2) / (sigma * (2.0 * torch.pi) ** 0.5)
111
+ He = herme_vander_torch(z, max_order)
112
+ derivs_1d = [
113
+ (((-1) ** n) / (sigma**n) if scale_magnitude else (-1) ** n) * He[:, n] * g
114
+ for n in range(max_order + 1)
115
+ ]
116
+ bank = []
117
+ for o in range(max_order + 1):
118
+ for i in range(o + 1):
119
+ K = torch.outer(derivs_1d[o - i], derivs_1d[i])
120
+ bank.append(K)
121
+ if include_negations:
122
+ bank.append(-K)
123
+ return torch.stack(bank, 0)
124
+
125
+
126
+ class LearnedFeatureUnification(nn.Module):
127
+ def __init__(
128
+ self,
129
+ out_channels: int,
130
+ kernel_size: int = 3,
131
+ init_gaussian_derivatives: bool = False,
132
+ ):
133
+ super().__init__()
134
+ self.out_channels = out_channels
135
+ self.kernel_size = kernel_size
136
+ if init_gaussian_derivatives:
137
+ order = 0
138
+ while compute_basis_size["gauss_deriv"](order, False) < out_channels:
139
+ order += 1
140
+ print(
141
+ f"FeatureUnification: initializing with Gaussian derivative basis of order {order}"
142
+ )
143
+ self.basis = nn.Parameter(
144
+ gauss_deriv(
145
+ order,
146
+ device="cpu",
147
+ dtype=torch.float32,
148
+ kernel_size=kernel_size,
149
+ scale_magnitude=False,
150
+ )[:out_channels, None]
151
+ )
152
+ else:
153
+ self.basis = nn.Parameter(
154
+ torch.randn(out_channels, 1, kernel_size, kernel_size)
155
+ )
156
+
157
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
158
+ b, c, h, w = features.shape
159
+ x = self._depthwise_conv(features, self.basis, self.kernel_size).view(
160
+ b, self.out_channels, c, h, w
161
+ )
162
+ attn = F.softmax(x, dim=1)
163
+ return attn.mean(dim=2)
164
+
165
+ @staticmethod
166
+ def _depthwise_conv(feats, basis, k):
167
+ b, c, h, w = feats.shape
168
+ p = k // 2
169
+ x = F.pad(feats, (p, p, p, p), value=0)
170
+ x = F.conv2d(x, basis.repeat(c, 1, 1, 1), groups=c)
171
+ mask = torch.ones(1, 1, h, w, dtype=x.dtype, device=x.device)
172
+ denom = F.conv2d(
173
+ F.pad(mask, (p, p, p, p), value=0),
174
+ torch.ones(1, 1, k, k, device=x.device, dtype=x.dtype),
175
+ )
176
+ return x / denom
177
+
178
+
179
+ # ---------------------------------------------------------------------------
180
+ # RoPE (from layers/positional_encoding.py) – AnyUp-internal, separate from
181
+ # the main model's 3D RoPE
182
+ # ---------------------------------------------------------------------------
183
+
184
+ def _rotate_half(x):
185
+ x1, x2 = x.chunk(2, dim=-1)
186
+ return torch.cat((-x2, x1), dim=-1)
187
+
188
+
189
+ class AnyUpRoPE(nn.Module):
190
+ def __init__(
191
+ self,
192
+ dim: int,
193
+ theta: int = 100,
194
+ ):
195
+ super().__init__()
196
+ self.dim = dim
197
+ self.theta = theta
198
+ self.freqs = nn.Parameter(torch.empty(2, self.dim))
199
+
200
+ def _device_weight_init(self):
201
+ if isinstance(self.freqs, DTensor):
202
+ target_device = self.freqs.to_local().device
203
+ target_dtype = self.freqs.to_local().dtype
204
+ else:
205
+ target_device = self.freqs.device
206
+ target_dtype = self.freqs.dtype
207
+
208
+ freqs_1d = self.theta ** torch.linspace(
209
+ 0, -1, self.dim // 4, device=target_device, dtype=target_dtype
210
+ )
211
+ freqs_1d = torch.cat([freqs_1d, freqs_1d])
212
+ freqs_2d = torch.zeros(2, self.dim, device=target_device, dtype=target_dtype)
213
+ freqs_2d[0, : self.dim // 2] = freqs_1d
214
+ freqs_2d[1, -self.dim // 2 :] = freqs_1d
215
+ freqs_2d.mul_(2 * torch.pi)
216
+
217
+ with torch.no_grad():
218
+ if isinstance(self.freqs, DTensor):
219
+ dist_freqs = distribute_tensor(
220
+ freqs_2d, self.freqs.device_mesh, placements=self.freqs.placements
221
+ )
222
+ self.freqs.to_local().copy_(dist_freqs.to_local())
223
+ else:
224
+ self.freqs.copy_(freqs_2d)
225
+
226
+ def forward(self, x: torch.Tensor, coords: torch.Tensor) -> torch.Tensor:
227
+ angle = coords @ self.freqs
228
+ return x * angle.cos() + _rotate_half(x) * angle.sin()
229
+
230
+
231
+ # ---------------------------------------------------------------------------
232
+ # Attention masking (from layers/attention/attention_masking.py)
233
+ # ---------------------------------------------------------------------------
234
+
235
+ def window2d(
236
+ low_res: int | Tuple[int, int],
237
+ high_res: int | Tuple[int, int],
238
+ ratio: float,
239
+ *,
240
+ device: str = "cpu",
241
+ ) -> torch.Tensor:
242
+ """Calculate the lower and upper bounds of row and col for each pixel/position"""
243
+ if isinstance(high_res, int):
244
+ H = W = high_res
245
+ else:
246
+ H, W = high_res
247
+ if isinstance(low_res, int):
248
+ Lh = Lw = low_res
249
+ else:
250
+ Lh, Lw = low_res
251
+
252
+ r_pos = (torch.arange(H, device=device, dtype=torch.float32) + 0.5) / H
253
+ c_pos = (torch.arange(W, device=device, dtype=torch.float32) + 0.5) / W
254
+ pos_r, pos_c = torch.meshgrid(r_pos, c_pos, indexing="ij")
255
+
256
+ r_lo = (pos_r - ratio).clamp(0.0, 1.0)
257
+ r_hi = (pos_r + ratio).clamp(0.0, 1.0)
258
+ c_lo = (pos_c - ratio).clamp(0.0, 1.0)
259
+ c_hi = (pos_c + ratio).clamp(0.0, 1.0)
260
+
261
+ r0 = (r_lo * Lh).floor().long()
262
+ r1 = (r_hi * Lh).ceil().long()
263
+ c0 = (c_lo * Lw).floor().long()
264
+ c1 = (c_hi * Lw).ceil().long()
265
+
266
+ return torch.stack([r0, r1, c0, c1], dim=2)
267
+
268
+
269
+ @lru_cache
270
+ def compute_attention_mask(
271
+ high_res_h, high_res_w, low_res_h, low_res_w, window_size_ratio, device="cpu"
272
+ ):
273
+ h, w = high_res_h, high_res_w
274
+ h_, w_ = low_res_h, low_res_w
275
+
276
+ windows = window2d(
277
+ low_res=(h_, w_), high_res=(h, w), ratio=window_size_ratio, device=device
278
+ )
279
+
280
+ q = h * w
281
+
282
+ r0 = windows[..., 0].reshape(q, 1)
283
+ r1 = windows[..., 1].reshape(q, 1)
284
+ c0 = windows[..., 2].reshape(q, 1)
285
+ c1 = windows[..., 3].reshape(q, 1)
286
+
287
+ rows = torch.arange(h_, device=device)
288
+ cols = torch.arange(w_, device=device)
289
+
290
+ row_ok = (rows >= r0) & (rows < r1)
291
+ col_ok = (cols >= c0) & (cols < c1)
292
+
293
+ attention_mask = (
294
+ (row_ok.unsqueeze(2) & col_ok.unsqueeze(1))
295
+ .reshape(q, h_ * w_)
296
+ .to(dtype=torch.bool)
297
+ )
298
+
299
+ return ~attention_mask
300
+
301
+
302
+ def get_attention_mask_mod(
303
+ high_res_h, high_res_w, low_res_h, low_res_w, window_size_ratio=0.1, device="cpu"
304
+ ):
305
+ """Window Attention as above but for FlexAttention."""
306
+ h, w = high_res_h, high_res_w
307
+ h_, w_ = low_res_h, low_res_w
308
+
309
+ windows = window2d(
310
+ low_res=(h_, w_),
311
+ high_res=(h, w),
312
+ ratio=window_size_ratio,
313
+ device=device,
314
+ )
315
+
316
+ r0 = windows[..., 0]
317
+ r1 = windows[..., 1]
318
+ c0 = windows[..., 2]
319
+ c1 = windows[..., 3]
320
+
321
+ def _mask_mod(b_idx, h_idx, q_idx, kv_idx):
322
+ q_r_idx = q_idx // w
323
+ q_c_idx = q_idx % w
324
+ kv_r_idx = kv_idx // w_
325
+ kv_c_idx = kv_idx % w_
326
+ row_lower = kv_r_idx >= r0[q_r_idx, q_c_idx]
327
+ row_upper = kv_r_idx < r1[q_r_idx, q_c_idx]
328
+ col_lower = kv_c_idx >= c0[q_r_idx, q_c_idx]
329
+ col_upper = kv_c_idx < c1[q_r_idx, q_c_idx]
330
+
331
+ return row_lower & row_upper & col_lower & col_upper
332
+
333
+ return _mask_mod
334
+
335
+
336
+ # ---------------------------------------------------------------------------
337
+ # Cross-attention (from layers/attention/chunked_attention.py)
338
+ # ---------------------------------------------------------------------------
339
+
340
+ class AttentionWrapper(nn.Module):
341
+ def __init__(self, qk_dim: int):
342
+ super().__init__()
343
+ self.in_proj_weight = nn.Parameter(torch.empty([qk_dim * 3, qk_dim]))
344
+ self.in_proj_bias = nn.Parameter(torch.empty([qk_dim * 3]))
345
+
346
+ def forward(self, x_q, x_k, x_v):
347
+ w_q, w_k, w_v = self.in_proj_weight.chunk(3, dim=0)
348
+ b_q, b_k, b_v = self.in_proj_bias.chunk(3)
349
+ x_q = x_q @ w_q.T + b_q
350
+ x_k = x_k @ w_k.T + b_k
351
+ return x_q, x_k, x_v
352
+
353
+
354
+ class FlexCrossAttention(nn.Module):
355
+ def __init__(self, qk_dim: int, num_heads: int, **kwargs):
356
+ super().__init__()
357
+ self.dim = qk_dim
358
+ self.num_head = num_heads
359
+ self.norm_q = nn.RMSNorm(qk_dim)
360
+ self.norm_k = nn.RMSNorm(qk_dim)
361
+ self.attention = AttentionWrapper(qk_dim)
362
+
363
+ def forward(self, query, key, value, mask=None, **kwargs):
364
+ x_q = self.norm_q(query)
365
+ x_k = self.norm_k(key)
366
+ x_q, x_k, x_v = self.attention(x_q, x_k, value)
367
+ x_q = E.rearrange(x_q, "b HW (h d) -> b h HW d", h=self.num_head)
368
+ x_k = E.rearrange(x_k, "b hw (h d) -> b h hw d", h=self.num_head)
369
+
370
+ x_v = E.rearrange(value, "b hw (h d) -> b h hw d", h=self.num_head)
371
+ output = compiled_flex_attn_prefill(x_q, x_k, x_v, block_mask=mask)
372
+ output = E.rearrange(output, "b h hw d -> b hw (h d)")
373
+
374
+ return output
375
+
376
+
377
+ class CrossAttentionBlock(nn.Module):
378
+ def __init__(
379
+ self,
380
+ qk_dim,
381
+ num_heads,
382
+ window_ratio: float = 0.1,
383
+ **kwargs,
384
+ ):
385
+ super().__init__()
386
+ self.cross_attn = FlexCrossAttention(qk_dim, num_heads)
387
+ self.window_ratio = window_ratio
388
+ self.conv2d = nn.Conv2d(
389
+ qk_dim, qk_dim, kernel_size=3, stride=1, padding=1, bias=False
390
+ )
391
+
392
+ def forward(self, q, k, v, block_mask, **kwargs):
393
+ b, _, h, w = q.shape
394
+
395
+ q = self.conv2d(q)
396
+ q = E.rearrange(q, "b c h w -> b (h w) c")
397
+ k = E.rearrange(k, "b c h w -> b (h w) c")
398
+ v = E.rearrange(v, "b c h w -> b (h w) c")
399
+
400
+ features = self.cross_attn(q, k, v, mask=block_mask)
401
+ return E.rearrange(features, "b (h w) c -> b c h w", h=h, w=w)
402
+
403
+
404
+ # ---------------------------------------------------------------------------
405
+ # AnyUp (from model.py)
406
+ # ---------------------------------------------------------------------------
407
+
408
+ IMAGENET_MEAN = torch.tensor([0.485, 0.456, 0.406]).reshape(1, 3, 1, 1)
409
+ IMAGENET_STD = torch.tensor([0.229, 0.224, 0.225]).reshape(1, 3, 1, 1)
410
+
411
+
412
+ def create_coordinate(h, w, start=0.0, end=1.0, device=None, dtype=None):
413
+ x = torch.linspace(start, end, h, device=device, dtype=dtype)
414
+ y = torch.linspace(start, end, w, device=device, dtype=dtype)
415
+ xx, yy = torch.meshgrid(x, y, indexing="ij")
416
+ return torch.stack((xx, yy), -1).view(1, h * w, 2)
417
+
418
+
419
+ class AnyUp(nn.Module):
420
+ def __init__(
421
+ self,
422
+ input_dim=3,
423
+ qk_dim=128,
424
+ kernel_size=1,
425
+ kernel_size_lfu=5,
426
+ window_ratio=0.1,
427
+ num_heads=4,
428
+ init_gaussian_derivatives=False,
429
+ **kwargs,
430
+ ):
431
+ super().__init__()
432
+ self.qk_dim = qk_dim
433
+ self.window_ratio = window_ratio
434
+ self._rb_args = dict(
435
+ kernel_size=1,
436
+ num_groups=8,
437
+ pad_mode="reflect",
438
+ norm_fn=nn.GroupNorm,
439
+ activation_fn=nn.SiLU,
440
+ )
441
+
442
+ self.image_encoder = self._make_encoder(input_dim, kernel_size)
443
+ self.key_encoder = self._make_encoder(qk_dim, 1)
444
+ self.query_encoder = self._make_encoder(qk_dim, 1)
445
+ self.key_features_encoder = self._make_encoder(
446
+ None,
447
+ 1,
448
+ first_layer_k=kernel_size_lfu,
449
+ init_gaussian_derivatives=init_gaussian_derivatives,
450
+ )
451
+
452
+ self.cross_decode = CrossAttentionBlock(
453
+ qk_dim=qk_dim, num_heads=num_heads, window_ratio=window_ratio
454
+ )
455
+ self.aggregation = self._make_encoder(2 * qk_dim, 3)
456
+
457
+ self.rope = AnyUpRoPE(qk_dim)
458
+ self.rope._device_weight_init()
459
+
460
+ self._compiled_encoders = False
461
+
462
+ def compile(self, *, mode: str | None = None, dynamic: bool = True):
463
+ if self._compiled_encoders:
464
+ return self
465
+ self.image_encoder = torch.compile(self.image_encoder, dynamic=dynamic, mode=mode)
466
+ self.key_encoder = torch.compile(self.key_encoder, dynamic=dynamic, mode=mode)
467
+ self.query_encoder = torch.compile(self.query_encoder, dynamic=dynamic, mode=mode)
468
+ self.key_features_encoder = torch.compile(
469
+ self.key_features_encoder, dynamic=dynamic, mode=mode
470
+ )
471
+ self.aggregation = torch.compile(self.aggregation, dynamic=dynamic, mode=mode)
472
+ self._compiled_encoders = True
473
+ return self
474
+
475
+ def _make_encoder(
476
+ self, in_ch, k, layers=2, first_layer_k=0, init_gaussian_derivatives=False
477
+ ):
478
+ pre = (
479
+ nn.Conv2d(
480
+ in_ch,
481
+ self.qk_dim,
482
+ k,
483
+ padding=k // 2,
484
+ padding_mode="reflect",
485
+ bias=False,
486
+ )
487
+ if first_layer_k == 0
488
+ else LearnedFeatureUnification(
489
+ self.qk_dim,
490
+ first_layer_k,
491
+ init_gaussian_derivatives=init_gaussian_derivatives,
492
+ )
493
+ )
494
+ blocks = [
495
+ ResBlock(self.qk_dim, self.qk_dim, **self._rb_args) for _ in range(layers)
496
+ ]
497
+ return nn.Sequential(pre, *blocks)
498
+
499
+ def upsample(
500
+ self, enc_img, feats, attn_mask, out_size, vis_attn=False, q_chunk_size=None
501
+ ):
502
+ b, c, h, w = feats.shape
503
+
504
+ q = F.adaptive_avg_pool2d(self.query_encoder(enc_img), output_size=out_size)
505
+ k = F.adaptive_avg_pool2d(self.key_encoder(enc_img), output_size=(h, w))
506
+ k = torch.cat([k, self.key_features_encoder(F.normalize(feats, dim=1))], dim=1)
507
+ k = self.aggregation(k)
508
+ v = feats
509
+
510
+ result = self.cross_decode(
511
+ q, k, v, attn_mask, vis_attn=vis_attn, q_chunk_size=q_chunk_size
512
+ )
513
+ return result
514
+
515
+ def forward(
516
+ self,
517
+ images,
518
+ features,
519
+ attn_mask,
520
+ output_size=None,
521
+ vis_attn=False,
522
+ q_chunk_size=None,
523
+ ):
524
+ output_size = output_size if output_size is not None else images.shape[-2:]
525
+ images = images * 0.5 + 0.5
526
+ images = (images - IMAGENET_MEAN.to(images)) / IMAGENET_STD.to(images)
527
+ images = images.to(features)
528
+ enc = self.image_encoder(images)
529
+ h = enc.shape[-2]
530
+ coords = create_coordinate(h, enc.shape[-1], device=enc.device, dtype=enc.dtype)
531
+ enc = enc.permute(0, 2, 3, 1).view(enc.shape[0], -1, enc.shape[1])
532
+ enc = self.rope(enc, coords)
533
+ enc = enc.view(enc.shape[0], h, -1, enc.shape[-1]).permute(0, 3, 1, 2)
534
+
535
+ result = self.upsample(
536
+ enc,
537
+ features,
538
+ attn_mask,
539
+ output_size,
540
+ vis_attn=vis_attn,
541
+ q_chunk_size=q_chunk_size,
542
+ )
543
+ return result
attention.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import Tensor as T
3
+ from torch.nn.attention.flex_attention import (
4
+ _mask_mod_signature,
5
+ create_block_mask,
6
+ flex_attention,
7
+ )
8
+
9
+ # ---------------------------------------------------------------------------
10
+ # Two compiled variants of flex_attention
11
+ # ---------------------------------------------------------------------------
12
+ # _decode: fullgraph=True, static shapes.
13
+ # Used for decode steps (S_q == 1) where shapes are fixed and
14
+ # the call will be captured inside a CUDA graph. fullgraph=True
15
+ # avoids graph breaks that would corrupt the capture.
16
+ #
17
+ # _prefill: dynamic=True, symbolic shapes.
18
+ # Used for prefill steps (S_q > 1) where the sequence length
19
+ # varies per image. dynamic=True lets one compiled graph handle
20
+ # all lengths without recompilation. Prefill is never inside a
21
+ # CUDA graph, so symbolic shape guards are fine.
22
+ compiled_flex_attn_decode = torch.compile(flex_attention, fullgraph=True)
23
+ compiled_flex_attn_prefill = torch.compile(flex_attention, dynamic=True)
24
+
25
+
26
+ def offset_mask_mod(mask_mod: _mask_mod_signature, offset: int):
27
+ """Get a mask mod function with an offset applied to the query positions."""
28
+
29
+ def _mask_mod(b, h, q, kv):
30
+ return mask_mod(b, h, q + offset, kv)
31
+
32
+ return _mask_mod
33
+
34
+
35
+ def get_causal_mask_mod() -> _mask_mod_signature:
36
+ """Causal mask that prevents attention to future tokens."""
37
+
38
+ def _causal_mask(b: T, h: T, q_idx: T, kv_idx: T) -> T:
39
+ return q_idx >= kv_idx
40
+
41
+ return _causal_mask
42
+
43
+
44
+ def get_document_mask_mod(batch: T, eos_id: int) -> _mask_mod_signature:
45
+ """Creates a document mask that prevents attention across document boundaries.
46
+
47
+ Args:
48
+ batch: Input batch tensor with shape [b, s, h, d]
49
+ eos_id: End-of-sequence token ID that marks document boundaries
50
+
51
+ Returns:
52
+ A mask modifier function that implements document-level masking.
53
+ """
54
+ # batch is [b, s, h, d] shape
55
+ eos_mask = batch == eos_id
56
+ eos_mask[:, -1] = True
57
+ cumulative_mask = torch.cumsum(torch.where(eos_mask, 1, 0), dim=1)
58
+ sequence_indices = torch.zeros_like(cumulative_mask, dtype=torch.int32)
59
+ sequence_indices[:, 1:] = cumulative_mask[:, :-1]
60
+
61
+ def document_mask(b: T, h: T, q_idx: T, kv_idx: T) -> T:
62
+ return sequence_indices[b, q_idx] == sequence_indices[b, kv_idx]
63
+
64
+ return document_mask
65
+
66
+
67
+ def get_non_left_pad_mask_mod(batch: T, pad_id: int) -> _mask_mod_signature:
68
+ """Prevent model from attending to the left-padded token required for correct batch inference."""
69
+
70
+ non_pad_mask_id = torch.cumsum(batch != pad_id, dim=1)
71
+
72
+ # Left-most pad tokens have cumulative id == 0.
73
+ def mask_mod(b, h, q_idx, kv_idx):
74
+ return non_pad_mask_id[b, kv_idx] > 0
75
+
76
+ return mask_mod
77
+
78
+
79
+ def get_image_prefix_mask_mod(
80
+ batch: T, soi_id: int, eoi_id: int
81
+ ) -> _mask_mod_signature:
82
+ # batch is [b, s, h, d] shape
83
+ soi_mask = batch == soi_id
84
+ eoi_mask = batch == eoi_id
85
+ acc_soi_mask = torch.cumsum(soi_mask, dim=1)
86
+ acc_eoi_mask = torch.cumsum(eoi_mask, dim=1)
87
+ # Get every tokens between two soi_id and eoi_id exclusive of eoi_id
88
+ img_mask = (acc_soi_mask - acc_eoi_mask) > 0
89
+
90
+ # Create a tensor that assigns each token to its image number
91
+ # Each image starts with SOI token, so we can use acc_soi_mask to track image numbers
92
+ img_indices = acc_soi_mask * img_mask
93
+
94
+ def image_prefix_mask_mod(b, h, q_idx, kv_idx):
95
+ # Check if both tokens are image tokens and belong to the same image
96
+ is_img_tokens = img_mask[b, q_idx] & img_mask[b, kv_idx]
97
+ is_same_image = img_indices[b, q_idx] == img_indices[b, kv_idx]
98
+ return is_img_tokens & is_same_image
99
+
100
+ return image_prefix_mask_mod
101
+
102
+
103
+ _compiled_create_block_mask = torch.compile(
104
+ create_block_mask, dynamic=True
105
+ ) # Note: can't use mode = 'reduce-overhead' here because it uses internal CUDA graph trees on private streams, causing manual capture to record empty graphs
106
+
107
+
108
+ @torch.inference_mode()
109
+ def create_attention_mask(*args, **kwargs):
110
+ """
111
+ NOTE: We compile this for performance/memory reasons in large masks. To reduce
112
+ recompiles due to grad_mode flips, we always run mask creation under inference_mode.
113
+ """
114
+ return _compiled_create_block_mask(*args, **kwargs)
config.json ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "FalconPerceptionForSegmentation"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_falcon_perception.FalconPerceptionConfig",
7
+ "AutoModelForCausalLM": "modeling_falcon_perception.FalconPerceptionForSegmentation"
8
+ },
9
+ "model_type": "falcon_perception",
10
+ "torch_dtype": "bfloat16",
11
+
12
+ "dim": 1024,
13
+ "n_layers": 28,
14
+ "n_heads": 16,
15
+ "head_dim": 128,
16
+ "n_kv_heads": 8,
17
+ "vocab_size": 65536,
18
+ "ffn_dim": 3072,
19
+ "norm_eps": 1e-05,
20
+ "max_seq_len": 8192,
21
+ "rope_theta": 10000,
22
+
23
+ "channel_size": 3,
24
+ "spatial_patch_size": 16,
25
+ "temporal_patch_size": 1,
26
+
27
+ "do_segmentation": true,
28
+ "segm_out_dim": 256,
29
+ "num_segm_layers": 3,
30
+
31
+ "coord_enc_dim": 512,
32
+ "coord_dec_dim": 8192,
33
+ "coord_out_dim": 2048,
34
+ "coord_token_id": 240,
35
+
36
+ "size_enc_dim": 512,
37
+ "size_dec_dim": 8192,
38
+ "size_out_dim": 2048,
39
+ "size_token_id": 241,
40
+
41
+ "seg_token_id": 262,
42
+ "img_id": 227,
43
+ "eos_id": 11,
44
+ "image_cls_token_id": 244,
45
+ "image_mask_token_id": 243,
46
+ "image_reg_1_token_id": 245,
47
+ "image_reg_2_token_id": 246,
48
+ "image_reg_3_token_id": 247,
49
+ "image_reg_4_token_id": 248,
50
+ "img_start_id": 229,
51
+ "img_end_id": 230,
52
+ "img_row_sep_id": 228,
53
+ "vid_start_id": 231,
54
+ "vid_end_id": 232,
55
+ "frame_sep_id": 233
56
+ }
configuration_falcon_perception.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class FalconPerceptionConfig(PretrainedConfig):
5
+ model_type = "falcon_perception"
6
+
7
+ def __init__(
8
+ self,
9
+ dim: int = 1024,
10
+ n_layers: int = 28,
11
+ n_heads: int = 16,
12
+ head_dim: int = 128,
13
+ n_kv_heads: int = 8,
14
+ vocab_size: int = 65536,
15
+ ffn_dim: int = 3072,
16
+ norm_eps: float = 1e-5,
17
+ max_seq_len: int = 8192,
18
+ rope_theta: int = 10000,
19
+ channel_size: int = 3,
20
+ spatial_patch_size: int = 16,
21
+ temporal_patch_size: int = 1,
22
+ do_segmentation: bool = True,
23
+ segm_out_dim: int = 256,
24
+ num_segm_layers: int = 3,
25
+ coord_enc_dim: int = 512,
26
+ coord_dec_dim: int = 8192,
27
+ coord_out_dim: int = 2048,
28
+ coord_token_id: int = 240,
29
+ size_enc_dim: int = 512,
30
+ size_dec_dim: int = 8192,
31
+ size_out_dim: int = 2048,
32
+ size_token_id: int = 241,
33
+ seg_token_id: int = 262,
34
+ img_id: int = 227,
35
+ eos_id: int = 11,
36
+ image_cls_token_id: int = 244,
37
+ image_mask_token_id: int = 243,
38
+ image_reg_1_token_id: int = 245,
39
+ image_reg_2_token_id: int = 246,
40
+ image_reg_3_token_id: int = 247,
41
+ image_reg_4_token_id: int = 248,
42
+ img_start_id: int = 229,
43
+ img_end_id: int = 230,
44
+ img_row_sep_id: int = 228,
45
+ vid_start_id: int = 231,
46
+ vid_end_id: int = 232,
47
+ frame_sep_id: int = 233,
48
+ **kwargs,
49
+ ):
50
+ self.dim = dim
51
+ self.n_layers = n_layers
52
+ self.n_heads = n_heads
53
+ self.head_dim = head_dim
54
+ self.n_kv_heads = n_kv_heads
55
+ self.vocab_size = vocab_size
56
+ self.ffn_dim = ffn_dim
57
+ self.norm_eps = norm_eps
58
+ self.max_seq_len = max_seq_len
59
+ self.rope_theta = rope_theta
60
+ self.channel_size = channel_size
61
+ self.spatial_patch_size = spatial_patch_size
62
+ self.temporal_patch_size = temporal_patch_size
63
+ self.do_segmentation = do_segmentation
64
+ self.segm_out_dim = segm_out_dim
65
+ self.num_segm_layers = num_segm_layers
66
+ self.coord_enc_dim = coord_enc_dim
67
+ self.coord_dec_dim = coord_dec_dim
68
+ self.coord_out_dim = coord_out_dim
69
+ self.coord_token_id = coord_token_id
70
+ self.size_enc_dim = size_enc_dim
71
+ self.size_dec_dim = size_dec_dim
72
+ self.size_out_dim = size_out_dim
73
+ self.size_token_id = size_token_id
74
+ self.seg_token_id = seg_token_id
75
+ self.img_id = img_id
76
+ self.eos_id = eos_id
77
+ self.image_cls_token_id = image_cls_token_id
78
+ self.image_mask_token_id = image_mask_token_id
79
+ self.image_reg_1_token_id = image_reg_1_token_id
80
+ self.image_reg_2_token_id = image_reg_2_token_id
81
+ self.image_reg_3_token_id = image_reg_3_token_id
82
+ self.image_reg_4_token_id = image_reg_4_token_id
83
+ self.img_start_id = img_start_id
84
+ self.img_end_id = img_end_id
85
+ self.img_row_sep_id = img_row_sep_id
86
+ self.vid_start_id = vid_start_id
87
+ self.vid_end_id = vid_end_id
88
+ self.frame_sep_id = frame_sep_id
89
+ super().__init__(**kwargs)
main_fig.jpg ADDED

Git LFS Details

  • SHA256: a25a745799ac3cf2967620af6936fa35cb3534b73ff93e42acd37adb67a03c34
  • Pointer size: 132 Bytes
  • Size of remote file: 1.48 MB
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d8c4a8882cdbf294a69b58497f325fe715e7cfa2d42e806daeccfada6986e1d8
3
+ size 2529523048
model_args.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "channel_size": 3,
3
+ "coord_dec_dim": 8192,
4
+ "coord_enc_dim": 512,
5
+ "coord_out_dim": 2048,
6
+ "coord_token_id": 240,
7
+ "dim": 1024,
8
+ "do_segmentation": true,
9
+ "eos_id": 11,
10
+ "ffn_dim": 3072,
11
+ "frame_sep_id": 233,
12
+ "head_dim": 128,
13
+ "image_cls_token_id": 244,
14
+ "image_mask_token_id": 243,
15
+ "image_reg_1_token_id": 245,
16
+ "image_reg_2_token_id": 246,
17
+ "image_reg_3_token_id": 247,
18
+ "image_reg_4_token_id": 248,
19
+ "img_end_id": 230,
20
+ "img_id": 227,
21
+ "img_row_sep_id": 228,
22
+ "img_start_id": 229,
23
+ "max_seq_len": 8192,
24
+ "n_heads": 16,
25
+ "n_kv_heads": 8,
26
+ "n_layers": 28,
27
+ "norm_eps": 1e-05,
28
+ "num_segm_layers": 3,
29
+ "rope_theta": 10000,
30
+ "seg_token_id": 262,
31
+ "segm_out_dim": 256,
32
+ "size_dec_dim": 8192,
33
+ "size_enc_dim": 512,
34
+ "size_out_dim": 2048,
35
+ "size_token_id": 241,
36
+ "spatial_patch_size": 16,
37
+ "temporal_patch_size": 1,
38
+ "vid_end_id": 232,
39
+ "vid_start_id": 231,
40
+ "vocab_size": 65536
41
+ }
modeling_falcon_perception.py ADDED
@@ -0,0 +1,896 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import time
3
+ from pathlib import Path
4
+
5
+ import einops as E
6
+ import numpy as np
7
+ import torch
8
+ import torch.nn.functional as F
9
+ import triton
10
+ import triton.language as tl
11
+ from PIL import Image
12
+ from pycocotools import mask as mask_utils
13
+ from torch import Tensor as T
14
+ from torch import nn
15
+ from torch.nn.attention.flex_attention import (
16
+ AuxRequest,
17
+ BlockMask,
18
+ and_masks,
19
+ or_masks,
20
+ )
21
+ from transformers import AutoTokenizer, PreTrainedModel
22
+
23
+ from .anyup import AnyUp, get_attention_mask_mod as get_upsampler_attn_mask_mod
24
+ from .attention import (
25
+ compiled_flex_attn_decode,
26
+ compiled_flex_attn_prefill,
27
+ create_attention_mask,
28
+ get_causal_mask_mod,
29
+ get_document_mask_mod,
30
+ get_image_prefix_mask_mod,
31
+ get_non_left_pad_mask_mod,
32
+ offset_mask_mod,
33
+ )
34
+ from .configuration_falcon_perception import FalconPerceptionConfig
35
+ from .processing_falcon_perception import load_image, process_batch
36
+ from .rope import (
37
+ apply_3d_rotary_emb,
38
+ apply_golden_freqs_cis_to_visual_pos,
39
+ precompute_freqs_cis,
40
+ )
41
+
42
+
43
+ # ---------------------------------------------------------------------------
44
+ # Sub-modules: Heads
45
+ # ---------------------------------------------------------------------------
46
+
47
+ class FourierEncoder(nn.Module):
48
+ def __init__(self, in_dim: int, feat_dim: int, out_dim: int):
49
+ super().__init__()
50
+ self.embed = nn.Linear(in_dim, feat_dim // 2, bias=False)
51
+ self.transform = nn.Linear(feat_dim, out_dim, bias=False)
52
+
53
+ def forward(self, x):
54
+ f = 2 * math.pi * self.embed(x)
55
+ f = torch.cat([f.cos(), f.sin()], dim=-1)
56
+ return self.transform(f)
57
+
58
+
59
+ class BboxDecoder(nn.Module):
60
+ def __init__(self, in_dim: int, hidden_dim: int, out_dim: int) -> None:
61
+ super().__init__()
62
+ self.w1 = nn.Linear(in_dim, hidden_dim, bias=False)
63
+ self.w2 = nn.Linear(hidden_dim, out_dim, bias=False)
64
+
65
+ def forward(self, x: T) -> T:
66
+ return self.w2(F.relu(self.w1(x)).square())
67
+
68
+
69
+ class SegmDecoder(nn.Module):
70
+ def __init__(self, in_dim: int, out_dim: int, num_layers: int) -> None:
71
+ super().__init__()
72
+ self.layers = nn.ModuleList([nn.Linear(in_dim, in_dim) for _ in range(num_layers - 1)])
73
+ self.pixel_layer = nn.Linear(in_dim, out_dim, bias=False)
74
+
75
+ def forward(self, x) -> torch.Tensor:
76
+ for layer in self.layers:
77
+ x = F.relu(layer(x)).square()
78
+ return self.pixel_layer(x)
79
+
80
+
81
+ # ---------------------------------------------------------------------------
82
+ # Sub-modules: Attention
83
+ # ---------------------------------------------------------------------------
84
+
85
+ def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
86
+ B, S, H, D = x.shape
87
+ if n_rep == 1:
88
+ return x
89
+ return torch.unsqueeze(x, dim=3).expand(B, S, H, n_rep, D).reshape(B, S, H * n_rep, D)
90
+
91
+
92
+ class Attention(nn.Module):
93
+ def __init__(self, config: FalconPerceptionConfig, layer_id: int):
94
+ super().__init__()
95
+ self.layer_id = layer_id
96
+ self.n_kv_heads = config.n_kv_heads or config.n_heads
97
+ self.n_rep = config.n_heads // self.n_kv_heads
98
+ self.head_dim = config.head_dim or config.dim // config.n_heads
99
+ self.q_dim = config.n_heads * self.head_dim
100
+ self.kv_dim = self.n_kv_heads * self.head_dim
101
+
102
+ self.wq = nn.Linear(config.dim, self.q_dim, bias=False)
103
+ self.wk = nn.Linear(config.dim, self.kv_dim, bias=False)
104
+ self.wv = nn.Linear(config.dim, self.kv_dim, bias=False)
105
+ self.wo = nn.Linear(config.n_heads * self.head_dim, config.dim, bias=False)
106
+ self.sinks = nn.Parameter(torch.empty((config.n_heads,)))
107
+
108
+ def _fuse_weights(self):
109
+ wqkv_weight = torch.cat([self.wq.weight.data, self.wk.weight.data, self.wv.weight.data], dim=0)
110
+ self.register_buffer("_wqkv_weight", wqkv_weight)
111
+ del self.wq, self.wk, self.wv
112
+
113
+ def _pre_attention_qkv(self, x) -> tuple[T, T, T]:
114
+ qkv = F.linear(F.rms_norm(x, (x.size(-1),)), self._wqkv_weight)
115
+ xq, xk, xv = qkv.split([self.q_dim, self.kv_dim, self.kv_dim], dim=-1)
116
+ xq = E.rearrange(xq, "b s (h d) -> b s h d", d=self.head_dim)
117
+ xk = E.rearrange(xk, "b s (h d) -> b s h d", d=self.head_dim)
118
+ xv = E.rearrange(xv, "b s (h d) -> b s h d", d=self.head_dim)
119
+ xq = F.rms_norm(xq, (xq.size(-1),))
120
+ xk = F.rms_norm(xk, (xk.size(-1),))
121
+ xk = repeat_kv(xk, n_rep=self.n_rep)
122
+ xv = repeat_kv(xv, n_rep=self.n_rep)
123
+ return xq, xk, xv
124
+
125
+ def _post_attention(self, output: T, lse: T) -> T:
126
+ sinks_BHS = self.sinks.view(1, -1, 1)
127
+ sink_scale = torch.sigmoid(lse - sinks_BHS)
128
+ output = (output * sink_scale.unsqueeze(-1)).to(output.dtype)
129
+ output = output.permute(0, 2, 1, 3).contiguous().flatten(2)
130
+ return self.wo(output)
131
+
132
+ def compile_attention(self, *, dynamic: bool = True, mode: str = "default"):
133
+ self._pre_attention_qkv = torch.compile(self._pre_attention_qkv, dynamic=dynamic, mode=mode)
134
+ self._post_attention = torch.compile(self._post_attention, dynamic=dynamic, mode=mode)
135
+
136
+ def forward(
137
+ self, x: T, attention_masks: BlockMask, freqs_cis: T,
138
+ freqs_cis_2d: T | None = None, pos_hw: T | None = None,
139
+ kv_cache=None, input_pos=None, batch_idx=None,
140
+ flex_attn_kernel_options=None,
141
+ ):
142
+ xq, xk, xv = self._pre_attention_qkv(x)
143
+ xq, xk = apply_3d_rotary_emb(xq, xk, freqs_cis, freqs_cis_2d, pos_hw)
144
+ xq = E.rearrange(xq, "b s h d -> b h s d")
145
+ xk = E.rearrange(xk, "b s h d -> b h s d")
146
+ xv = E.rearrange(xv, "b s h d -> b h s d")
147
+ xk, xv = kv_cache.insert_kv(self.layer_id, xk, xv, input_pos=input_pos, batch_idx=batch_idx)
148
+ flex_fn = compiled_flex_attn_decode if xq.shape[2] == 1 else compiled_flex_attn_prefill
149
+ output, aux_output = flex_fn(xq, xk, xv, block_mask=attention_masks, return_aux=AuxRequest(lse=True))
150
+ return self._post_attention(output, aux_output.lse)
151
+
152
+
153
+ # ---------------------------------------------------------------------------
154
+ # Sub-modules: FeedForward
155
+ # ---------------------------------------------------------------------------
156
+
157
+ @triton.jit
158
+ def _squared_relu_gate_kernel(
159
+ packed_ptr, out_ptr, n_rows, n_cols,
160
+ in_row_stride, in_col_stride, out_row_stride, out_col_stride,
161
+ BLOCK_SIZE: tl.constexpr,
162
+ ):
163
+ pid = tl.program_id(0)
164
+ n_elements = n_rows * n_cols
165
+ offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
166
+ mask = offsets < n_elements
167
+ rows = offsets // n_cols
168
+ cols = offsets % n_cols
169
+ gate_idx = rows * in_row_stride + (2 * cols) * in_col_stride
170
+ up_idx = rows * in_row_stride + (2 * cols + 1) * in_col_stride
171
+ out_idx = rows * out_row_stride + cols * out_col_stride
172
+ gate = tl.load(packed_ptr + gate_idx, mask=mask)
173
+ up = tl.load(packed_ptr + up_idx, mask=mask)
174
+ gate = tl.where(gate > 0, gate, 0.0)
175
+ out = gate * gate * up
176
+ tl.store(out_ptr + out_idx, out, mask=mask)
177
+
178
+
179
+ def squared_relu_gate(packed: T, hidden_dim: int) -> T:
180
+ packed_2d = packed.flatten(0, -2)
181
+ n_rows = packed_2d.shape[0]
182
+ n_cols = hidden_dim
183
+ out_2d = torch.empty((n_rows, n_cols), device=packed.device, dtype=packed.dtype)
184
+ n = n_rows * n_cols
185
+ grid = lambda meta: (triton.cdiv(n, meta["BLOCK_SIZE"]),)
186
+ _squared_relu_gate_kernel[grid](
187
+ packed_2d, out_2d, n_rows, n_cols,
188
+ packed_2d.stride(0), packed_2d.stride(1),
189
+ out_2d.stride(0), out_2d.stride(1),
190
+ BLOCK_SIZE=1024,
191
+ )
192
+ return out_2d.view(*packed.shape[:-1], hidden_dim)
193
+
194
+
195
+ class FeedForward(nn.Module):
196
+ def __init__(self, dim: int, hidden_dim: int):
197
+ super().__init__()
198
+ self.w1 = nn.Linear(dim, hidden_dim, bias=False)
199
+ self.w2 = nn.Linear(hidden_dim, dim, bias=False)
200
+ self.w3 = nn.Linear(dim, hidden_dim, bias=False)
201
+ self.hidden_dim = hidden_dim
202
+
203
+ def _fuse_weights(self):
204
+ if hasattr(self, "_w13_weight"):
205
+ return
206
+ w1_weight_fused = self.w1.weight.data * math.sqrt(2.0)
207
+ w13_weight = torch.empty(
208
+ (2 * self.hidden_dim, self.w1.weight.shape[1]),
209
+ device=w1_weight_fused.device, dtype=w1_weight_fused.dtype,
210
+ )
211
+ w13_weight[0::2] = w1_weight_fused
212
+ w13_weight[1::2] = self.w3.weight.data
213
+ self.register_buffer("_w13_weight", w13_weight)
214
+ del self.w1, self.w3
215
+
216
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
217
+ x = F.rms_norm(x, (x.size(-1),))
218
+ w13_out = F.linear(x, self._w13_weight)
219
+ return self.w2(squared_relu_gate(w13_out, self.hidden_dim))
220
+
221
+
222
+ # ---------------------------------------------------------------------------
223
+ # Sub-modules: TransformerBlock
224
+ # ---------------------------------------------------------------------------
225
+
226
+ class TransformerBlock(nn.Module):
227
+ def __init__(self, layer_id: int, config: FalconPerceptionConfig):
228
+ super().__init__()
229
+ self.attention = Attention(config, layer_id)
230
+ self.feed_forward = FeedForward(config.dim, config.ffn_dim)
231
+
232
+ def compile(self, *, dynamic: bool = True, mode: str = "default"):
233
+ self.feed_forward = torch.compile(self.feed_forward, dynamic=dynamic, mode=mode)
234
+ self.attention.compile_attention(dynamic=dynamic, mode=mode)
235
+ return self
236
+
237
+ def forward(
238
+ self, x: T, freqs_cis: T, freqs_cis_2d: T | None = None,
239
+ pos_hw: T | None = None, attention_masks=None, kv_cache=None,
240
+ input_pos=None, batch_idx=None, flex_attn_kernel_options=None,
241
+ ):
242
+ B, S, D = x.shape
243
+ x = x + self.attention(
244
+ x, freqs_cis=freqs_cis, freqs_cis_2d=freqs_cis_2d, pos_hw=pos_hw,
245
+ attention_masks=attention_masks, kv_cache=kv_cache,
246
+ input_pos=input_pos, batch_idx=batch_idx,
247
+ flex_attn_kernel_options=flex_attn_kernel_options,
248
+ )
249
+ out = x + self.feed_forward(x)
250
+ return out.reshape(B, S, D)
251
+
252
+
253
+ # ---------------------------------------------------------------------------
254
+ # KV Cache
255
+ # ---------------------------------------------------------------------------
256
+
257
+ class KVCache:
258
+ def __init__(self, max_batch_size, max_seq_length, n_heads, head_dim, num_layers):
259
+ self.kv_shape = (num_layers, 2, max_batch_size, n_heads, max_seq_length, head_dim)
260
+ self.kv_cache = None
261
+ self.pos = 0
262
+ self.pos_t: T | None = None
263
+
264
+ def reset(self):
265
+ self.pos = 0
266
+ self.pos_t = None
267
+
268
+ def get_pos(self):
269
+ return self.pos
270
+
271
+ def set_pos_t(self, pos_t):
272
+ self.pos_t = pos_t
273
+
274
+ def increment_and_get_pos_t(self):
275
+ assert self.pos_t is not None
276
+ self.pos_t += 1
277
+ return self.pos_t
278
+
279
+ def insert_kv(self, layer_id: int, k: T, v: T, **kwargs):
280
+ del kwargs
281
+ assert self.pos_t is not None
282
+ if self.kv_cache is None:
283
+ self.kv_cache = torch.empty(self.kv_shape, dtype=k.dtype, device=k.device)
284
+ B, H, T_add, D = k.size()
285
+ t0, t1 = self.pos, self.pos + T_add
286
+ self.kv_cache[layer_id, 0, :, :, t0:t1] = k
287
+ self.kv_cache[layer_id, 1, :, :, t0:t1] = v
288
+ key_view = self.kv_cache[layer_id, 0, :, :, :t1]
289
+ value_view = self.kv_cache[layer_id, 1, :, :, :t1]
290
+ if layer_id == self.kv_cache.size(0) - 1:
291
+ self.pos = t1
292
+ return key_view, value_view
293
+
294
+
295
+ # ---------------------------------------------------------------------------
296
+ # Sampling
297
+ # ---------------------------------------------------------------------------
298
+
299
+ @torch.inference_mode()
300
+ def sample_next_token(logits, rng, temperature=0.0, top_k=None):
301
+ assert temperature >= 0.0
302
+ if temperature == 0.0:
303
+ return torch.argmax(logits, dim=-1, keepdim=True)
304
+ if top_k is not None:
305
+ k = min(top_k, logits.size(-1))
306
+ vals, idx = torch.topk(logits, k, dim=-1)
307
+ vals = vals / temperature
308
+ probs = F.softmax(vals, dim=-1)
309
+ choice = torch.multinomial(probs, num_samples=1, generator=rng)
310
+ return idx.gather(1, choice)
311
+ logits = logits / temperature
312
+ probs = F.softmax(logits, dim=-1)
313
+ return torch.multinomial(probs, num_samples=1, generator=rng)
314
+
315
+
316
+ # ---------------------------------------------------------------------------
317
+ # Main Model
318
+ # ---------------------------------------------------------------------------
319
+
320
+ class FalconPerceptionForSegmentation(PreTrainedModel):
321
+ config_class = FalconPerceptionConfig
322
+ _no_split_modules = ["TransformerBlock"]
323
+
324
+ def __init__(self, config: FalconPerceptionConfig):
325
+ super().__init__(config)
326
+ img_in_dim = config.temporal_patch_size * config.spatial_patch_size ** 2 * config.channel_size
327
+ self.img_projector = nn.Linear(img_in_dim, config.dim, bias=False)
328
+ self.tok_embeddings = nn.Embedding(config.vocab_size, config.dim)
329
+
330
+ self.layers = nn.ModuleDict()
331
+ for layer_id in range(config.n_layers):
332
+ self.layers[str(layer_id)] = TransformerBlock(layer_id, config)
333
+
334
+ self.norm = nn.RMSNorm(config.dim, eps=config.norm_eps)
335
+ self.output = nn.Linear(config.dim, config.vocab_size, bias=False)
336
+
337
+ self.coord_encoder = FourierEncoder(2, config.coord_enc_dim, config.dim)
338
+ self.coord_decoder = BboxDecoder(config.dim, config.coord_dec_dim, config.coord_out_dim)
339
+ self.size_encoder = FourierEncoder(2, config.size_enc_dim, config.dim)
340
+ self.size_decoder = BboxDecoder(config.dim, config.size_dec_dim, config.size_out_dim)
341
+
342
+ if config.do_segmentation:
343
+ self.itok_upsampler = AnyUp()
344
+ self.proj_segm = SegmDecoder(config.dim, config.segm_out_dim, config.num_segm_layers)
345
+ self.conv_segm = nn.Conv2d(config.dim, config.segm_out_dim, kernel_size=3, padding=1)
346
+
347
+ rope_dim = config.head_dim // 2
348
+ freqs_cis = precompute_freqs_cis(rope_dim, config.max_seq_len, config.rope_theta)
349
+ freqs_cis_golden = torch.empty((config.n_heads, rope_dim // 2, 2), dtype=torch.float)
350
+ self.register_buffer("freqs_cis", freqs_cis, persistent=False)
351
+ self.register_buffer("freqs_cis_golden", freqs_cis_golden, persistent=True)
352
+
353
+ self._weights_fused = False
354
+ self._is_compiled = False
355
+
356
+ self.post_init()
357
+
358
+ # -- Weight management ---------------------------------------------------
359
+
360
+ def _fuse_weights(self):
361
+ if self._weights_fused:
362
+ return
363
+
364
+ device = self.tok_embeddings.weight.device
365
+ c = self.config
366
+
367
+ # Recompute freqs_cis on the actual device — non-persistent buffers
368
+ # get replaced with empty tensors by transformers' meta-device loading.
369
+ rope_dim = c.head_dim // 2
370
+ freqs_cis = precompute_freqs_cis(rope_dim, c.max_seq_len, c.rope_theta).to(device)
371
+ self.register_buffer("freqs_cis", freqs_cis, persistent=False)
372
+
373
+ # Ensure freqs_cis_golden is on the right device (loaded from safetensors)
374
+ if self.freqs_cis_golden.device != device:
375
+ self.freqs_cis_golden = self.freqs_cis_golden.to(device)
376
+
377
+ for layer in self.layers.values():
378
+ layer.attention._fuse_weights()
379
+ layer.feed_forward._fuse_weights()
380
+ self.coord_decoder.w1.weight.mul_(math.sqrt(2))
381
+ self.size_decoder.w1.weight.mul_(math.sqrt(2))
382
+ if self.config.do_segmentation:
383
+ for layer in self.proj_segm.layers:
384
+ layer.weight.mul_(math.sqrt(2))
385
+ self._weights_fused = True
386
+
387
+ def compile_model(self):
388
+ if self._is_compiled:
389
+ return
390
+ torch._inductor.config.triton.cudagraphs = False
391
+ for layer in self.layers.values():
392
+ layer.compile(dynamic=True, mode="default")
393
+ self.coord_encoder = torch.compile(self.coord_encoder, dynamic=True, mode="default")
394
+ self.coord_decoder = torch.compile(self.coord_decoder, dynamic=True, mode="default")
395
+ self.size_encoder = torch.compile(self.size_encoder, dynamic=True, mode="default")
396
+ self.size_decoder = torch.compile(self.size_decoder, dynamic=True, mode="default")
397
+ if self.config.do_segmentation:
398
+ self.itok_upsampler.compile(mode="default", dynamic=True)
399
+ self._is_compiled = True
400
+
401
+ # -- Tokenizer -----------------------------------------------------------
402
+
403
+ def _get_tokenizer(self):
404
+ if not hasattr(self, "_tokenizer"):
405
+ import os
406
+ path = self.config._name_or_path
407
+ is_local = os.path.exists(path)
408
+ self._tokenizer = AutoTokenizer.from_pretrained(path, local_files_only=is_local, trust_remote_code=True)
409
+ for token_name, token in self._tokenizer.special_tokens_map.items():
410
+ if isinstance(token, str):
411
+ setattr(self._tokenizer, token_name, token)
412
+ setattr(
413
+ self._tokenizer, token_name + "_id",
414
+ self._tokenizer.convert_tokens_to_ids(token),
415
+ )
416
+ return self._tokenizer
417
+
418
+ # -- Attention mask ------------------------------------------------------
419
+
420
+ def get_attention_mask(self, input_batch: T, max_len: int | None = None):
421
+ B, S = input_batch.size()
422
+ c = self.config
423
+ block_causal_mask_mod = and_masks(
424
+ get_causal_mask_mod(),
425
+ get_document_mask_mod(input_batch, c.eos_id),
426
+ get_non_left_pad_mask_mod(input_batch, self._pad_token_id),
427
+ )
428
+ image_prefix_mask_mod = get_image_prefix_mask_mod(
429
+ batch=input_batch, soi_id=c.image_cls_token_id, eoi_id=c.img_end_id,
430
+ )
431
+ mask_mod = or_masks(image_prefix_mask_mod, block_causal_mask_mod)
432
+ max_len = max_len or S
433
+ return create_attention_mask(mask_mod, B, None, max_len, max_len)
434
+
435
+ def get_upsampler_attn_mask(self, H, W, h, w, device):
436
+ return create_attention_mask(
437
+ get_upsampler_attn_mask_mod(H, W, h, w, device=device),
438
+ B=None, H=None, Q_LEN=H * W, KV_LEN=h * w,
439
+ )
440
+
441
+ # -- Embedding helpers ---------------------------------------------------
442
+
443
+ def _scatter_img_tokens_with_projector(self, h_BSD, pixel_patches_NLC, pixel_masks_NTHW, tokens_BS):
444
+ B, S, D = h_BSD.shape
445
+ pixel_patch_mask = E.reduce(
446
+ pixel_masks_NTHW,
447
+ "n (t pt) (h ph) (w pw) -> (n t h w)",
448
+ reduction="any",
449
+ pt=self.config.temporal_patch_size,
450
+ ph=self.config.spatial_patch_size,
451
+ pw=self.config.spatial_patch_size,
452
+ )
453
+ pixel_patches_flat = E.rearrange(pixel_patches_NLC, "n p c -> (n p) c")
454
+ valid_patches = pixel_patches_flat[pixel_patch_mask]
455
+ valid_feats = self.img_projector(valid_patches)
456
+ img_mask_h_BSD = E.repeat(tokens_BS == self.config.img_id, "b s -> b s d", d=D)
457
+ assert valid_feats.numel() == img_mask_h_BSD.sum()
458
+ return torch.masked_scatter(h_BSD, img_mask_h_BSD, valid_feats)
459
+
460
+ def _encode_coords(self, h_BSD: T, tokens_BS: T, all_xy: T):
461
+ coord_tokens_mask = tokens_BS == self.config.coord_token_id
462
+ if all_xy.numel() == 0:
463
+ return h_BSD
464
+ coord_tokens = self.coord_encoder(all_xy.reshape(-1, 2))
465
+ if coord_tokens.shape[0] == h_BSD.shape[0]:
466
+ h_BSD = torch.where(
467
+ coord_tokens_mask.unsqueeze(-1),
468
+ coord_tokens.view(h_BSD.shape[0], -1, h_BSD.shape[-1]),
469
+ h_BSD,
470
+ )
471
+ else:
472
+ h_BSD = h_BSD.masked_scatter_(coord_tokens_mask.unsqueeze(-1), coord_tokens)
473
+ return h_BSD
474
+
475
+ def _encode_sizes(self, h_BSD, tokens_BS, all_hw: T):
476
+ size_tokens_mask = tokens_BS == self.config.size_token_id
477
+ if all_hw.numel() == 0:
478
+ return h_BSD
479
+ size_tokens = self.size_encoder(all_hw.reshape(-1, 2))
480
+ if size_tokens.shape[0] == h_BSD.shape[0]:
481
+ h_BSD = torch.where(
482
+ size_tokens_mask.unsqueeze(-1),
483
+ size_tokens.view(h_BSD.shape[0], -1, h_BSD.shape[-1]),
484
+ h_BSD,
485
+ )
486
+ else:
487
+ h_BSD = h_BSD.masked_scatter_(size_tokens_mask.unsqueeze(-1), size_tokens)
488
+ return h_BSD
489
+
490
+ def decode_coords(self, h_BSD, labels):
491
+ B, S, D = h_BSD.shape
492
+ coord_masks = labels == self.config.coord_token_id
493
+ coord_tokens = torch.masked_select(h_BSD, coord_masks.unsqueeze(-1))
494
+ coord_logits = self.coord_decoder(coord_tokens.reshape(-1, D))
495
+ return E.rearrange(coord_logits, "b (two dim) -> b two dim", two=2)
496
+
497
+ def decode_sizes(self, h_BSD, labels):
498
+ B, S, D = h_BSD.shape
499
+ size_masks = labels == self.config.size_token_id
500
+ size_tokens = torch.masked_select(h_BSD, size_masks.unsqueeze(-1))
501
+ size_logits = self.size_decoder(size_tokens.reshape(-1, D))
502
+ return E.rearrange(size_logits, "b (two dim) -> b two dim", two=2)
503
+
504
+ def process_sizes(self, logits):
505
+ num_bins = logits.shape[-1]
506
+ pred = torch.argmax(logits, dim=-1).float() / (num_bins - 1)
507
+ min_size = torch.log2(torch.tensor(1 / num_bins))
508
+ max_size = 0.0
509
+ pred = pred * (max_size - min_size) + min_size
510
+ return torch.pow(2.0, pred)
511
+
512
+ # -- Segmentation -------------------------------------------------------
513
+
514
+ def gather_img_tokens(self, h_BSD: T, tokens_BS: T, itok_masks_NTHW: T):
515
+ B, S, D = h_BSD.shape
516
+ itok_masks_BSD = E.repeat(tokens_BS == self.config.img_id, "b s -> b s d", d=D)
517
+ itok_flatten = torch.masked_select(h_BSD, itok_masks_BSD)
518
+ itok_masks_NTHWD = E.repeat(itok_masks_NTHW, "n t h w -> n t h w d", d=D)
519
+ itok_NTHWD = torch.zeros_like(itok_masks_NTHWD, dtype=h_BSD.dtype, device=h_BSD.device)
520
+ itok_NTHWD = itok_NTHWD.masked_scatter_(itok_masks_NTHWD, itok_flatten)
521
+ return itok_NTHWD
522
+
523
+ def upsample_img_features(self, h_BSD: T, tokens_BS: T, pixel_values_NTHWC: T, pixel_mask_NTHW: T):
524
+ device = h_BSD.device
525
+ c = self.config
526
+ itok_masks_NTHW = E.reduce(
527
+ pixel_mask_NTHW,
528
+ "n (t pt) (h ph) (w pw) -> n t h w",
529
+ reduction="any",
530
+ pt=c.temporal_patch_size, ph=c.spatial_patch_size, pw=c.spatial_patch_size,
531
+ )
532
+ N, _, h, w = itok_masks_NTHW.shape
533
+ _, _, H, W = pixel_mask_NTHW.shape
534
+ images = E.rearrange(pixel_values_NTHWC, "n 1 h w c -> n c h w")
535
+ lr_img_features = self.gather_img_tokens(h_BSD, tokens_BS, itok_masks_NTHW)
536
+ lr_img_features = E.rearrange(lr_img_features, "n 1 h w d -> n d h w")
537
+ lr_img_features = self.conv_segm(lr_img_features)
538
+
539
+ upsampler_attn_mask = self.get_upsampler_attn_mask(H, W, h, w, device=device)
540
+ hr_parts = []
541
+ for i in range(N):
542
+ hr_i = self.itok_upsampler(
543
+ images=images[i:i + 1], features=lr_img_features[i:i + 1], attn_mask=upsampler_attn_mask,
544
+ )
545
+ hr_parts.append(hr_i)
546
+ return torch.cat(hr_parts, dim=0) if N > 1 else hr_parts[0]
547
+
548
+ @staticmethod
549
+ def _mask_to_coco_rle(binary_masks: torch.Tensor) -> list[dict]:
550
+ C, H, W = binary_masks.shape
551
+ has_any = E.reduce(binary_masks, "c h w -> c", reduction="any")
552
+ binary_col = E.rearrange(binary_masks, "c h w -> c (w h)")
553
+ diffs = binary_col[:, 1:] != binary_col[:, :-1]
554
+ nz = torch.nonzero(diffs, as_tuple=False)
555
+ first_vals = binary_col[:, 0]
556
+ nz_cpu = nz.cpu().numpy()
557
+ has_any_cpu = has_any.cpu().numpy()
558
+ first_vals_cpu = first_vals.cpu().numpy()
559
+ del diffs, nz, binary_col, first_vals, has_any
560
+ N_px = H * W
561
+ if nz_cpu.shape[0] > 0:
562
+ mask_ids = nz_cpu[:, 0]
563
+ change_cols = nz_cpu[:, 1]
564
+ uniq, grp_starts = np.unique(mask_ids, return_index=True)
565
+ grp_ends = np.append(grp_starts[1:], len(mask_ids))
566
+ mask_to_grp = {int(m): (int(gs), int(ge)) for m, gs, ge in zip(uniq, grp_starts, grp_ends)}
567
+ else:
568
+ change_cols = np.array([], dtype=np.intp)
569
+ mask_to_grp = {}
570
+ results = []
571
+ for i in range(C):
572
+ if not has_any_cpu[i]:
573
+ continue
574
+ if i in mask_to_grp:
575
+ gs, ge = mask_to_grp[i]
576
+ cidx = change_cols[gs:ge]
577
+ else:
578
+ cidx = np.array([], dtype=np.intp)
579
+ num_runs = len(cidx) + 1
580
+ starts = np.empty(num_runs, dtype=np.intp)
581
+ starts[0] = 0
582
+ if len(cidx) > 0:
583
+ starts[1:] = cidx + 1
584
+ counts = np.empty(num_runs, dtype=np.uint32)
585
+ if num_runs > 1:
586
+ counts[:-1] = np.diff(starts)
587
+ counts[-1] = N_px - starts[-1]
588
+ if first_vals_cpu[i]:
589
+ counts = np.concatenate([[0], counts])
590
+ rle = {"counts": counts.tolist(), "size": [H, W]}
591
+ rle = mask_utils.frPyObjects(rle, H, W)
592
+ rle["counts"] = rle["counts"].decode("utf-8")
593
+ results.append(rle)
594
+ return results
595
+
596
+ # -- Core forward --------------------------------------------------------
597
+
598
+ def forward(
599
+ self,
600
+ tokens: T,
601
+ attention_mask: BlockMask,
602
+ kv_cache,
603
+ rope_pos_t: T | None = None,
604
+ rope_pos_hw: T | None = None,
605
+ pixel_values: T | None = None,
606
+ pixel_mask: T | None = None,
607
+ coord_xy: T | None = None,
608
+ size_hw: T | None = None,
609
+ ):
610
+ B, S = tokens.size()
611
+ c = self.config
612
+ block_mask = attention_mask
613
+
614
+ T_pos = kv_cache.get_pos()
615
+ is_prefill = S != 1
616
+
617
+ if is_prefill:
618
+ assert rope_pos_t is not None and rope_pos_hw is not None
619
+ pos_t = rope_pos_t[:, T_pos:T_pos + S].long()
620
+ kv_cache.pos_t = pos_t[:, -1:]
621
+ freqs_cis = self.freqs_cis[pos_t]
622
+ rope_pos_hw = rope_pos_hw[:, T_pos:T_pos + S]
623
+ freqs_cis_golden = apply_golden_freqs_cis_to_visual_pos(self.freqs_cis_golden, rope_pos_hw)
624
+ block_mask.seq_lengths = (S, S)
625
+ else:
626
+ pos_t = kv_cache.increment_and_get_pos_t()
627
+ freqs_cis = self.freqs_cis[pos_t]
628
+ freqs_cis_golden = None
629
+ block_idx = T_pos // block_mask.BLOCK_SIZE[0]
630
+ block_mask = block_mask[:, :, block_idx]
631
+ block_mask.seq_lengths = (S, T_pos + S)
632
+ block_mask.mask_mod = offset_mask_mod(attention_mask.mask_mod, offset=T_pos)
633
+
634
+ h_BSD = self.tok_embeddings(tokens)
635
+
636
+ coord_xy = coord_xy if coord_xy is not None else h_BSD.new_empty(0)
637
+ size_hw = size_hw if size_hw is not None else h_BSD.new_empty(0)
638
+ h_BSD = self._encode_coords(h_BSD, tokens, coord_xy)
639
+ h_BSD = self._encode_sizes(h_BSD, tokens, size_hw)
640
+
641
+ if pixel_values is not None:
642
+ assert pixel_mask is not None
643
+ pixel_values = pixel_values.to(self.dtype)
644
+ pixel_mask = pixel_mask.to(self.dtype)
645
+ pixel_patches_NLC = E.rearrange(
646
+ pixel_values,
647
+ "n (t pt) (h ph) (w pw) c -> n (t h w) (pt ph pw c)",
648
+ pt=c.temporal_patch_size, ph=c.spatial_patch_size, pw=c.spatial_patch_size,
649
+ )
650
+ h_BSD = self._scatter_img_tokens_with_projector(h_BSD, pixel_patches_NLC, pixel_mask, tokens)
651
+
652
+ for layer in self.layers.values():
653
+ h_BSD = layer(
654
+ h_BSD, freqs_cis=freqs_cis, freqs_cis_2d=freqs_cis_golden,
655
+ pos_hw=rope_pos_hw, attention_masks=block_mask, kv_cache=kv_cache,
656
+ )
657
+
658
+ h_BSD = self.norm(h_BSD)
659
+ logits_BSV = self.output(h_BSD)
660
+ return logits_BSV, h_BSD
661
+
662
+ # -- Main API: generate --------------------------------------------------
663
+
664
+ @torch.inference_mode()
665
+ def generate(
666
+ self,
667
+ images,
668
+ queries,
669
+ max_new_tokens: int = 2048,
670
+ temperature: float = 0.0,
671
+ top_k: int | None = None,
672
+ min_dimension: int = 256,
673
+ max_dimension: int = 1024,
674
+ compile: bool = True,
675
+ seed: int | None = 42,
676
+ segm_threshold: float = 0.5,
677
+ ) -> list[list[dict]]:
678
+ """
679
+ Segment objects in images matching the given queries.
680
+
681
+ Args:
682
+ images: Single PIL Image (or path/URL) or list of them.
683
+ queries: Single query string or list of query strings (one per image).
684
+ max_new_tokens: Maximum generation steps.
685
+ temperature: Sampling temperature (0.0 = greedy).
686
+ top_k: Top-k sampling (None = disabled).
687
+ min_dimension: Min image side after resize.
688
+ max_dimension: Max image side after resize.
689
+ compile: Whether to torch.compile on first call.
690
+ seed: Random seed for reproducibility (None = non-deterministic).
691
+ segm_threshold: Sigmoid threshold for binary mask.
692
+
693
+ Returns:
694
+ List (per image) of lists (per detection) of dicts::
695
+
696
+ {
697
+ "xy": {"x": float, "y": float},
698
+ "hw": {"h": float, "w": float},
699
+ "mask_rle": {"counts": str, "size": [H, W]},
700
+ }
701
+ """
702
+ self._fuse_weights()
703
+ if compile:
704
+ self.compile_model()
705
+
706
+ # Normalize inputs
707
+ if isinstance(images, (str, Path, Image.Image)):
708
+ images = [images]
709
+ if isinstance(queries, str):
710
+ queries = [queries]
711
+ assert len(images) == len(queries), "Must provide one query per image"
712
+
713
+ device = self.device
714
+ tokenizer = self._get_tokenizer()
715
+ self._pad_token_id = tokenizer.convert_tokens_to_ids("<|pad|>")
716
+ stop_token_ids = [self.config.eos_id, tokenizer.convert_tokens_to_ids("<|end_of_query|>")]
717
+
718
+ # Store original image sizes for mask resizing
719
+ pil_images = [load_image(img).convert("RGB") for img in images]
720
+ original_sizes = [(img.height, img.width) for img in pil_images]
721
+
722
+ # Build prompts
723
+ image_prompt_pairs = [
724
+ (img, f"<|image|>Segment these expressions in the image:<|start_of_query|>{q}<|REF_SEG|>")
725
+ for img, q in zip(pil_images, queries)
726
+ ]
727
+
728
+ # Preprocess
729
+ batch_inputs = process_batch(
730
+ tokenizer, self.config, image_prompt_pairs,
731
+ max_length=4096, min_dimension=min_dimension, max_dimension=max_dimension,
732
+ )
733
+ batch_inputs = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in batch_inputs.items()}
734
+
735
+ tokens = batch_inputs["tokens"]
736
+ B, L = tokens.size()
737
+ block_size = 128
738
+ S = (L + max_new_tokens + block_size - 1) // block_size * block_size
739
+ assert S <= self.config.max_seq_len
740
+
741
+ rng = torch.Generator(device).manual_seed(seed) if seed is not None else None
742
+
743
+ kv_cache = KVCache(
744
+ max_batch_size=B, max_seq_length=S, n_heads=self.config.n_heads,
745
+ head_dim=self.config.head_dim, num_layers=self.config.n_layers,
746
+ )
747
+
748
+ padded_tokens = torch.full((B, S), self._pad_token_id, dtype=tokens.dtype, device=device)
749
+ padded_tokens[:, :L] = tokens
750
+
751
+ attention_mask = self.get_attention_mask(padded_tokens, max_len=S)
752
+
753
+ all_xy, all_hw = self._extract_coords([[]])
754
+ coord_xy = all_xy.to(device=device, dtype=self.dtype)
755
+ size_hw_t = all_hw.to(device=device, dtype=self.dtype)
756
+
757
+ # Prefill
758
+ logits_BSV, h_BSD = self.forward(
759
+ tokens=tokens, rope_pos_t=batch_inputs["pos_t"], rope_pos_hw=batch_inputs["pos_hw"],
760
+ attention_mask=attention_mask, kv_cache=kv_cache,
761
+ pixel_values=batch_inputs["pixel_values"], pixel_mask=batch_inputs["pixel_mask"],
762
+ coord_xy=coord_xy, size_hw=size_hw_t,
763
+ )
764
+
765
+ hr_img_features = self.upsample_img_features(
766
+ h_BSD, tokens, batch_inputs["pixel_values"], batch_inputs["pixel_mask"],
767
+ )
768
+
769
+ aux_output_B = [[] for _ in range(B)]
770
+ stop_ids = torch.tensor(stop_token_ids).to(device)
771
+ should_stop_B = torch.full((B,), False, dtype=torch.bool, device=device)
772
+
773
+ # Decode loop
774
+ while not torch.all(should_stop_B) and (pos := kv_cache.get_pos()) < S:
775
+ tokens_B1 = sample_next_token(logits_BSV[:, -1], rng, temperature, top_k)
776
+
777
+ if torch.any(should_stop_B):
778
+ tokens_B1 = tokens_B1.clone()
779
+ tokens_B1[should_stop_B, :] = self._pad_token_id
780
+ padded_tokens[:, pos] = tokens_B1[:, -1]
781
+
782
+ # Decode coords
783
+ coord_logits = self.decode_coords(h_BSD[:, -1:], tokens_B1)
784
+ xy_b2 = torch.argmax(coord_logits, dim=-1) / coord_logits.size(-1)
785
+ coord_preds = [{"x": xy[0].item(), "y": xy[1].item()} for xy in xy_b2]
786
+ sample_w_coord = torch.where(tokens_B1 == self.config.coord_token_id)[0]
787
+ for i, b in enumerate(sample_w_coord.tolist()):
788
+ aux_output_B[b].append(coord_preds[i])
789
+
790
+ # Decode sizes
791
+ size_logits = self.decode_sizes(h_BSD[:, -1:], tokens_B1)
792
+ hw_b2 = self.process_sizes(size_logits)
793
+ size_preds = [{"h": hw[0].item(), "w": hw[1].item()} for hw in hw_b2]
794
+ sample_w_size = torch.where(tokens_B1 == self.config.size_token_id)[0]
795
+ for i, b in enumerate(sample_w_size.tolist()):
796
+ aux_output_B[b].append(size_preds[i])
797
+
798
+ # Decode segmentation
799
+ sample_w_segm = torch.where(tokens_B1 == self.config.seg_token_id)[0]
800
+ segm_tokens = h_BSD[sample_w_segm, -1, :]
801
+ segm_tokens = self.proj_segm(segm_tokens)
802
+ segm_masks = torch.einsum("kdhw,kd->khw", hr_img_features[sample_w_segm], segm_tokens)
803
+ for i, b in enumerate(sample_w_segm):
804
+ aux_output_B[b].append(segm_masks[i])
805
+
806
+ # Next step
807
+ logits_BSV, h_BSD = self.forward(
808
+ tokens=tokens_B1, attention_mask=attention_mask,
809
+ coord_xy=xy_b2.to(self.dtype), size_hw=hw_b2.to(self.dtype), kv_cache=kv_cache,
810
+ )
811
+
812
+ hit_stop_B = torch.isin(tokens_B1, stop_ids).any(dim=-1)
813
+ should_stop_B = should_stop_B.logical_or(hit_stop_B)
814
+
815
+ # Post-process: convert aux outputs to structured results with RLE masks
816
+ pixel_mask_batch = batch_inputs["pixel_mask"][:, 0] # (B, H, W)
817
+ results = []
818
+ for b in range(B):
819
+ dets = self._postprocess_aux(
820
+ aux_output_B[b], pixel_mask_batch[b], original_sizes[b], segm_threshold,
821
+ )
822
+ results.append(dets)
823
+
824
+ return results
825
+
826
+ # -- Post-processing helpers ---------------------------------------------
827
+
828
+ def _extract_coords(self, coords_BO: list[list]):
829
+ all_xy, all_hw = [], []
830
+ for coords_O in coords_BO:
831
+ if not coords_O:
832
+ continue
833
+ for coords in coords_O:
834
+ for k, v in coords.items():
835
+ if k.startswith(("x", "y")):
836
+ all_xy.append(v)
837
+ elif k.startswith(("h", "w")):
838
+ all_hw.append(v)
839
+ return torch.tensor(all_xy), torch.tensor(all_hw)
840
+
841
+ def _postprocess_aux(
842
+ self,
843
+ aux_list: list,
844
+ pixel_mask_hw: T,
845
+ orig_hw: tuple[int, int],
846
+ threshold: float,
847
+ ) -> list[dict]:
848
+ """Convert raw aux outputs into structured detections with RLE masks."""
849
+ orig_h, orig_w = orig_hw
850
+
851
+ # Find active image region from pixel mask
852
+ nonzero = torch.nonzero(pixel_mask_hw, as_tuple=False)
853
+ if len(nonzero) > 0:
854
+ min_h, min_w = nonzero.min(dim=0)[0]
855
+ max_h, max_w = nonzero.max(dim=0)[0]
856
+ act_h = (max_h - min_h + 1).item()
857
+ act_w = (max_w - min_w + 1).item()
858
+ else:
859
+ min_h = min_w = 0
860
+ act_h = act_w = None
861
+
862
+ # Group into triplets: coord, size, mask
863
+ detections = []
864
+ step = 3 # coord, size, mask
865
+ for i in range(0, len(aux_list), step):
866
+ if i + 2 >= len(aux_list):
867
+ break
868
+ xy = aux_list[i]
869
+ hw = aux_list[i + 1]
870
+ mask_logits = aux_list[i + 2]
871
+ if not isinstance(mask_logits, torch.Tensor):
872
+ continue
873
+
874
+ # Crop to active region
875
+ if act_h is not None and act_w is not None:
876
+ mask_logits = mask_logits[min_h:min_h + act_h, min_w:min_w + act_w]
877
+
878
+ # Resize to original image size
879
+ mask_logits = mask_logits.unsqueeze(0).unsqueeze(0).float()
880
+ mask_logits = F.interpolate(mask_logits, size=(orig_h, orig_w), mode="bilinear", align_corners=False)
881
+ mask_logits = mask_logits.squeeze(0).squeeze(0)
882
+
883
+ # Threshold
884
+ binary_mask = (torch.sigmoid(mask_logits) > threshold).bool()
885
+
886
+ # Encode as COCO RLE
887
+ rle_list = self._mask_to_coco_rle(binary_mask.unsqueeze(0))
888
+ mask_rle = rle_list[0] if rle_list else {"counts": "", "size": [orig_h, orig_w]}
889
+
890
+ detections.append({
891
+ "xy": xy,
892
+ "hw": hw,
893
+ "mask_rle": mask_rle,
894
+ })
895
+
896
+ return detections
processing_falcon_perception.py ADDED
@@ -0,0 +1,423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import math
3
+
4
+ import einops as E
5
+ import numpy as np
6
+ import requests
7
+ import torch
8
+ from PIL import Image
9
+ from transformers.image_processing_utils import BaseImageProcessor
10
+ from transformers.image_transforms import convert_to_rgb, resize
11
+ from transformers.image_utils import (
12
+ ImageInput,
13
+ get_image_size,
14
+ infer_channel_dimension_format,
15
+ to_numpy_array,
16
+ valid_images,
17
+ validate_preprocess_arguments,
18
+ )
19
+
20
+ IMAGE_MEAN = [0.5, 0.5, 0.5]
21
+ IMAGE_STD = [0.5, 0.5, 0.5]
22
+
23
+
24
+ def load_image(image):
25
+ if image is None:
26
+ return None
27
+ if isinstance(image, Image.Image):
28
+ return image
29
+ if isinstance(image, str):
30
+ if image.startswith(("http://", "https://")):
31
+ response = requests.get(image, timeout=10)
32
+ response.raise_for_status()
33
+ return Image.open(io.BytesIO(response.content))
34
+ if image.endswith(".npy"):
35
+ img_array = io.BytesIO(np.load(image))
36
+ return Image.open(img_array)
37
+ return Image.open(image)
38
+ if isinstance(image, np.bytes_):
39
+ return Image.open(io.BytesIO(image))
40
+ if isinstance(image, np.ndarray):
41
+ return Image.fromarray(image)
42
+ raise TypeError(f"Unknown image format {image}")
43
+
44
+
45
+ def load_images(images_input, min_dimension: int, max_dimension: int):
46
+ images = []
47
+ if images_input is not None:
48
+ for inp in images_input:
49
+ img = load_image(inp)
50
+ img = resize_image_if_necessary(img, min_dimension, max_dimension)
51
+ images.append(img)
52
+ return images
53
+
54
+
55
+ def resize_image_if_necessary(
56
+ image,
57
+ shortest_dimension=224,
58
+ longest_dimension=896,
59
+ ):
60
+ original_width, original_height = image.size
61
+ aspect_ratio = original_width / original_height
62
+
63
+ if (
64
+ shortest_dimension <= original_width <= longest_dimension
65
+ and shortest_dimension <= original_height <= longest_dimension
66
+ ):
67
+ return image
68
+
69
+ is_vertical_image = original_width < original_height
70
+ if original_width < shortest_dimension or original_height < shortest_dimension:
71
+ if is_vertical_image:
72
+ new_width = shortest_dimension
73
+ new_height = int(new_width / aspect_ratio)
74
+ else:
75
+ new_height = shortest_dimension
76
+ new_width = int(new_height * aspect_ratio)
77
+ else:
78
+ if is_vertical_image:
79
+ new_width = longest_dimension
80
+ new_height = int(new_width / aspect_ratio)
81
+ else:
82
+ new_height = longest_dimension
83
+ new_width = int(new_height * aspect_ratio)
84
+
85
+ if new_width > longest_dimension:
86
+ new_width = longest_dimension
87
+ new_height = int(new_width / aspect_ratio)
88
+ if new_height > longest_dimension:
89
+ new_height = longest_dimension
90
+ new_width = int(new_height * aspect_ratio)
91
+
92
+ resized_image = image.resize((new_width, new_height))
93
+ return resized_image
94
+
95
+
96
+ def smart_resize(
97
+ image,
98
+ factor: int,
99
+ resample,
100
+ input_data_format,
101
+ min_pixels: int = 56 * 56,
102
+ max_pixels: int = 14 * 14 * 4 * 1280,
103
+ ):
104
+ height, width = get_image_size(image, channel_dim=input_data_format)
105
+ if height < factor or width < factor:
106
+ raise ValueError(f"{height=} or {width=} must be larger than {factor=}")
107
+ if max(height, width) / min(height, width) > 200:
108
+ raise ValueError(
109
+ f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}"
110
+ )
111
+ h_bar = round(height / factor) * factor
112
+ w_bar = round(width / factor) * factor
113
+ if h_bar * w_bar > max_pixels:
114
+ beta = np.sqrt((height * width) / max_pixels)
115
+ h_bar = math.floor(height / beta / factor) * factor
116
+ w_bar = math.floor(width / beta / factor) * factor
117
+ elif h_bar * w_bar < min_pixels:
118
+ beta = np.sqrt(min_pixels / (height * width))
119
+ h_bar = math.ceil(height * beta / factor) * factor
120
+ w_bar = math.ceil(width * beta / factor) * factor
121
+ image = resize(
122
+ image,
123
+ size=(h_bar, w_bar),
124
+ resample=resample,
125
+ input_data_format=input_data_format,
126
+ )
127
+ return image
128
+
129
+
130
+ class ImageProcessor(BaseImageProcessor):
131
+ def __init__(
132
+ self,
133
+ patch_size,
134
+ merge_size,
135
+ do_resize: bool = True,
136
+ resample: Image.Resampling = Image.Resampling.BICUBIC,
137
+ do_rescale: bool = True,
138
+ rescale_factor: float = 1 / 255,
139
+ do_normalize: bool = True,
140
+ image_mean: float | list[float] | None = None,
141
+ image_std: float | list[float] | None = None,
142
+ do_convert_rgb: bool = True,
143
+ min_pixels: int = 56 * 56,
144
+ max_pixels: int = 28 * 28 * 1280,
145
+ **kwargs,
146
+ ) -> None:
147
+ super().__init__(**kwargs)
148
+ self.do_resize = do_resize
149
+ self.resample = resample
150
+ self.do_rescale = do_rescale
151
+ self.rescale_factor = rescale_factor
152
+ self.do_normalize = do_normalize
153
+ self.image_mean = image_mean or IMAGE_MEAN
154
+ self.image_std = image_std or IMAGE_STD
155
+ self.min_pixels = min_pixels
156
+ self.max_pixels = max_pixels
157
+ self.patch_size = patch_size
158
+ self.merge_size = merge_size
159
+ self.size = {"min_pixels": min_pixels, "max_pixels": max_pixels}
160
+ self.do_convert_rgb = do_convert_rgb
161
+ validate_preprocess_arguments(
162
+ rescale_factor=self.rescale_factor,
163
+ do_normalize=self.do_normalize,
164
+ image_mean=self.image_mean,
165
+ image_std=self.image_std,
166
+ do_resize=self.do_resize,
167
+ size=self.size,
168
+ resample=self.resample,
169
+ )
170
+
171
+ def _preprocess(self, image: ImageInput, do_rescale=None, do_normalize=None):
172
+ if self.do_convert_rgb:
173
+ image = convert_to_rgb(image)
174
+ image = to_numpy_array(image)
175
+ input_data_format = infer_channel_dimension_format(image)
176
+ if self.do_resize:
177
+ image = smart_resize(
178
+ image,
179
+ factor=self.patch_size * self.merge_size,
180
+ resample=self.resample,
181
+ input_data_format=input_data_format,
182
+ min_pixels=self.min_pixels,
183
+ max_pixels=self.max_pixels,
184
+ )
185
+ if do_rescale or self.do_rescale:
186
+ image = self.rescale(image, scale=self.rescale_factor, input_data_format=input_data_format)
187
+ if do_normalize or self.do_normalize:
188
+ image = self.normalize(
189
+ image=image, mean=self.image_mean, std=self.image_std,
190
+ input_data_format=input_data_format,
191
+ )
192
+ return image
193
+
194
+ def preprocess(self, images: list[ImageInput] | None, do_rescale=None, do_normalize=None, **kwargs):
195
+ del kwargs
196
+ if images is None:
197
+ return []
198
+ images = [item for item in images if item is not None]
199
+ if not valid_images(images):
200
+ raise ValueError(
201
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
202
+ "torch.Tensor, tf.Tensor or jax.ndarray."
203
+ )
204
+ pixel_values = []
205
+ for image in images:
206
+ processed_image = self._preprocess(image, do_rescale, do_normalize)
207
+ processed_image = processed_image[None, ...]
208
+ pixel_values.append(processed_image)
209
+ return pixel_values
210
+
211
+ def batch_images_with_mask(self, pixel_values, max_image_height, max_image_width):
212
+ if pixel_values is None:
213
+ return None
214
+ pixel_values = [item for item in pixel_values if item is not None and len(item) != 0]
215
+ if len(pixel_values) == 0:
216
+ return None
217
+ pixel_values = [torch.from_numpy(img) for img in pixel_values]
218
+ max_temporal = max(img.shape[0] for img in pixel_values)
219
+
220
+ def pad_image_and_mask(img):
221
+ time_steps, height, width, channels = img.shape
222
+ if channels != 3:
223
+ raise ValueError(f"Expected 3-channel RGB images, got {channels} channels.")
224
+ padding = (0, 0, 0, max_image_width - width, 0, max_image_height - height, 0, max_temporal - time_steps)
225
+ padded_image = torch.nn.functional.pad(img, padding)
226
+ mask = torch.zeros((max_temporal, max_image_height, max_image_width), dtype=torch.long)
227
+ mask[:time_steps, :height, :width] = 1
228
+ return padded_image, mask
229
+
230
+ padded_pixel_values, padding_masks = zip(*[pad_image_and_mask(img) for img in pixel_values])
231
+ padded_pixel_values = torch.stack(list(padded_pixel_values))
232
+ padding_masks = torch.stack(list(padding_masks))
233
+ return {"pixel_values": padded_pixel_values, "padding_mask": padding_masks}
234
+
235
+
236
+ # ---------------------------------------------------------------------------
237
+ # Positional encoding helpers
238
+ # ---------------------------------------------------------------------------
239
+
240
+ def _compute_image_spatial_positions(
241
+ pixel_mask_THW: torch.Tensor,
242
+ spatial_patch_size: int,
243
+ temporal_patch_size: int = 1,
244
+ ) -> tuple[torch.Tensor, torch.Tensor]:
245
+ mask_thw = E.reduce(
246
+ pixel_mask_THW,
247
+ "(t tp) (h hp) (w wp) -> t h w",
248
+ reduction="any",
249
+ tp=temporal_patch_size,
250
+ hp=spatial_patch_size,
251
+ wp=spatial_patch_size,
252
+ )
253
+ width = E.reduce(mask_thw.sum(dim=-1).int(), "t h -> ", reduction="max")
254
+ height = E.reduce(mask_thw.sum(dim=-2).int(), "t w -> ", reduction="max")
255
+ xlim = torch.sqrt(width / height)
256
+ ylim = torch.sqrt(height / width)
257
+ xpos = torch.linspace(-xlim, xlim, int(width))
258
+ ypos = torch.linspace(-ylim, ylim, int(height))
259
+ wpos, hpos = torch.meshgrid(xpos, ypos, indexing="xy")
260
+ return hpos.flatten(), wpos.flatten()
261
+
262
+
263
+ def _get_image_token_masks(tokens, config):
264
+ spatial_mask = tokens == config.img_id
265
+ no_increase_mask = (
266
+ spatial_mask
267
+ | (tokens == config.image_reg_1_token_id)
268
+ | (tokens == config.image_reg_2_token_id)
269
+ | (tokens == config.image_reg_3_token_id)
270
+ | (tokens == config.image_reg_4_token_id)
271
+ | (tokens == config.img_end_id)
272
+ )
273
+ return spatial_mask, no_increase_mask
274
+
275
+
276
+ def get_pos_thw(
277
+ tokens: torch.Tensor,
278
+ pixel_masks_NTHW: torch.Tensor,
279
+ config,
280
+ spatial_patch_size: int,
281
+ temporal_patch_size: int = 1,
282
+ pad_token_id: int = None,
283
+ ):
284
+ assert pad_token_id is not None
285
+ assert tokens.ndim == 2
286
+ assert pixel_masks_NTHW.ndim == 4
287
+
288
+ spatial_img_token_mask_BS, no_increase_idx_img_token_mask_BS = _get_image_token_masks(tokens, config)
289
+
290
+ hpos_parts, wpos_parts = [], []
291
+ for i in range(pixel_masks_NTHW.shape[0]):
292
+ h, w = _compute_image_spatial_positions(pixel_masks_NTHW[i], spatial_patch_size, temporal_patch_size)
293
+ hpos_parts.append(h)
294
+ wpos_parts.append(w)
295
+
296
+ hpos_N = torch.cat(hpos_parts) if hpos_parts else torch.empty(0)
297
+ wpos_N = torch.cat(wpos_parts) if wpos_parts else torch.empty(0)
298
+
299
+ expected_tokens = spatial_img_token_mask_BS.sum().item()
300
+ actual_tokens = hpos_N.numel()
301
+ assert actual_tokens == expected_tokens, (
302
+ f"Mismatch between spatial image tokens ({expected_tokens}) and generated positions ({actual_tokens})."
303
+ )
304
+
305
+ hpos_BS = torch.full_like(tokens, fill_value=torch.nan, dtype=torch.float, device=tokens.device)
306
+ wpos_BS = torch.full_like(tokens, fill_value=torch.nan, dtype=torch.float, device=tokens.device)
307
+ hpos_BS = hpos_BS.masked_scatter_(spatial_img_token_mask_BS, hpos_N)
308
+ wpos_BS = wpos_BS.masked_scatter_(spatial_img_token_mask_BS, wpos_N)
309
+
310
+ tpos_BS = torch.ones_like(tokens, dtype=torch.float, device=tokens.device)
311
+ tpos_BS[no_increase_idx_img_token_mask_BS] = 0
312
+ tpos_BS = torch.cumsum(tpos_BS, dim=1) - 1
313
+ tpos_BS[tokens == pad_token_id] = 0
314
+
315
+ hw_pos_BS2 = torch.stack([hpos_BS, wpos_BS], dim=-1)
316
+ return tpos_BS.long(), hw_pos_BS2
317
+
318
+
319
+ def calculate_image_tokens(image, patch_size, merge_size):
320
+ height, width = get_image_size(image)
321
+ return int((height * width) / (patch_size * patch_size * merge_size * merge_size))
322
+
323
+
324
+ def tokenize_inputs(prompt, images, tokenizer, config, patch_size, merge_size, max_length):
325
+ img_reg_ids = [
326
+ config.image_reg_1_token_id,
327
+ config.image_reg_2_token_id,
328
+ config.image_reg_3_token_id,
329
+ config.image_reg_4_token_id,
330
+ ]
331
+
332
+ if images is not None and len(images) > 0:
333
+ image_token_counts = [calculate_image_tokens(image, patch_size, merge_size) for image in images]
334
+ else:
335
+ image_token_counts = []
336
+
337
+ image_token = tokenizer.convert_ids_to_tokens(config.img_id)
338
+ prompt_chunks = [tokenizer.encode(chunk) for chunk in prompt.split(image_token)]
339
+
340
+ def insert_separator(X, sep):
341
+ return [ele for sublist in zip(X, sep) for ele in sublist][:-1]
342
+
343
+ input_ids = []
344
+ offset = 0
345
+ bos_id = getattr(tokenizer, "bos_token_id", None)
346
+ if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and bos_id is not None and prompt_chunks[0][0] == bos_id:
347
+ offset = 1
348
+ input_ids.append(prompt_chunks[0][0])
349
+
350
+ separators = []
351
+ for count in image_token_counts:
352
+ tokens = [config.img_id] * count
353
+ image_block = [config.image_cls_token_id, *img_reg_ids, *tokens, config.img_end_id]
354
+ separators.append(image_block)
355
+
356
+ if len(separators) != 0 and len(separators) != len(prompt_chunks):
357
+ separators.append(separators[-1])
358
+
359
+ selected_images = []
360
+ if len(separators) == 0:
361
+ input_ids = prompt_chunks[0]
362
+ else:
363
+ for index, x in enumerate(insert_separator(prompt_chunks, separators)):
364
+ if index % 2 != 0:
365
+ if (len(input_ids) + len(x)) < max_length:
366
+ input_ids.extend(x)
367
+ selected_images.append(images[index // 2])
368
+ elif index % 2 == 0:
369
+ input_ids.extend(x[offset:])
370
+
371
+ input_ids = torch.LongTensor(input_ids)
372
+ return input_ids, selected_images
373
+
374
+
375
+ def process_batch(
376
+ tokenizer,
377
+ config,
378
+ image_prompt_pairs,
379
+ max_length,
380
+ min_dimension,
381
+ max_dimension,
382
+ patch_size=16,
383
+ merge_size=1,
384
+ ):
385
+ """
386
+ Process a batch of images with text prompts.
387
+ Uses LEFT PADDING for proper batch generation with causal models.
388
+ """
389
+ all_input_ids = []
390
+ all_selected_images = []
391
+ processor_local = ImageProcessor(patch_size, merge_size)
392
+
393
+ for img_input, prompt in image_prompt_pairs:
394
+ img = load_image(img_input)
395
+ if img is not None:
396
+ img = resize_image_if_necessary(img, min_dimension, max_dimension)
397
+ images = processor_local.preprocess(images=[img] if img else [])
398
+ input_ids, selected_images = tokenize_inputs(
399
+ prompt, images, tokenizer, config, patch_size, merge_size, max_length,
400
+ )
401
+ all_input_ids.append(input_ids)
402
+ all_selected_images.extend(selected_images)
403
+
404
+ pad_token_id = tokenizer.convert_tokens_to_ids("<|pad|>")
405
+ padded_input_ids = torch.nn.utils.rnn.pad_sequence(
406
+ all_input_ids, batch_first=True, padding_value=pad_token_id, padding_side="left",
407
+ )
408
+
409
+ processed = processor_local.batch_images_with_mask(all_selected_images, max_dimension, max_dimension)
410
+ assert processed is not None
411
+
412
+ pos_t, pos_hw = get_pos_thw(
413
+ padded_input_ids, processed["padding_mask"], config, patch_size, pad_token_id=pad_token_id,
414
+ )
415
+
416
+ return {
417
+ "tokens": padded_input_ids,
418
+ "pixel_values": processed["pixel_values"],
419
+ "pixel_mask": processed["padding_mask"],
420
+ "pos_t": pos_t,
421
+ "pos_hw": pos_hw,
422
+ "pad_token_id": pad_token_id,
423
+ }
rope.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import einops as E
2
+ import torch
3
+
4
+
5
+ def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0) -> torch.Tensor:
6
+ """
7
+ Precompute the frequency tensor for complex exponentials (cis) with given dimensions.
8
+
9
+ This function calculates a frequency tensor with complex exponentials using the given dimension 'dim'
10
+ and the end index 'end'. The 'theta' parameter scales the frequencies.
11
+ The returned tensor contains complex values in complex64 data type.
12
+
13
+ Args:
14
+ dim (int): Dimension of the frequency tensor.
15
+ end (int): End index for precomputing frequencies.
16
+ theta (float, optional): Scaling factor for frequency computation. Defaults to 10000.0.
17
+
18
+ Returns:
19
+ torch.Tensor: Precomputed frequency tensor with complex exponentials.
20
+ """
21
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
22
+ t = torch.arange(end, device=freqs.device)
23
+ freqs = torch.outer(t, freqs).float()
24
+ freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64
25
+ return freqs_cis # [S, D//2]
26
+
27
+
28
+ def apply_rotary_emb(
29
+ xq: torch.Tensor,
30
+ xk: torch.Tensor,
31
+ freqs_cis: torch.Tensor,
32
+ ) -> tuple[torch.Tensor, torch.Tensor]:
33
+ """1D rotary embedding"""
34
+ xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
35
+ xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
36
+ assert freqs_cis.ndim == 3, (
37
+ "Freqs_cis must be indexed by position ids already and has shape (B,S,D)"
38
+ )
39
+ freqs_cis = E.rearrange(freqs_cis, "b s d -> b s 1 d")
40
+ xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
41
+ xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
42
+ return xq_out.type_as(xq), xk_out.type_as(xk)
43
+
44
+
45
+ ###### 2D golden rope
46
+ """
47
+ Dimension key:
48
+ B: batch size
49
+ S: number of tokens per sample, Seqlen
50
+ T: Number of selected Tokens
51
+ P: pos_dim
52
+ h: n_heads
53
+ d: head_dim
54
+ F: num_freqs == head_dim // 2
55
+ """
56
+
57
+
58
+ def apply_golden_freqs_cis_to_visual_pos(freqs_hFP, pos_BSP) -> torch.Tensor:
59
+ """
60
+ This function is applied once per input batch, and the cached
61
+ freqs_cis is passed through to all layers.
62
+ Safe for Torch‑Inductor because it never uses boolean indexing on a symbolic tensor.
63
+ """
64
+ # 1. Boolean mask → integer indices (no unbacked shapes)
65
+ img_mask_BS = E.reduce(~torch.isnan(pos_BSP), 'b s p -> b s', reduction='all')
66
+ idx_b, idx_s = torch.nonzero(img_mask_BS, as_tuple=True) # each shape: (N,)
67
+
68
+ # 2. Gather the positional tensor for those tokens
69
+ pos_tP = pos_BSP[idx_b, idx_s].float() # (N, p)
70
+
71
+ # 3. Project positions onto the frequency table → angles θ
72
+ theta_thF = torch.einsum("tp,hfp->thf", pos_tP, freqs_hFP.float()) # (t, h, f)
73
+
74
+ # 4. Convert to complex numbers on the unit circle
75
+ freqs_cis_thF = torch.polar(torch.ones_like(theta_thF), theta_thF)
76
+ return freqs_cis_thF
77
+
78
+
79
+ def apply_golden_rotary_emb(input_BShd, freqs_cis_thF, pos_BSP) -> torch.Tensor:
80
+ """
81
+ Rotates *only* the image tokens in `input_BShd`. No boolean indexing,
82
+ so it is safe for Torch‑Inductor.
83
+ """
84
+ img_mask_BS = E.reduce(~torch.isnan(pos_BSP), 'b s p -> b s', reduction='all')
85
+ idx_b, idx_s = torch.nonzero(img_mask_BS, as_tuple=True) # (N,)
86
+
87
+ input_thd = input_BShd[idx_b, idx_s].float() # (N, h, d)
88
+ x_even = input_thd[..., 0::2] # (N, h, F)
89
+ x_odd = input_thd[..., 1::2] # (N, h, F)
90
+
91
+ cos_thF = freqs_cis_thF.real
92
+ sin_thF = freqs_cis_thF.imag
93
+
94
+ # (a + ib) * (c + id) = (ac - bd) + i(ad + bc)
95
+ rot_even = x_even * cos_thF - x_odd * sin_thF
96
+ rot_odd = x_even * sin_thF + x_odd * cos_thF
97
+
98
+ output_real = torch.empty_like(input_thd)
99
+ output_real[..., 0::2] = rot_even
100
+ output_real[..., 1::2] = rot_odd
101
+ output_real = output_real.type_as(input_BShd)
102
+
103
+ output_BShd = input_BShd.clone()
104
+ output_BShd[idx_b, idx_s] = output_real
105
+
106
+ return output_BShd
107
+
108
+
109
+ def apply_3d_rotary_emb(
110
+ xq: torch.Tensor, # (B, S, H, D)
111
+ xk: torch.Tensor, # (B, S, H, D)
112
+ freqs_cis: torch.Tensor,
113
+ freqs_cis_2d: torch.Tensor | None,
114
+ pos_hw: torch.Tensor | None, # (B,S,3)
115
+ ) -> tuple[torch.Tensor, torch.Tensor]:
116
+ xq_t, xq_hw = xq.chunk(chunks=2, dim=-1)
117
+ xk_t, xk_hw = xk.chunk(chunks=2, dim=-1)
118
+ B, S, H, D = xq.shape
119
+
120
+ xq_t, xk_t = apply_rotary_emb(xq_t, xk_t, freqs_cis)
121
+ if freqs_cis_2d is not None and pos_hw is not None:
122
+ xq_hw = apply_golden_rotary_emb(xq_hw, freqs_cis_2d, pos_hw)
123
+ xk_hw = apply_golden_rotary_emb(xk_hw, freqs_cis_2d, pos_hw)
124
+
125
+ xq_out = torch.concat([xq_t, xq_hw], dim=-1).type_as(xq)
126
+ xk_out = torch.concat([xk_t, xk_hw], dim=-1).type_as(xk)
127
+ return xq_out, xk_out
special_tokens_map.json ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "absence_token": "<|absence|>",
3
+ "additional_special_tokens": [
4
+ "<|pad|>",
5
+ ">>ABSTRACT<<",
6
+ ">>INTRODUCTION<<",
7
+ ">>SUMMARY<<",
8
+ ">>COMMENT<<",
9
+ ">>ANSWER<<",
10
+ ">>QUESTION<<",
11
+ ">>DOMAIN<<",
12
+ ">>PREFIX<<",
13
+ ">>SUFFIX<<",
14
+ ">>MIDDLE<<",
15
+ "<|finetune_right_pad_id|>",
16
+ "<|start_header_id|>",
17
+ "<|end_header_id|>",
18
+ "<|eom_id|>",
19
+ "<|eot_id|>",
20
+ "<|begin_of_text|>",
21
+ ">>TITLE<<",
22
+ "<tool_response>",
23
+ "</tool_response>",
24
+ "<tool_call>",
25
+ "</tool_call>",
26
+ "<schema>",
27
+ "</schema>",
28
+ "<scratch_pad>",
29
+ "</scratch_pad>",
30
+ "<thinking>",
31
+ "</thinking>",
32
+ "<explanation>",
33
+ "</explanation>",
34
+ "<file_sep>",
35
+ "<repo_name>",
36
+ ">>UNUSED_119<<",
37
+ ">>UNUSED_120<<",
38
+ "<|image|>",
39
+ "<|image_row_sep|>",
40
+ "<|start_of_image|>",
41
+ "<|end_of_image|>",
42
+ "<|start_of_video|>",
43
+ "<|end_of_video|>",
44
+ "<|frame_sep|>",
45
+ "<|start_of_turn|>",
46
+ "<|end_of_turn|>",
47
+ "<|start_of_diffusion_query|>",
48
+ "<|end_of_diffusion_query|>",
49
+ "<|diffusion_query|>",
50
+ "<|object|>",
51
+ "<|coord|>",
52
+ "<|size|>",
53
+ "<|perceive|>",
54
+ "<|image_mask_token|>",
55
+ "<|image_cls|>",
56
+ "<|image_reg_1|>",
57
+ "<|image_reg_2|>",
58
+ "<|image_reg_3|>",
59
+ "<|image_reg_4|>",
60
+ "<|image_reg_5|>",
61
+ "<|image_reg_6|>",
62
+ "<|image_reg_7|>",
63
+ "<|image_reg_8|>",
64
+ "<|DET|>",
65
+ "<|POINTING|>",
66
+ "<|OCR_GROUNDING|>",
67
+ "<|OCR_DOC_PARSER|>",
68
+ "<|OCR_PLAIN|>",
69
+ "<|REF_SEG|>",
70
+ "<|POINT_REF_SEG|>",
71
+ "<|CAPTION|>",
72
+ "<|DETAILED_CAPTION|>",
73
+ "<|seg|>",
74
+ "<|end_of_query|>",
75
+ "<|start_of_query|>",
76
+ "<|task_sep|>",
77
+ "<|SEMANTIC_SEG_TASK|>",
78
+ "<|semantic_seg|>",
79
+ "<|presence|>",
80
+ "<|absence|>",
81
+ ">>UNUSED_258<<",
82
+ ">>UNUSED_259<<",
83
+ ">>UNUSED_260<<",
84
+ ">>UNUSED_261<<",
85
+ ">>UNUSED_262<<",
86
+ ">>UNUSED_263<<",
87
+ ">>UNUSED_264<<",
88
+ ">>UNUSED_265<<",
89
+ ">>UNUSED_266<<",
90
+ ">>UNUSED_267<<",
91
+ ">>UNUSED_268<<",
92
+ ">>UNUSED_269<<",
93
+ ">>UNUSED_270<<",
94
+ ">>UNUSED_271<<",
95
+ ">>UNUSED_272<<",
96
+ ">>UNUSED_273<<",
97
+ ">>UNUSED_274<<",
98
+ ">>UNUSED_275<<",
99
+ ">>UNUSED_276<<",
100
+ ">>UNUSED_277<<",
101
+ ">>UNUSED_278<<",
102
+ ">>UNUSED_279<<",
103
+ ">>UNUSED_280<<",
104
+ ">>UNUSED_281<<",
105
+ ">>UNUSED_282<<",
106
+ ">>UNUSED_283<<",
107
+ ">>UNUSED_284<<",
108
+ ">>UNUSED_285<<",
109
+ ">>UNUSED_286<<",
110
+ ">>UNUSED_287<<",
111
+ ">>UNUSED_288<<",
112
+ ">>UNUSED_289<<",
113
+ ">>UNUSED_290<<",
114
+ ">>UNUSED_291<<",
115
+ ">>UNUSED_292<<",
116
+ ">>UNUSED_293<<",
117
+ ">>UNUSED_294<<",
118
+ ">>UNUSED_295<<",
119
+ ">>UNUSED_296<<",
120
+ ">>UNUSED_297<<",
121
+ ">>UNUSED_298<<",
122
+ ">>UNUSED_299<<",
123
+ ">>UNUSED_300<<",
124
+ ">>UNUSED_301<<",
125
+ ">>UNUSED_302<<",
126
+ ">>UNUSED_303<<",
127
+ ">>UNUSED_304<<",
128
+ ">>UNUSED_305<<",
129
+ ">>UNUSED_306<<",
130
+ ">>UNUSED_307<<",
131
+ ">>UNUSED_308<<",
132
+ ">>UNUSED_309<<",
133
+ ">>UNUSED_310<<",
134
+ ">>UNUSED_311<<",
135
+ ">>UNUSED_312<<",
136
+ ">>UNUSED_313<<",
137
+ ">>UNUSED_314<<",
138
+ ">>UNUSED_315<<",
139
+ ">>UNUSED_316<<",
140
+ ">>UNUSED_317<<",
141
+ ">>UNUSED_318<<",
142
+ ">>UNUSED_319<<",
143
+ ">>UNUSED_320<<",
144
+ ">>UNUSED_321<<",
145
+ ">>UNUSED_322<<",
146
+ ">>UNUSED_323<<",
147
+ ">>UNUSED_324<<",
148
+ ">>UNUSED_325<<",
149
+ ">>UNUSED_326<<",
150
+ ">>UNUSED_327<<",
151
+ ">>UNUSED_328<<",
152
+ ">>UNUSED_329<<",
153
+ ">>UNUSED_330<<",
154
+ ">>UNUSED_331<<",
155
+ ">>UNUSED_332<<",
156
+ ">>UNUSED_333<<",
157
+ ">>UNUSED_334<<",
158
+ ">>UNUSED_335<<",
159
+ ">>UNUSED_336<<",
160
+ ">>UNUSED_337<<",
161
+ ">>UNUSED_338<<",
162
+ ">>UNUSED_339<<",
163
+ ">>UNUSED_340<<",
164
+ ">>UNUSED_341<<",
165
+ ">>UNUSED_342<<",
166
+ ">>UNUSED_343<<",
167
+ ">>UNUSED_344<<",
168
+ ">>UNUSED_345<<",
169
+ ">>UNUSED_346<<",
170
+ ">>UNUSED_347<<",
171
+ ">>UNUSED_348<<",
172
+ ">>UNUSED_349<<",
173
+ ">>UNUSED_350<<",
174
+ ">>UNUSED_351<<",
175
+ ">>UNUSED_352<<",
176
+ ">>UNUSED_353<<",
177
+ ">>UNUSED_354<<",
178
+ ">>UNUSED_355<<",
179
+ ">>UNUSED_356<<",
180
+ ">>UNUSED_357<<",
181
+ ">>UNUSED_358<<",
182
+ ">>UNUSED_359<<",
183
+ ">>UNUSED_360<<",
184
+ ">>UNUSED_361<<",
185
+ ">>UNUSED_362<<",
186
+ ">>UNUSED_363<<",
187
+ ">>UNUSED_364<<",
188
+ ">>UNUSED_365<<",
189
+ ">>UNUSED_366<<",
190
+ ">>UNUSED_367<<",
191
+ ">>UNUSED_368<<",
192
+ ">>UNUSED_369<<",
193
+ ">>UNUSED_370<<",
194
+ ">>UNUSED_371<<",
195
+ ">>UNUSED_372<<",
196
+ ">>UNUSED_373<<",
197
+ ">>UNUSED_374<<",
198
+ ">>UNUSED_375<<",
199
+ ">>UNUSED_376<<",
200
+ ">>UNUSED_377<<",
201
+ ">>UNUSED_378<<",
202
+ ">>UNUSED_379<<",
203
+ ">>UNUSED_380<<",
204
+ ">>UNUSED_381<<",
205
+ ">>UNUSED_382<<",
206
+ ">>UNUSED_383<<",
207
+ ">>UNUSED_384<<",
208
+ ">>UNUSED_385<<",
209
+ ">>UNUSED_386<<",
210
+ ">>UNUSED_387<<",
211
+ ">>UNUSED_388<<",
212
+ ">>UNUSED_389<<",
213
+ ">>UNUSED_390<<",
214
+ ">>UNUSED_391<<",
215
+ ">>UNUSED_392<<",
216
+ ">>UNUSED_393<<",
217
+ ">>UNUSED_394<<",
218
+ ">>UNUSED_395<<",
219
+ ">>UNUSED_396<<",
220
+ ">>UNUSED_397<<",
221
+ ">>UNUSED_398<<",
222
+ ">>UNUSED_399<<",
223
+ ">>UNUSED_400<<",
224
+ ">>UNUSED_401<<",
225
+ ">>UNUSED_402<<",
226
+ ">>UNUSED_403<<",
227
+ ">>UNUSED_404<<",
228
+ ">>UNUSED_405<<",
229
+ ">>UNUSED_406<<",
230
+ ">>UNUSED_407<<",
231
+ ">>UNUSED_408<<",
232
+ ">>UNUSED_409<<",
233
+ ">>UNUSED_410<<",
234
+ ">>UNUSED_411<<",
235
+ ">>UNUSED_412<<",
236
+ ">>UNUSED_413<<",
237
+ ">>UNUSED_414<<",
238
+ ">>UNUSED_415<<",
239
+ ">>UNUSED_416<<",
240
+ ">>UNUSED_417<<",
241
+ ">>UNUSED_418<<",
242
+ ">>UNUSED_419<<",
243
+ ">>UNUSED_420<<",
244
+ ">>UNUSED_421<<",
245
+ ">>UNUSED_422<<",
246
+ ">>UNUSED_423<<",
247
+ ">>UNUSED_424<<",
248
+ ">>UNUSED_425<<",
249
+ ">>UNUSED_426<<",
250
+ ">>UNUSED_427<<",
251
+ ">>UNUSED_428<<",
252
+ ">>UNUSED_429<<",
253
+ ">>UNUSED_430<<",
254
+ ">>UNUSED_431<<",
255
+ ">>UNUSED_432<<",
256
+ ">>UNUSED_433<<",
257
+ ">>UNUSED_434<<",
258
+ ">>UNUSED_435<<",
259
+ ">>UNUSED_436<<",
260
+ ">>UNUSED_437<<",
261
+ ">>UNUSED_438<<",
262
+ ">>UNUSED_439<<",
263
+ ">>UNUSED_440<<",
264
+ ">>UNUSED_441<<",
265
+ ">>UNUSED_442<<",
266
+ ">>UNUSED_443<<",
267
+ ">>UNUSED_444<<",
268
+ ">>UNUSED_445<<",
269
+ ">>UNUSED_446<<",
270
+ ">>UNUSED_447<<",
271
+ ">>UNUSED_448<<",
272
+ ">>UNUSED_449<<",
273
+ ">>UNUSED_450<<",
274
+ ">>UNUSED_451<<",
275
+ ">>UNUSED_452<<",
276
+ ">>UNUSED_453<<",
277
+ ">>UNUSED_454<<",
278
+ ">>UNUSED_455<<",
279
+ ">>UNUSED_456<<",
280
+ ">>UNUSED_457<<",
281
+ ">>UNUSED_458<<",
282
+ ">>UNUSED_459<<",
283
+ ">>UNUSED_460<<",
284
+ ">>UNUSED_461<<",
285
+ ">>UNUSED_462<<",
286
+ ">>UNUSED_463<<",
287
+ ">>UNUSED_464<<",
288
+ ">>UNUSED_465<<",
289
+ ">>UNUSED_466<<",
290
+ ">>UNUSED_467<<",
291
+ ">>UNUSED_468<<",
292
+ ">>UNUSED_469<<",
293
+ ">>UNUSED_470<<",
294
+ ">>UNUSED_471<<",
295
+ ">>UNUSED_472<<",
296
+ ">>UNUSED_473<<",
297
+ ">>UNUSED_474<<",
298
+ ">>UNUSED_475<<",
299
+ ">>UNUSED_476<<",
300
+ ">>UNUSED_477<<",
301
+ ">>UNUSED_478<<",
302
+ ">>UNUSED_479<<",
303
+ ">>UNUSED_480<<",
304
+ ">>UNUSED_481<<",
305
+ ">>UNUSED_482<<",
306
+ ">>UNUSED_483<<",
307
+ ">>UNUSED_484<<",
308
+ ">>UNUSED_485<<",
309
+ ">>UNUSED_486<<",
310
+ ">>UNUSED_487<<",
311
+ ">>UNUSED_488<<",
312
+ ">>UNUSED_489<<",
313
+ ">>UNUSED_490<<",
314
+ ">>UNUSED_491<<",
315
+ ">>UNUSED_492<<",
316
+ ">>UNUSED_493<<",
317
+ ">>UNUSED_494<<",
318
+ ">>UNUSED_495<<",
319
+ ">>UNUSED_496<<",
320
+ ">>UNUSED_497<<",
321
+ ">>UNUSED_498<<",
322
+ ">>UNUSED_499<<",
323
+ ">>UNUSED_500<<",
324
+ ">>UNUSED_501<<",
325
+ ">>UNUSED_502<<",
326
+ ">>UNUSED_503<<",
327
+ ">>UNUSED_504<<",
328
+ ">>UNUSED_505<<",
329
+ ">>UNUSED_506<<",
330
+ ">>UNUSED_507<<",
331
+ ">>UNUSED_508<<",
332
+ ">>UNUSED_509<<",
333
+ ">>UNUSED_510<<",
334
+ ">>UNUSED_511<<"
335
+ ],
336
+ "caption_token": "<|CAPTION|>",
337
+ "coord_token": "<|coord|>",
338
+ "det_token": "<|DET|>",
339
+ "detailed_caption_token": "<|DETAILED_CAPTION|>",
340
+ "diffusion_query_token": "<|diffusion_query|>",
341
+ "end_of_diffusion_query_token": "<|end_of_diffusion_query|>",
342
+ "end_of_image_token": "<|end_of_image|>",
343
+ "end_of_query_token": "<|end_of_query|>",
344
+ "end_of_turn_token": "<|end_of_turn|>",
345
+ "end_of_video_token": "<|end_of_video|>",
346
+ "eos_token": "<|end_of_text|>",
347
+ "frame_sep_token": "<|frame_sep|>",
348
+ "image_cls_token": "<|image_cls|>",
349
+ "image_mask_token": "<|image_mask_token|>",
350
+ "image_reg_1_token": "<|image_reg_1|>",
351
+ "image_reg_2_token": "<|image_reg_2|>",
352
+ "image_reg_3_token": "<|image_reg_3|>",
353
+ "image_reg_4_token": "<|image_reg_4|>",
354
+ "image_reg_5_token": "<|image_reg_5|>",
355
+ "image_reg_6_token": "<|image_reg_6|>",
356
+ "image_reg_7_token": "<|image_reg_7|>",
357
+ "image_reg_8_token": "<|image_reg_8|>",
358
+ "image_row_sep_token": "<|image_row_sep|>",
359
+ "image_token": "<|image|>",
360
+ "object_token": "<|object|>",
361
+ "ocr_doc_parser_token": "<|OCR_DOC_PARSER|>",
362
+ "ocr_grounding_token": "<|OCR_GROUNDING|>",
363
+ "ocr_plain_token": "<|OCR_PLAIN|>",
364
+ "pad_token": "<|pad|>",
365
+ "perceive_token": "<|perceive|>",
366
+ "point_ref_seg_token": "<|POINT_REF_SEG|>",
367
+ "pointing_token": "<|POINTING|>",
368
+ "presence_token": "<|presence|>",
369
+ "ref_seg_token": "<|REF_SEG|>",
370
+ "seg_token": "<|seg|>",
371
+ "semantic_seg_task_token": "<|SEMANTIC_SEG_TASK|>",
372
+ "semantic_seg_token": "<|semantic_seg|>",
373
+ "size_token": "<|size|>",
374
+ "start_of_diffusion_query_token": "<|start_of_diffusion_query|>",
375
+ "start_of_image_token": "<|start_of_image|>",
376
+ "start_of_query_token": "<|start_of_query|>",
377
+ "start_of_turn_token": "<|start_of_turn|>",
378
+ "start_of_video_token": "<|start_of_video|>",
379
+ "task_sep_token": "<|task_sep|>"
380
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
The diff for this file is too large to render. See raw diff