Octopus1 commited on
Commit
b899f25
·
verified ·
1 Parent(s): f10e224

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. LICENSE +15 -0
  2. README.md +92 -0
  3. modeling_page.py +1096 -0
LICENSE ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ library_name: transformers
4
+ tags:
5
+ - gaze-estimation
6
+ - gaze-target-estimation
7
+ - computer-vision
8
+ - dinov3
9
+ language:
10
+ - en
11
+ ---
12
+
13
+ # PaGE: Patch-level Gaze Estimation
14
+
15
+ PaGE is a gaze target estimation model that predicts where a person is looking in a scene.
16
+ It uses two DINOv3 ViT backbones (a **scene branch** and a **head branch**) whose features
17
+ interact through cross-attention layers, then decodes a gaze **heatmap** and an **in/out** score
18
+ (whether the gaze target is inside the image).
19
+
20
+ This repository holds the **model code** (`modeling_page.py`) referenced by all PaGE weight
21
+ repositories via `auto_map`. The weight checkpoints live in their own repos (see below).
22
+
23
+ ## Model checkpoints
24
+
25
+ | Model | Backbone | Params (approx.) | Weight repo |
26
+ |-------|----------|------------------|-------------|
27
+ | PaGE-ViT-S | DINOv3 ViT-S/16 | ~25M | [`Octopus1/page-vits`](https://huggingface.co/Octopus1/page-vits) |
28
+ | PaGE-ViT-S+ | DINOv3 ViT-S+/16 (gated MLP) | ~30M | [`Octopus1/page-vitsplus`](https://huggingface.co/Octopus1/page-vitsplus) |
29
+ | PaGE-ViT-B | DINOv3 ViT-B/16 | ~90M | [`Octopus1/page-vitb`](https://huggingface.co/Octopus1/page-vitb) |
30
+ | PaGE-ViT-B (screen) | DINOv3 ViT-B/16 | ~90M | [`Octopus1/page-vitb-screen`](https://huggingface.co/Octopus1/page-vitb-screen) |
31
+ | PaGE-ViT-H+ | DINOv3 ViT-H+/16 (gated MLP) | ~1.7B | [`Octopus1/page-vithplus`](https://huggingface.co/Octopus1/page-vithplus) |
32
+
33
+ > **No external DINOv3 weights are required.** Each checkpoint contains the full backbone
34
+ > weights in its `safetensors` files. The DINOv3 model *structure* is provided by
35
+ > `transformers>=4.56` (built-in `dinov3_vit`).
36
+
37
+ ## Installation
38
+
39
+ ```bash
40
+ pip install torch torchvision timm "transformers>=4.56" safetensors pillow
41
+ ```
42
+
43
+ ## Quick start
44
+
45
+ ```python
46
+ from transformers import AutoModel, AutoImageProcessor
47
+ from PIL import Image
48
+ import torch
49
+
50
+ repo = "Octopus1/page-vitb"
51
+ model = AutoModel.from_pretrained(repo, trust_remote_code=True).eval()
52
+ processor = AutoImageProcessor.from_pretrained(repo, trust_remote_code=True)
53
+
54
+ scene = Image.open("scene.jpg").convert("RGB")
55
+ head_crop = Image.open("head.jpg").convert("RGB") # cropped head of the person
56
+
57
+ # bboxes: list (one per scene image) of bbox lists; bbox = (xmin, ymin, xmax, ymax) in [0,1]
58
+ inputs = processor(scene, head_crops=[head_crop], bboxes=[[(0.10, 0.10, 0.30, 0.40)]])
59
+
60
+ with torch.no_grad():
61
+ out = model(inputs)
62
+
63
+ heatmap = out["heatmap"][0] # [Np, 64, 64] gaze heatmap per person
64
+ inout = out["inout"][0] # [Np] in/out score per person
65
+ ```
66
+
67
+ ## Inputs
68
+
69
+ The model's `forward` takes a dict:
70
+
71
+ - `images`: list of scene tensors `[B, 3, 512, 512]`
72
+ - `head_images`: list of head-crop tensors `[sum(Np), 3, 256, 256]` (one entry per backbone stream)
73
+ - `bboxes`: list (len `B`) of lists of `Np` bboxes; each bbox is `(xmin, ymin, xmax, ymax)` in `[0, 1]` image coordinates
74
+
75
+ The `PaGEImageProcessor` (via `AutoImageProcessor`) builds this dict from a PIL scene image,
76
+ per-person head crops, and bboxes.
77
+
78
+ ## Outputs
79
+
80
+ - `heatmap`: list (len `B`) of `[Np, 64, 64]` tensors (sigmoid applied)
81
+ - `inout`: list (len `B`) of `[Np]` tensors (sigmoid applied)
82
+
83
+ ## Architecture
84
+
85
+ PaGE = two DINOv3 ViT backbones (scene @ 512², head @ 256²) → 1× self-attn each → 5×
86
+ scene/head cross-attention interaction layers (axial 2D RoPE) → heatmap head (deconv + 1×1 conv)
87
+ + in/out head (MLP on pooled scene+head inout tokens). Decoder dim 256, 8 heads, GEGLU FFN,
88
+ 4 register tokens + 1 inout token per stream. All final-architecture variants share this design.
89
+
90
+ ## License
91
+
92
+ Apache-2.0.
modeling_page.py ADDED
@@ -0,0 +1,1096 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # PaGE: Patch-level Gaze Estimation with cross-attention scene/head interaction.
3
+ #
4
+ # This file is self-contained. Dependencies: torch, torchvision, timm, transformers (>=4.56, which ships DINOv3 built-in).
5
+ # The DINOv3 backbones are constructed from config only (no external checkpoint download); their weights live in this
6
+ # model's safetensors alongside the gaze decoder.
7
+ #
8
+ # Auto-map entry points: PaGEConfig, PaGEModel, PaGEImageProcessor.
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+ from typing import Optional, Tuple, Type, Union, List
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+ import torchvision
19
+
20
+ from timm.models.vision_transformer import Block
21
+ from timm.layers.mlp import SwiGLU, Mlp
22
+ from timm.layers import DropPath, LayerNorm, LayerScale, use_fused_attn
23
+
24
+ from transformers import PretrainedConfig, PreTrainedModel
25
+ from transformers.image_processing_utils import BaseImageProcessor
26
+
27
+ # --------------------------------------------------------------------------- #
28
+ # Robust DINOv3 import (built into transformers >= 4.56). #
29
+ # --------------------------------------------------------------------------- #
30
+ try:
31
+ from transformers.models.dinov3_vit import DINOv3ViTModel, DINOv3ViTConfig
32
+ except Exception as e: # pragma: no cover
33
+ raise ImportError(
34
+ "PaGE requires transformers>=4.56 with built-in DINOv3 support (`transformers.models.dinov3_vit`). "
35
+ f"Import failed: {e!r}"
36
+ )
37
+
38
+
39
+ # =========================================================================== #
40
+ # Vendored utilities (from gazelle.utils) #
41
+ # =========================================================================== #
42
+ def repeat_tensors(tensor, repeat_counts):
43
+ repeated_tensors = [
44
+ tensor[i:i + 1].repeat(repeat, *[1] * (tensor.ndim - 1))
45
+ for i, repeat in enumerate(repeat_counts)
46
+ ]
47
+ return torch.cat(repeated_tensors, dim=0)
48
+
49
+
50
+ def split_tensors(tensor, split_counts):
51
+ indices = torch.cumsum(torch.tensor([0] + split_counts), dim=0)
52
+ return [tensor[indices[i]:indices[i + 1]] for i in range(len(split_counts))]
53
+
54
+
55
+ class TransposeLayerNorm(nn.Module):
56
+ """Transpose 2D feature maps for layer norm, then transpose back."""
57
+
58
+ def __init__(self, dim):
59
+ super().__init__()
60
+ self.ln = nn.LayerNorm(dim)
61
+
62
+ def forward(self, x: torch.Tensor):
63
+ x = x.permute(0, 2, 3, 1).contiguous()
64
+ x = self.ln(x)
65
+ x = x.permute(0, 3, 1, 2).contiguous()
66
+ return x
67
+
68
+
69
+ def positionalencoding2d(d_model, height, width):
70
+ if d_model % 4 != 0:
71
+ raise ValueError(
72
+ "Cannot use sin/cos positional encoding with odd dimension (got dim={:d})".format(d_model))
73
+ pe = torch.zeros(d_model, height, width)
74
+ d_model = int(d_model / 2)
75
+ div_term = torch.exp(torch.arange(0., d_model, 2)
76
+ * -(math.log(10000.0) / d_model))
77
+ pos_w = torch.arange(0., width).unsqueeze(1)
78
+ pos_h = torch.arange(0., height).unsqueeze(1)
79
+ pe[0:d_model:2, :, :] = torch.sin(pos_w * div_term).transpose(0, 1).unsqueeze(1).repeat(1, height, 1)
80
+ pe[1:d_model:2, :, :] = torch.cos(pos_w * div_term).transpose(0, 1).unsqueeze(1).repeat(1, height, 1)
81
+ pe[d_model::2, :, :] = torch.sin(pos_h * div_term).transpose(0, 1).unsqueeze(2).repeat(1, 1, width)
82
+ pe[d_model + 1::2, :, :] = torch.cos(pos_h * div_term).transpose(0, 1).unsqueeze(2).repeat(1, 1, width)
83
+ return pe
84
+
85
+
86
+ # =========================================================================== #
87
+ # Vendored Axial 2D RoPE self-attention (from gazelle.rope_self_attention) #
88
+ # =========================================================================== #
89
+ GridSize = Optional[Tuple[int, int]]
90
+ Rect = Union[Tuple[float, float, float, float], torch.Tensor]
91
+
92
+
93
+ class Axial2dRotaryEmbedding(nn.Module):
94
+ def __init__(self, dim: int, base: float = 100.0) -> None:
95
+ super().__init__()
96
+ if dim <= 0 or dim % 4 != 0:
97
+ raise ValueError(f"`dim` must be a positive multiple of 4, got {dim}.")
98
+ self.dim = dim
99
+ self.axis_dim = dim // 2
100
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.axis_dim, 2, dtype=torch.float32) / self.axis_dim))
101
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
102
+
103
+ def _axis_cos_sin(self, coords, *, device, dtype):
104
+ inv_freq = self.inv_freq.to(device=device, dtype=torch.float32)
105
+ freqs = coords.to(device=device, dtype=torch.float32)[:, None] * inv_freq[None, :]
106
+ return freqs.cos().to(dtype=dtype), freqs.sin().to(dtype=dtype)
107
+
108
+ @staticmethod
109
+ def _rotate_axis(x, cos, sin):
110
+ x = x.reshape(*x.shape[:-1], -1, 2)
111
+ x_even, x_odd = x.unbind(dim=-1)
112
+ cos = cos[None, None, :, :]
113
+ sin = sin[None, None, :, :]
114
+ x_rot = torch.stack((x_even * cos - x_odd * sin, x_even * sin + x_odd * cos), dim=-1)
115
+ return x_rot.flatten(-2)
116
+
117
+ def forward(self, q, k, grid_size, num_front_tokens=0):
118
+ _, _, n, head_dim = q.shape
119
+ gh, gw = grid_size
120
+ num_patch_tokens = gh * gw
121
+ expected = num_front_tokens + num_patch_tokens
122
+ if n != expected:
123
+ raise ValueError(f"Token count mismatch: got N={n}, expected {num_front_tokens} front + {gh}*{gw} = {expected}.")
124
+ if self.dim > head_dim:
125
+ raise ValueError(f"RoPE dim {self.dim} exceeds head_dim {head_dim}.")
126
+ q_front, q_patch = q[:, :, :num_front_tokens], q[:, :, num_front_tokens:]
127
+ k_front, k_patch = k[:, :, :num_front_tokens], k[:, :, num_front_tokens:]
128
+ yy, xx = torch.meshgrid(torch.arange(gh, device=q.device), torch.arange(gw, device=q.device), indexing="ij")
129
+ yy = yy.reshape(-1); xx = xx.reshape(-1)
130
+ cos_y, sin_y = self._axis_cos_sin(yy, device=q.device, dtype=q.dtype)
131
+ cos_x, sin_x = self._axis_cos_sin(xx, device=q.device, dtype=q.dtype)
132
+
133
+ def apply_rope(t):
134
+ t_rope, t_pass = t[..., :self.dim], t[..., self.dim:]
135
+ t_y, t_x = t_rope.split(self.axis_dim, dim=-1)
136
+ t_y = self._rotate_axis(t_y, cos_y, sin_y)
137
+ t_x = self._rotate_axis(t_x, cos_x, sin_x)
138
+ return torch.cat((t_y, t_x, t_pass), dim=-1)
139
+
140
+ q_patch = apply_rope(q_patch)
141
+ k_patch = apply_rope(k_patch)
142
+ q = torch.cat((q_front, q_patch), dim=2)
143
+ k = torch.cat((k_front, k_patch), dim=2)
144
+ return q, k
145
+
146
+
147
+ class AxialRoPEAttention(nn.Module):
148
+ fused_attn: bool
149
+
150
+ def __init__(self, dim, num_heads=8, attn_head_dim=None, dim_out=None, qkv_bias=False,
151
+ qk_norm=False, scale_norm=False, proj_bias=True, attn_drop=0.0, proj_drop=0.0,
152
+ norm_layer=None, grid_size=None, num_front_tokens=0, rope_base=100.0,
153
+ rope_dim=None, device=None, dtype=None):
154
+ super().__init__()
155
+ dd = {"device": device, "dtype": dtype}
156
+ dim_out = dim_out or dim
157
+ head_dim = attn_head_dim or dim // num_heads
158
+ if attn_head_dim is None:
159
+ assert dim % num_heads == 0
160
+ if qk_norm or scale_norm:
161
+ assert norm_layer is not None
162
+ rope_dim = head_dim if rope_dim is None else rope_dim
163
+ if rope_dim > head_dim:
164
+ raise ValueError(f"`rope_dim`={rope_dim} exceeds head_dim={head_dim}.")
165
+ if rope_dim % 4 != 0:
166
+ raise ValueError("For axial 2D RoPE, `rope_dim` must be divisible by 4.")
167
+ if num_front_tokens < 0:
168
+ raise ValueError("`num_front_tokens` must be non-negative.")
169
+ self.num_heads = num_heads
170
+ self.head_dim = head_dim
171
+ self.attn_dim = num_heads * head_dim
172
+ self.scale = head_dim ** -0.5
173
+ self.fused_attn = use_fused_attn()
174
+ self.grid_size = grid_size
175
+ self.num_front_tokens = num_front_tokens
176
+ self.qkv = nn.Linear(dim, self.attn_dim * 3, bias=qkv_bias, **dd)
177
+ self.q_norm = norm_layer(head_dim, **dd) if qk_norm else nn.Identity()
178
+ self.k_norm = norm_layer(head_dim, **dd) if qk_norm else nn.Identity()
179
+ self.rope = Axial2dRotaryEmbedding(rope_dim, base=rope_base)
180
+ self.attn_drop = nn.Dropout(attn_drop)
181
+ self.norm = norm_layer(self.attn_dim, **dd) if scale_norm else nn.Identity()
182
+ self.proj = nn.Linear(self.attn_dim, dim_out, bias=proj_bias, **dd)
183
+ self.proj_drop = nn.Dropout(proj_drop)
184
+
185
+ def set_grid_size(self, grid_size):
186
+ self.grid_size = grid_size
187
+
188
+ def _infer_grid_size(self, num_patch_tokens):
189
+ if self.grid_size is not None:
190
+ gh, gw = self.grid_size
191
+ if gh * gw != num_patch_tokens:
192
+ raise ValueError(f"`grid_size={self.grid_size}` implies {gh * gw} patches, got {num_patch_tokens}.")
193
+ return gh, gw
194
+ side = math.isqrt(num_patch_tokens)
195
+ if side * side != num_patch_tokens:
196
+ raise ValueError("Cannot infer a non-square patch grid from the token sequence.")
197
+ return side, side
198
+
199
+ def forward(self, x, attn_mask=None, is_causal=False):
200
+ b, n, _ = x.shape
201
+ num_patch_tokens = n - self.num_front_tokens
202
+ if num_patch_tokens <= 0:
203
+ raise ValueError(f"Expected patch tokens after {self.num_front_tokens} front tokens, got N={n}.")
204
+ qkv = self.qkv(x).reshape(b, n, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
205
+ q, k, v = qkv.unbind(0)
206
+ q = self.q_norm(q); k = self.k_norm(k)
207
+ grid_size = self._infer_grid_size(num_patch_tokens)
208
+ q, k = self.rope(q, k, grid_size=grid_size, num_front_tokens=self.num_front_tokens)
209
+ if self.fused_attn:
210
+ x = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask,
211
+ dropout_p=self.attn_drop.p if self.training else 0.0, is_causal=is_causal)
212
+ else:
213
+ q = q * self.scale
214
+ attn = q @ k.transpose(-2, -1)
215
+ attn = attn.softmax(dim=-1)
216
+ attn = self.attn_drop(attn)
217
+ x = attn @ v
218
+ x = x.transpose(1, 2).reshape(b, n, self.attn_dim)
219
+ x = self.norm(x)
220
+ x = self.proj(x)
221
+ x = self.proj_drop(x)
222
+ return x
223
+
224
+
225
+ class AxialRoPEBlock(nn.Module):
226
+ def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False, qk_norm=False,
227
+ scale_attn_norm=False, scale_mlp_norm=False, proj_bias=True, proj_drop=0.0,
228
+ attn_drop=0.0, init_values=None, drop_path=0.0, act_layer=nn.GELU,
229
+ norm_layer=LayerNorm, mlp_layer=Mlp, attn_layer=None, depth=0,
230
+ grid_size=None, num_front_tokens=0, rope_base=100.0, rope_dim=None, device=None, dtype=None):
231
+ super().__init__()
232
+ dd = {"device": device, "dtype": dtype}
233
+ self.norm1 = norm_layer(dim, **dd)
234
+ self.attn = AxialRoPEAttention(dim=dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_norm=qk_norm,
235
+ scale_norm=scale_attn_norm, proj_bias=proj_bias, attn_drop=attn_drop,
236
+ proj_drop=proj_drop, norm_layer=norm_layer, grid_size=grid_size,
237
+ num_front_tokens=num_front_tokens, rope_base=rope_base, rope_dim=rope_dim, **dd)
238
+ self.ls1 = LayerScale(dim, init_values=init_values, **dd) if init_values is not None else nn.Identity()
239
+ self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
240
+ self.norm2 = norm_layer(dim, **dd)
241
+ self.mlp = mlp_layer(in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=act_layer,
242
+ norm_layer=norm_layer if scale_mlp_norm else None, bias=proj_bias, drop=proj_drop, **dd)
243
+ self.ls2 = LayerScale(dim, init_values=init_values, **dd) if init_values is not None else nn.Identity()
244
+ self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
245
+
246
+ def set_grid_size(self, grid_size):
247
+ self.attn.set_grid_size(grid_size)
248
+
249
+ def forward(self, x, attn_mask=None, is_causal=False):
250
+ x = x + self.drop_path1(self.ls1(self.attn(self.norm1(x), attn_mask=attn_mask, is_causal=is_causal)))
251
+ x = x + self.drop_path2(self.ls2(self.mlp(self.norm2(x))))
252
+ return x
253
+
254
+
255
+ # =========================================================================== #
256
+ # Vendored cross-attention (no RoPE) (from gazelle.cross_attention) #
257
+ # =========================================================================== #
258
+ def _cross_attn_mask(attn_mask, dtype):
259
+ if attn_mask is None:
260
+ return None
261
+ if attn_mask.dtype == torch.bool:
262
+ bias = torch.zeros_like(attn_mask, dtype=dtype)
263
+ bias.masked_fill_(~attn_mask, float("-inf"))
264
+ return bias
265
+ return attn_mask
266
+
267
+
268
+ class CrossAttention(nn.Module):
269
+ fused_attn: bool
270
+
271
+ def __init__(self, dim, num_heads=8, attn_head_dim=None, dim_out=None, qkv_bias=False,
272
+ qk_norm=False, scale_norm=False, proj_bias=True, attn_drop=0.0, proj_drop=0.0, norm_layer=None):
273
+ super().__init__()
274
+ dim_out = dim_out or dim
275
+ if attn_head_dim is None:
276
+ assert dim % num_heads == 0
277
+ head_dim = dim // num_heads
278
+ else:
279
+ head_dim = attn_head_dim
280
+ if qk_norm or scale_norm:
281
+ assert norm_layer is not None
282
+ self.num_heads = num_heads
283
+ self.head_dim = head_dim
284
+ self.attn_dim = num_heads * head_dim
285
+ self.scale = head_dim ** -0.5
286
+ self.fused_attn = use_fused_attn()
287
+ self.q = nn.Linear(dim, self.attn_dim, bias=qkv_bias)
288
+ self.k = nn.Linear(dim, self.attn_dim, bias=qkv_bias)
289
+ self.v = nn.Linear(dim, self.attn_dim, bias=qkv_bias)
290
+ self.q_norm = norm_layer(head_dim) if qk_norm else nn.Identity()
291
+ self.k_norm = norm_layer(head_dim) if qk_norm else nn.Identity()
292
+ self.attn_drop = nn.Dropout(attn_drop)
293
+ self.norm = norm_layer(self.attn_dim) if scale_norm else nn.Identity()
294
+ self.proj = nn.Linear(self.attn_dim, dim_out, bias=proj_bias)
295
+ self.proj_drop = nn.Dropout(proj_drop)
296
+
297
+ def forward(self, x_q, x_kv, attn_mask=None):
298
+ B, Nq, _ = x_q.shape
299
+ Bkv, Nk, _ = x_kv.shape
300
+ assert B == Bkv
301
+ q = self.q(x_q).reshape(B, Nq, self.num_heads, self.head_dim).transpose(1, 2)
302
+ k = self.k(x_kv).reshape(B, Nk, self.num_heads, self.head_dim).transpose(1, 2)
303
+ v = self.v(x_kv).reshape(B, Nk, self.num_heads, self.head_dim).transpose(1, 2)
304
+ q = self.q_norm(q); k = self.k_norm(k)
305
+ if self.fused_attn:
306
+ x = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask,
307
+ dropout_p=self.attn_drop.p if self.training else 0.0)
308
+ else:
309
+ q = q * self.scale
310
+ attn = q @ k.transpose(-2, -1)
311
+ attn_bias = _cross_attn_mask(attn_mask, attn.dtype)
312
+ if attn_bias is not None:
313
+ attn = attn + attn_bias
314
+ attn = attn.softmax(dim=-1)
315
+ attn = self.attn_drop(attn)
316
+ x = attn @ v
317
+ x = x.transpose(1, 2).reshape(B, Nq, self.attn_dim)
318
+ x = self.norm(x)
319
+ x = self.proj(x)
320
+ x = self.proj_drop(x)
321
+ return x
322
+
323
+
324
+ class CrossAttentionBlock(nn.Module):
325
+ def __init__(self, dim, num_heads, qkv_bias=False, qk_norm=False, scale_attn_norm=False,
326
+ proj_bias=True, proj_drop=0.0, attn_drop=0.0, init_values=None, drop_path=0.0,
327
+ norm_layer=LayerNorm):
328
+ super().__init__()
329
+ self.norm_q = norm_layer(dim)
330
+ self.norm_kv = norm_layer(dim)
331
+ self.attn = CrossAttention(dim=dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_norm=qk_norm,
332
+ scale_norm=scale_attn_norm, proj_bias=proj_bias, attn_drop=attn_drop,
333
+ proj_drop=proj_drop, norm_layer=norm_layer)
334
+ self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
335
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
336
+
337
+ def forward(self, x_q, x_kv, attn_mask=None):
338
+ x_q = x_q + self.drop_path(self.ls1(self.attn(self.norm_q(x_q), self.norm_kv(x_kv), attn_mask=attn_mask)))
339
+ return x_q
340
+
341
+
342
+ # =========================================================================== #
343
+ # Vendored Axial 2D RoPE cross-attention (from gazelle.rope_cross_attention) #
344
+ # =========================================================================== #
345
+ def _infer_square_grid_size(num_patch_tokens, *, name):
346
+ side = math.isqrt(num_patch_tokens)
347
+ if side * side != num_patch_tokens:
348
+ raise ValueError(f"Cannot infer square grid for {name} from {num_patch_tokens} patch tokens.")
349
+ return side, side
350
+
351
+
352
+ def _as_batched_rect(rect, *, batch_size, device, dtype, name):
353
+ rect = torch.as_tensor(rect, device=device, dtype=dtype)
354
+ if rect.ndim == 1:
355
+ if rect.shape[0] != 4:
356
+ raise ValueError(f"{name}_rect must have shape [4] or [B, 4].")
357
+ rect = rect[None, :].expand(batch_size, 4)
358
+ elif rect.ndim == 2:
359
+ if rect.shape[1] != 4:
360
+ raise ValueError(f"{name}_rect must have shape [4] or [B, 4].")
361
+ if rect.shape[0] == 1:
362
+ rect = rect.expand(batch_size, 4)
363
+ elif rect.shape[0] != batch_size:
364
+ raise ValueError(f"{name}_rect has batch size {rect.shape[0]}, expected {batch_size}.")
365
+ else:
366
+ raise ValueError(f"{name}_rect must have shape [4] or [B, 4].")
367
+ return rect
368
+
369
+
370
+ def _native_grid_coords(grid_size, *, batch_size, device, dtype):
371
+ gh, gw = grid_size
372
+ yy, xx = torch.meshgrid(torch.arange(gh, device=device, dtype=dtype),
373
+ torch.arange(gw, device=device, dtype=dtype), indexing="ij")
374
+ coords = torch.stack((yy.reshape(-1), xx.reshape(-1)), dim=-1)
375
+ return coords[None, :, :].expand(batch_size, -1, -1)
376
+
377
+
378
+ def _rect_grid_coords(grid_size, rect, *, align_corners):
379
+ b = rect.shape[0]; gh, gw = grid_size
380
+ device = rect.device; dtype = rect.dtype
381
+ y0, x0, y1, x1 = rect.unbind(dim=-1)
382
+ if align_corners:
383
+ if gh == 1:
384
+ ys = ((y0 + y1 - 1.0) * 0.5)[:, None]
385
+ else:
386
+ iy = torch.linspace(0.0, 1.0, gh, device=device, dtype=dtype)
387
+ ys = y0[:, None] + iy[None, :] * ((y1 - 1.0) - y0)[:, None]
388
+ if gw == 1:
389
+ xs = ((x0 + x1 - 1.0) * 0.5)[:, None]
390
+ else:
391
+ ix = torch.linspace(0.0, 1.0, gw, device=device, dtype=dtype)
392
+ xs = x0[:, None] + ix[None, :] * ((x1 - 1.0) - x0)[:, None]
393
+ else:
394
+ iy = torch.arange(gh, device=device, dtype=dtype) + 0.5
395
+ ix = torch.arange(gw, device=device, dtype=dtype) + 0.5
396
+ ys = y0[:, None] + iy[None, :] * ((y1 - y0) / gh)[:, None] - 0.5
397
+ xs = x0[:, None] + ix[None, :] * ((x1 - x0) / gw)[:, None] - 0.5
398
+ yy = ys[:, :, None].expand(b, gh, gw)
399
+ xx = xs[:, None, :].expand(b, gh, gw)
400
+ return torch.stack((yy.reshape(b, -1), xx.reshape(b, -1)), dim=-1)
401
+
402
+
403
+ def _as_batched_patch_coords(patch_coords, *, batch_size, num_patch_tokens, device, dtype, name):
404
+ patch_coords = torch.as_tensor(patch_coords, device=device, dtype=dtype)
405
+ if patch_coords.ndim == 2:
406
+ if patch_coords.shape != (num_patch_tokens, 2):
407
+ raise ValueError(f"{name}_patch_coords must have shape [{num_patch_tokens}, 2] or [B, {num_patch_tokens}, 2], got {tuple(patch_coords.shape)}.")
408
+ patch_coords = patch_coords[None, :, :].expand(batch_size, -1, -1)
409
+ elif patch_coords.ndim == 3:
410
+ if patch_coords.shape[1:] != (num_patch_tokens, 2):
411
+ raise ValueError(f"{name}_patch_coords must have shape [B, {num_patch_tokens}, 2], got {tuple(patch_coords.shape)}.")
412
+ if patch_coords.shape[0] == 1:
413
+ patch_coords = patch_coords.expand(batch_size, -1, -1)
414
+ elif patch_coords.shape[0] != batch_size:
415
+ raise ValueError(f"{name}_patch_coords has batch size {patch_coords.shape[0]}, expected {batch_size}.")
416
+ else:
417
+ raise ValueError(f"{name}_patch_coords must have shape [N_patch, 2] or [B, N_patch, 2].")
418
+ return patch_coords
419
+
420
+
421
+ def make_stream_patch_coords(*, batch_size, num_patch_tokens, grid_size, rect, patch_coords,
422
+ device, dtype=torch.float32, align_corners=False, name):
423
+ if grid_size is None:
424
+ grid_size = _infer_square_grid_size(num_patch_tokens, name=name)
425
+ gh, gw = grid_size
426
+ expected = gh * gw
427
+ if expected != num_patch_tokens:
428
+ raise ValueError(f"{name}_grid_size={grid_size} implies {expected} patch tokens, but {name} stream has {num_patch_tokens}.")
429
+ if patch_coords is not None and rect is not None:
430
+ raise ValueError(f"Provide either {name}_patch_coords or {name}_rect, not both.")
431
+ if patch_coords is not None:
432
+ return _as_batched_patch_coords(patch_coords, batch_size=batch_size, num_patch_tokens=num_patch_tokens,
433
+ device=device, dtype=dtype, name=name)
434
+ if rect is not None:
435
+ rect = _as_batched_rect(rect, batch_size=batch_size, device=device, dtype=dtype, name=name)
436
+ return _rect_grid_coords(grid_size, rect, align_corners=align_corners)
437
+ return _native_grid_coords(grid_size, batch_size=batch_size, device=device, dtype=dtype)
438
+
439
+
440
+ class Axial2dCrossRotaryEmbedding(nn.Module):
441
+ def __init__(self, dim, base=100.0):
442
+ super().__init__()
443
+ if dim <= 0 or dim % 4 != 0:
444
+ raise ValueError(f"dim must be a positive multiple of 4, got {dim}.")
445
+ self.dim = dim
446
+ self.axis_dim = dim // 2
447
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.axis_dim, 2, dtype=torch.float32) / self.axis_dim))
448
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
449
+
450
+ def _axis_cos_sin(self, coords, *, out_dtype):
451
+ if coords.ndim != 2:
452
+ raise ValueError(f"coords must have shape [B, N], got {tuple(coords.shape)}.")
453
+ coords = coords.to(dtype=torch.float32)
454
+ inv_freq = self.inv_freq.to(device=coords.device, dtype=torch.float32)
455
+ freqs = coords[..., None] * inv_freq[None, None, :]
456
+ return freqs.cos().to(dtype=out_dtype), freqs.sin().to(dtype=out_dtype)
457
+
458
+ @staticmethod
459
+ def _rotate_axis(x, cos, sin):
460
+ x = x.reshape(*x.shape[:-1], -1, 2)
461
+ x_even, x_odd = x.unbind(dim=-1)
462
+ cos = cos[:, None, :, :]
463
+ sin = sin[:, None, :, :]
464
+ x_rot = torch.stack((x_even * cos - x_odd * sin, x_even * sin + x_odd * cos), dim=-1)
465
+ return x_rot.flatten(-2)
466
+
467
+ def rotate_one(self, x, coords_yx, *, num_front_tokens, stream_name):
468
+ b, _, n_total, head_dim = x.shape
469
+ if self.dim > head_dim:
470
+ raise ValueError(f"RoPE dim {self.dim} exceeds head_dim {head_dim} for {stream_name}.")
471
+ if num_front_tokens < 0:
472
+ raise ValueError(f"{stream_name}_num_front_tokens must be non-negative.")
473
+ n_patch = n_total - num_front_tokens
474
+ if n_patch <= 0:
475
+ raise ValueError(f"{stream_name} has no patch tokens after {num_front_tokens} front tokens.")
476
+ if coords_yx.shape != (b, n_patch, 2):
477
+ raise ValueError(f"{stream_name}_coords_yx must have shape [{b}, {n_patch}, 2], got {tuple(coords_yx.shape)}.")
478
+ coords_yx = coords_yx.to(device=x.device)
479
+ x_front = x[:, :, :num_front_tokens, :]
480
+ x_patch = x[:, :, num_front_tokens:, :]
481
+ y = coords_yx[..., 0]
482
+ x_coord = coords_yx[..., 1]
483
+ cos_y, sin_y = self._axis_cos_sin(y, out_dtype=x.dtype)
484
+ cos_x, sin_x = self._axis_cos_sin(x_coord, out_dtype=x.dtype)
485
+ x_rope = x_patch[..., :self.dim]
486
+ x_pass = x_patch[..., self.dim:]
487
+ x_y, x_x = x_rope.split(self.axis_dim, dim=-1)
488
+ x_y = self._rotate_axis(x_y, cos_y, sin_y)
489
+ x_x = self._rotate_axis(x_x, cos_x, sin_x)
490
+ x_patch = torch.cat((x_y, x_x, x_pass), dim=-1)
491
+ if num_front_tokens == 0:
492
+ return x_patch
493
+ return torch.cat((x_front, x_patch), dim=2)
494
+
495
+ def forward(self, q, k, *, q_coords_yx, kv_coords_yx, q_num_front_tokens=0, kv_num_front_tokens=0):
496
+ q = self.rotate_one(q, q_coords_yx, num_front_tokens=q_num_front_tokens, stream_name="q")
497
+ k = self.rotate_one(k, kv_coords_yx, num_front_tokens=kv_num_front_tokens, stream_name="kv")
498
+ return q, k
499
+
500
+
501
+ class AxialRoPECrossAttention(nn.Module):
502
+ fused_attn: bool
503
+
504
+ def __init__(self, dim, num_heads=8, attn_head_dim=None, dim_out=None, qkv_bias=False,
505
+ qk_norm=False, scale_norm=False, proj_bias=True, attn_drop=0.0, proj_drop=0.0,
506
+ norm_layer=None, q_num_front_tokens=0, kv_num_front_tokens=0, rope_base=100.0,
507
+ rope_dim=None, align_corners=False, device=None, dtype=None):
508
+ super().__init__()
509
+ dd = {"device": device, "dtype": dtype}
510
+ dim_out = dim_out or dim
511
+ if attn_head_dim is None:
512
+ assert dim % num_heads == 0
513
+ head_dim = dim // num_heads
514
+ else:
515
+ head_dim = attn_head_dim
516
+ if qk_norm or scale_norm:
517
+ assert norm_layer is not None
518
+ rope_dim = head_dim if rope_dim is None else rope_dim
519
+ if rope_dim > head_dim:
520
+ raise ValueError(f"rope_dim={rope_dim} exceeds head_dim={head_dim}.")
521
+ if rope_dim % 4 != 0:
522
+ raise ValueError("For axial 2D RoPE, `rope_dim` must be divisible by 4.")
523
+ if q_num_front_tokens < 0:
524
+ raise ValueError("q_num_front_tokens must be non-negative.")
525
+ if kv_num_front_tokens < 0:
526
+ raise ValueError("kv_num_front_tokens must be non-negative.")
527
+ self.num_heads = num_heads
528
+ self.head_dim = head_dim
529
+ self.attn_dim = num_heads * head_dim
530
+ self.scale = head_dim ** -0.5
531
+ self.fused_attn = use_fused_attn()
532
+ self.q_num_front_tokens = q_num_front_tokens
533
+ self.kv_num_front_tokens = kv_num_front_tokens
534
+ self.align_corners = align_corners
535
+ self.q = nn.Linear(dim, self.attn_dim, bias=qkv_bias, **dd)
536
+ self.k = nn.Linear(dim, self.attn_dim, bias=qkv_bias, **dd)
537
+ self.v = nn.Linear(dim, self.attn_dim, bias=qkv_bias, **dd)
538
+ self.q_norm = norm_layer(head_dim, **dd) if qk_norm else nn.Identity()
539
+ self.k_norm = norm_layer(head_dim, **dd) if qk_norm else nn.Identity()
540
+ self.rope = Axial2dCrossRotaryEmbedding(dim=rope_dim, base=rope_base)
541
+ self.attn_drop = nn.Dropout(attn_drop)
542
+ self.norm = norm_layer(self.attn_dim, **dd) if scale_norm else nn.Identity()
543
+ self.proj = nn.Linear(self.attn_dim, dim_out, bias=proj_bias, **dd)
544
+ self.proj_drop = nn.Dropout(proj_drop)
545
+
546
+ def forward(self, x_q, x_kv, attn_mask=None, *, q_grid_size=None, kv_grid_size=None,
547
+ q_rect=None, kv_rect=None, q_patch_coords=None, kv_patch_coords=None,
548
+ q_num_front_tokens=None, kv_num_front_tokens=None):
549
+ b, nq, _ = x_q.shape
550
+ b_kv, nk, _ = x_kv.shape
551
+ if b != b_kv:
552
+ raise ValueError(f"x_q and x_kv must have the same batch size, got {b} and {b_kv}.")
553
+ q_num_front_tokens = self.q_num_front_tokens if q_num_front_tokens is None else q_num_front_tokens
554
+ kv_num_front_tokens = self.kv_num_front_tokens if kv_num_front_tokens is None else kv_num_front_tokens
555
+ q_num_patch_tokens = nq - q_num_front_tokens
556
+ kv_num_patch_tokens = nk - kv_num_front_tokens
557
+ if q_num_patch_tokens <= 0:
558
+ raise ValueError(f"x_q has no patch tokens after {q_num_front_tokens} front tokens.")
559
+ if kv_num_patch_tokens <= 0:
560
+ raise ValueError(f"x_kv has no patch tokens after {kv_num_front_tokens} front tokens.")
561
+ coord_dtype = torch.float32
562
+ q_coords_yx = make_stream_patch_coords(batch_size=b, num_patch_tokens=q_num_patch_tokens, grid_size=q_grid_size,
563
+ rect=q_rect, patch_coords=q_patch_coords, device=x_q.device,
564
+ dtype=coord_dtype, align_corners=self.align_corners, name="q")
565
+ kv_coords_yx = make_stream_patch_coords(batch_size=b, num_patch_tokens=kv_num_patch_tokens, grid_size=kv_grid_size,
566
+ rect=kv_rect, patch_coords=kv_patch_coords, device=x_kv.device,
567
+ dtype=coord_dtype, align_corners=self.align_corners, name="kv")
568
+ q = self.q(x_q).reshape(b, nq, self.num_heads, self.head_dim).transpose(1, 2)
569
+ k = self.k(x_kv).reshape(b, nk, self.num_heads, self.head_dim).transpose(1, 2)
570
+ v = self.v(x_kv).reshape(b, nk, self.num_heads, self.head_dim).transpose(1, 2)
571
+ q = self.q_norm(q); k = self.k_norm(k)
572
+ q, k = self.rope(q, k, q_coords_yx=q_coords_yx, kv_coords_yx=kv_coords_yx,
573
+ q_num_front_tokens=q_num_front_tokens, kv_num_front_tokens=kv_num_front_tokens)
574
+ if self.fused_attn:
575
+ x = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask,
576
+ dropout_p=self.attn_drop.p if self.training else 0.0)
577
+ else:
578
+ q = q * self.scale
579
+ attn = q @ k.transpose(-2, -1)
580
+ attn_bias = _cross_attn_mask(attn_mask, attn.dtype)
581
+ if attn_bias is not None:
582
+ attn = attn + attn_bias
583
+ attn = attn.softmax(dim=-1)
584
+ attn = self.attn_drop(attn)
585
+ x = attn @ v
586
+ x = x.transpose(1, 2).reshape(b, nq, self.attn_dim)
587
+ x = self.norm(x)
588
+ x = self.proj(x)
589
+ x = self.proj_drop(x)
590
+ return x
591
+
592
+
593
+ class AxialRoPECrossAttentionBlock(nn.Module):
594
+ def __init__(self, dim, num_heads, qkv_bias=False, qk_norm=False, scale_attn_norm=False,
595
+ proj_bias=True, proj_drop=0.0, attn_drop=0.0, init_values=None, drop_path=0.0,
596
+ norm_layer=LayerNorm, q_num_front_tokens=0, kv_num_front_tokens=0, rope_base=100.0,
597
+ rope_dim=None, align_corners=False, device=None, dtype=None):
598
+ super().__init__()
599
+ dd = {"device": device, "dtype": dtype}
600
+ self.norm_q = norm_layer(dim, **dd)
601
+ self.norm_kv = norm_layer(dim, **dd)
602
+ self.attn = AxialRoPECrossAttention(dim=dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_norm=qk_norm,
603
+ scale_norm=scale_attn_norm, proj_bias=proj_bias, attn_drop=attn_drop,
604
+ proj_drop=proj_drop, norm_layer=norm_layer, q_num_front_tokens=q_num_front_tokens,
605
+ kv_num_front_tokens=kv_num_front_tokens, rope_base=rope_base, rope_dim=rope_dim,
606
+ align_corners=align_corners, **dd)
607
+ self.ls1 = LayerScale(dim, init_values=init_values, **dd) if init_values is not None else nn.Identity()
608
+ self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
609
+
610
+ def forward(self, x_q, x_kv, attn_mask=None, *, q_grid_size=None, kv_grid_size=None,
611
+ q_rect=None, kv_rect=None, q_patch_coords=None, kv_patch_coords=None,
612
+ q_num_front_tokens=None, kv_num_front_tokens=None):
613
+ x_q = x_q + self.drop_path1(self.ls1(self.attn(
614
+ self.norm_q(x_q), self.norm_kv(x_kv), attn_mask=attn_mask, q_grid_size=q_grid_size,
615
+ kv_grid_size=kv_grid_size, q_rect=q_rect, kv_rect=kv_rect, q_patch_coords=q_patch_coords,
616
+ kv_patch_coords=kv_patch_coords, q_num_front_tokens=q_num_front_tokens,
617
+ kv_num_front_tokens=kv_num_front_tokens)))
618
+ return x_q
619
+
620
+
621
+ # =========================================================================== #
622
+ # Block factories + SceneHeadInteraction (from gazelle.cross_attention_model) #
623
+ # =========================================================================== #
624
+ def get_vit_block(dim=256, num_heads=8, mlp_ratio=4, mlp_layer=SwiGLU, drop_path=0.1,
625
+ act_layer=nn.GELU, pos_encoding="rope", num_front_tokens=4, rope_base=100.0):
626
+ if pos_encoding not in {"rope", "sinusoidal", "ape"}:
627
+ raise ValueError(f"pos_encoding must be one of: rope, sinusoidal, ape, got {pos_encoding}")
628
+ if pos_encoding == "rope":
629
+ return AxialRoPEBlock(dim=dim, num_heads=num_heads, mlp_ratio=mlp_ratio, mlp_layer=mlp_layer,
630
+ drop_path=drop_path, act_layer=act_layer, num_front_tokens=num_front_tokens, rope_base=rope_base)
631
+ else:
632
+ return Block(dim=dim, num_heads=num_heads, mlp_ratio=mlp_ratio, mlp_layer=mlp_layer,
633
+ drop_path=drop_path, act_layer=act_layer)
634
+
635
+
636
+ def get_cross_attn_block(dim=256, num_heads=8, drop_path=0.1, pos_encoding="rope",
637
+ q_num_front_tokens=0, kv_num_front_tokens=0, rope_base=100.0):
638
+ if pos_encoding not in {"rope", "sinusoidal", "ape"}:
639
+ raise ValueError(f"pos_encoding must be one of: rope, sinusoidal, ape, got {pos_encoding}")
640
+ if pos_encoding == "rope":
641
+ return AxialRoPECrossAttentionBlock(dim=dim, num_heads=num_heads, drop_path=drop_path,
642
+ q_num_front_tokens=q_num_front_tokens, kv_num_front_tokens=kv_num_front_tokens,
643
+ rope_base=rope_base)
644
+ else:
645
+ return CrossAttentionBlock(dim=dim, num_heads=num_heads, drop_path=drop_path)
646
+
647
+
648
+ class SceneHeadInteraction(nn.Module):
649
+ """Variant A2: synchronous and symmetric feature interaction."""
650
+
651
+ def __init__(self, dim, num_heads=8, mlp_ratio=4, mlp_layer=SwiGLU, act_layer=nn.GELU,
652
+ drop_path=0.0, num_front_tokens=0, pos_encoding="rope"):
653
+ super().__init__()
654
+ if pos_encoding not in {"rope", "sinusoidal", "ape"}:
655
+ raise ValueError(f"pos_encoding must be one of: rope, sinusoidal, ape, got {pos_encoding}")
656
+ self.pos_encoding = pos_encoding
657
+ self.cross_attn_scene = get_cross_attn_block(dim=dim, num_heads=num_heads, pos_encoding=pos_encoding,
658
+ q_num_front_tokens=num_front_tokens, kv_num_front_tokens=num_front_tokens, drop_path=drop_path)
659
+ self.vit_block_scene = get_vit_block(dim=dim, num_heads=num_heads, mlp_ratio=mlp_ratio, mlp_layer=mlp_layer,
660
+ drop_path=drop_path, act_layer=act_layer, num_front_tokens=num_front_tokens, pos_encoding=pos_encoding)
661
+ self.cross_attn_head = get_cross_attn_block(dim=dim, num_heads=num_heads, pos_encoding=pos_encoding,
662
+ q_num_front_tokens=num_front_tokens, kv_num_front_tokens=num_front_tokens, drop_path=drop_path)
663
+ self.vit_block_head = get_vit_block(dim=dim, num_heads=num_heads, mlp_ratio=mlp_ratio, mlp_layer=mlp_layer,
664
+ drop_path=drop_path, act_layer=act_layer, num_front_tokens=num_front_tokens, pos_encoding=pos_encoding)
665
+
666
+ def forward(self, tokens):
667
+ scene_tokens = tokens["scene_tokens"]
668
+ head_tokens = tokens["head_tokens"]
669
+ head_rects = tokens["head_rects"]
670
+ if self.pos_encoding == "rope":
671
+ out_scene_tokens = self.cross_attn_scene(scene_tokens, head_tokens, kv_rect=head_rects)
672
+ out_head_tokens = self.cross_attn_head(head_tokens, scene_tokens, q_rect=head_rects)
673
+ else:
674
+ out_scene_tokens = self.cross_attn_scene(scene_tokens, head_tokens)
675
+ out_head_tokens = self.cross_attn_head(head_tokens, scene_tokens)
676
+ out_scene_tokens = self.vit_block_scene(out_scene_tokens)
677
+ out_head_tokens = self.vit_block_head(out_head_tokens)
678
+ return {"scene_tokens": out_scene_tokens, "head_tokens": out_head_tokens, "head_rects": head_rects}
679
+
680
+
681
+ # =========================================================================== #
682
+ # DINOv3 backbone wrapper (config-only construction, weights from safetensors) #
683
+ # =========================================================================== #
684
+ class PaGEBackbone(nn.Module):
685
+ """
686
+ Wraps a transformers built-in DINOv3ViTModel. Output: patch tokens -> [B, C, H', W'].
687
+ The DINOv3 model is built from config only (no external download).
688
+ """
689
+
690
+ def __init__(self, dinov3_config: DINOv3ViTConfig, in_size=(512, 512)):
691
+ super().__init__()
692
+ self.in_size = in_size
693
+ self.model = DINOv3ViTModel(dinov3_config)
694
+ self.patch_size = int(dinov3_config.patch_size)
695
+ self.embed_dim = int(dinov3_config.hidden_size)
696
+ # CLS(1) + num_register_tokens
697
+ self._num_front = 1 + int(getattr(dinov3_config, "num_register_tokens", 0) or 0)
698
+
699
+ def _get_patch_tokens(self, x: torch.Tensor) -> torch.Tensor:
700
+ out = self.model(pixel_values=x, return_dict=True)
701
+ tokens = getattr(out, "last_hidden_state", None)
702
+ if tokens is None:
703
+ tokens = out[0]
704
+ if not torch.is_tensor(tokens) or tokens.dim() != 3:
705
+ raise RuntimeError("Unexpected DINOv3 output format.")
706
+ tokens = tokens[:, self._num_front:, :] # drop CLS + register tokens
707
+ return tokens
708
+
709
+ def forward(self, x) -> torch.Tensor:
710
+ if isinstance(x, (list, tuple)):
711
+ # head stream comes in as a 1-element list (one backbone branch); unwrap it
712
+ assert len(x) == 1
713
+ x = x[0]
714
+ b, c, h, w = x.shape
715
+ out_h, out_w = self.get_out_size((h, w))
716
+ patch_tokens = self._get_patch_tokens(x)
717
+ if patch_tokens.shape[1] != out_h * out_w:
718
+ raise RuntimeError(
719
+ f"[PaGEBackbone] token count mismatch: {patch_tokens.shape[1]} vs {out_h * out_w}. "
720
+ f"patch_size={self.patch_size}, input={(h, w)}")
721
+ feat = patch_tokens.view(b, out_h, out_w, -1).permute(0, 3, 1, 2).contiguous()
722
+ return feat
723
+
724
+ def get_dimension(self):
725
+ return self.embed_dim
726
+
727
+ def get_out_size(self, in_size):
728
+ h, w = in_size
729
+ return (h // self.patch_size, w // self.patch_size)
730
+
731
+
732
+ # =========================================================================== #
733
+ # PaGE config #
734
+ # =========================================================================== #
735
+ class PaGEConfig(PretrainedConfig):
736
+ model_type = "page"
737
+
738
+ def __init__(
739
+ self,
740
+ # gaze decoder
741
+ dim: int = 256,
742
+ num_heads: int = 8,
743
+ mlp_ratio: float = 4.0,
744
+ mlp_layer: str = "geglu",
745
+ pos_encoding: str = "rope",
746
+ n_scene_self_attn_layers: int = 1,
747
+ n_head_self_attn_layers: int = 1,
748
+ n_scene_head_interaction_layers: int = 5,
749
+ n_reg_tokens: int = 4,
750
+ heatmap_out_size: Tuple[int, int] = (64, 64),
751
+ dino_feature_dropout: float = 0.1,
752
+ drop_path: float = 0.1,
753
+ use_head_prompt: bool = False,
754
+ inout: bool = True,
755
+ # input sizes
756
+ scene_in_size: Tuple[int, int] = (512, 512),
757
+ head_in_size: Tuple[int, int] = (256, 256),
758
+ # image preprocessing
759
+ image_mean: Tuple[float, float, float] = (0.485, 0.456, 0.406),
760
+ image_std: Tuple[float, float, float] = (0.229, 0.224, 0.225),
761
+ # DINOv3 backbone config (shared by scene & head branches)
762
+ dinov3_hidden_size: int = 768,
763
+ dinov3_num_hidden_layers: int = 12,
764
+ dinov3_num_attention_heads: int = 12,
765
+ dinov3_intermediate_size: int = 3072,
766
+ dinov3_num_register_tokens: int = 4,
767
+ dinov3_patch_size: int = 16,
768
+ dinov3_use_gated_mlp: bool = False,
769
+ dinov3_layerscale_value: float = 1.0,
770
+ dinov3_drop_path_rate: float = 0.0,
771
+ dinov3_layer_norm_eps: float = 1e-5,
772
+ **kwargs,
773
+ ):
774
+ self.dim = dim
775
+ self.num_heads = num_heads
776
+ self.mlp_ratio = mlp_ratio
777
+ self.mlp_layer = mlp_layer
778
+ self.pos_encoding = pos_encoding
779
+ self.n_scene_self_attn_layers = n_scene_self_attn_layers
780
+ self.n_head_self_attn_layers = n_head_self_attn_layers
781
+ self.n_scene_head_interaction_layers = n_scene_head_interaction_layers
782
+ self.n_reg_tokens = n_reg_tokens
783
+ self.heatmap_out_size = tuple(heatmap_out_size)
784
+ self.dino_feature_dropout = dino_feature_dropout
785
+ self.drop_path = drop_path
786
+ self.use_head_prompt = use_head_prompt
787
+ self.inout = inout
788
+ self.scene_in_size = tuple(scene_in_size)
789
+ self.head_in_size = tuple(head_in_size)
790
+ self.image_mean = tuple(image_mean)
791
+ self.image_std = tuple(image_std)
792
+ self.dinov3_hidden_size = dinov3_hidden_size
793
+ self.dinov3_num_hidden_layers = dinov3_num_hidden_layers
794
+ self.dinov3_num_attention_heads = dinov3_num_attention_heads
795
+ self.dinov3_intermediate_size = dinov3_intermediate_size
796
+ self.dinov3_num_register_tokens = dinov3_num_register_tokens
797
+ self.dinov3_patch_size = dinov3_patch_size
798
+ self.dinov3_use_gated_mlp = dinov3_use_gated_mlp
799
+ self.dinov3_layerscale_value = dinov3_layerscale_value
800
+ self.dinov3_drop_path_rate = dinov3_drop_path_rate
801
+ self.dinov3_layer_norm_eps = dinov3_layer_norm_eps
802
+ super().__init__(**kwargs)
803
+
804
+ def to_dinov3_config(self) -> DINOv3ViTConfig:
805
+ return DINOv3ViTConfig(
806
+ hidden_size=self.dinov3_hidden_size,
807
+ num_hidden_layers=self.dinov3_num_hidden_layers,
808
+ num_attention_heads=self.dinov3_num_attention_heads,
809
+ intermediate_size=self.dinov3_intermediate_size,
810
+ num_register_tokens=self.dinov3_num_register_tokens,
811
+ patch_size=self.dinov3_patch_size,
812
+ use_gated_mlp=self.dinov3_use_gated_mlp,
813
+ layerscale_value=self.dinov3_layerscale_value,
814
+ drop_path_rate=self.dinov3_drop_path_rate,
815
+ layer_norm_eps=self.dinov3_layer_norm_eps,
816
+ image_size=self.scene_in_size[0],
817
+ )
818
+
819
+
820
+ # =========================================================================== #
821
+ # PaGE model (CrossGaze architecture) #
822
+ # =========================================================================== #
823
+ class PaGEPreTrainedModel(PreTrainedModel):
824
+ config_class = PaGEConfig
825
+ base_model_prefix = "page"
826
+ supports_gradient_checkpointing = False
827
+
828
+ def _init_weights(self, module):
829
+ if isinstance(module, nn.Linear):
830
+ nn.init.trunc_normal_(module.weight, std=0.02)
831
+ if module.bias is not None:
832
+ nn.init.zeros_(module.bias)
833
+ elif isinstance(module, nn.Conv2d):
834
+ nn.init.trunc_normal_(module.weight, std=0.02)
835
+ if module.bias is not None:
836
+ nn.init.zeros_(module.bias)
837
+ elif isinstance(module, nn.Embedding):
838
+ nn.init.trunc_normal_(module.weight, std=0.02)
839
+ elif isinstance(module, nn.LayerNorm):
840
+ nn.init.zeros_(module.bias)
841
+ nn.init.ones_(module.weight)
842
+
843
+
844
+ class PaGEModel(PaGEPreTrainedModel):
845
+ """
846
+ PaGE gaze target estimation model with ViT-adapter-style cross attention between scene and head features.
847
+
848
+ Inputs (dict):
849
+ - "images": scene image tensor [B, 3, H_scene, W_scene]
850
+ - "head_images": list of head-crop tensors, one tensor [sum(Np), 3, H_head, W_head]
851
+ - "bboxes": list (len B) of lists of bboxes; each bbox is (xmin, ymin, xmax, ymax) in [0,1] image coords
852
+
853
+ Outputs (dict):
854
+ - "heatmap": list (len B) of [Np, H_out, W_out] heatmaps (sigmoid applied)
855
+ - "inout": list (len B) of [Np] in/out scores (sigmoid applied) if inout else None
856
+ """
857
+
858
+ def __init__(self, config: PaGEConfig):
859
+ super().__init__(config)
860
+ cfg = config
861
+ dinov3_cfg = cfg.to_dinov3_config()
862
+
863
+ self.scene_branch_backbone = PaGEBackbone(dinov3_cfg, in_size=cfg.scene_in_size)
864
+ self.head_branch_backbone = PaGEBackbone(dinov3_cfg, in_size=cfg.head_in_size)
865
+
866
+ self.dim = cfg.dim
867
+ self.n_scene_self_attn_layers = cfg.n_scene_self_attn_layers
868
+ self.n_head_self_attn_layers = cfg.n_head_self_attn_layers
869
+ self.n_scene_head_interaction_layers = cfg.n_scene_head_interaction_layers
870
+ self.scene_featmap_h, self.scene_featmap_w = self.scene_branch_backbone.get_out_size(cfg.scene_in_size)
871
+ self.head_featmap_h, self.head_featmap_w = self.head_branch_backbone.get_out_size(cfg.head_in_size)
872
+ self.n_reg_tokens = cfg.n_reg_tokens
873
+ self.n_front_tokens = cfg.n_reg_tokens + 1 if cfg.inout else cfg.n_reg_tokens
874
+ self.heatmap_out_size = tuple(cfg.heatmap_out_size)
875
+ self.inout = cfg.inout
876
+ self.pos_encoding = cfg.pos_encoding
877
+ self.use_head_prompt = cfg.use_head_prompt
878
+
879
+ self.scene_proj = nn.Sequential(
880
+ nn.Dropout2d(cfg.dino_feature_dropout),
881
+ nn.Conv2d(self.scene_branch_backbone.get_dimension(), self.dim, 1),
882
+ )
883
+ self.head_proj = nn.Sequential(
884
+ nn.Dropout2d(cfg.dino_feature_dropout),
885
+ nn.Conv2d(self.head_branch_backbone.get_dimension(), self.dim, 1),
886
+ )
887
+ if self.use_head_prompt:
888
+ self.head_position_token = nn.Embedding(1, self.dim)
889
+
890
+ if self.pos_encoding == "ape":
891
+ self.scene_seq_len = self.n_reg_tokens + self.scene_featmap_h * self.scene_featmap_w
892
+ self.head_seq_len = self.n_reg_tokens + self.head_featmap_h * self.head_featmap_w
893
+ self.scene_ape = nn.Parameter(torch.zeros((1, self.scene_seq_len, self.dim)))
894
+ self.head_ape = nn.Parameter(torch.zeros((1, self.head_seq_len, self.dim)))
895
+ elif self.pos_encoding == "sinusoidal":
896
+ self.register_buffer("scene_pos_embed", positionalencoding2d(self.dim, self.scene_featmap_h, self.scene_featmap_w).squeeze(0).squeeze(0))
897
+ self.register_buffer("head_pos_embed", positionalencoding2d(self.dim, self.head_featmap_h, self.head_featmap_w).squeeze(0).squeeze(0))
898
+
899
+ if self.inout:
900
+ self.scene_inout_token = nn.Parameter(torch.zeros((1, 1, self.dim)))
901
+ self.head_inout_token = nn.Parameter(torch.zeros((1, 1, self.dim)))
902
+
903
+ if self.n_reg_tokens > 0:
904
+ self.scene_register_tokens = nn.Parameter(torch.zeros((1, self.n_reg_tokens, self.dim)))
905
+ self.head_register_tokens = nn.Parameter(torch.zeros((1, self.n_reg_tokens, self.dim)))
906
+
907
+ if cfg.mlp_layer == "mlp":
908
+ mlp_layer = Mlp; act_layer = nn.GELU
909
+ elif cfg.mlp_layer == "geglu":
910
+ mlp_layer = SwiGLU; act_layer = nn.GELU
911
+ elif cfg.mlp_layer == "swiglu":
912
+ mlp_layer = SwiGLU; act_layer = nn.SiLU
913
+ else:
914
+ raise ValueError(f"mlp_layer must be mlp/geglu/swiglu, got {cfg.mlp_layer}")
915
+
916
+ self.scene_self_attn_layers = nn.Sequential(*[
917
+ get_vit_block(dim=self.dim, num_heads=cfg.num_heads, mlp_ratio=cfg.mlp_ratio, mlp_layer=mlp_layer,
918
+ drop_path=cfg.drop_path, act_layer=act_layer, num_front_tokens=self.n_front_tokens, pos_encoding=cfg.pos_encoding)
919
+ for _ in range(cfg.n_scene_self_attn_layers)
920
+ ]) if cfg.n_scene_self_attn_layers > 0 else nn.Identity()
921
+ self.head_self_attn_layers = nn.Sequential(*[
922
+ get_vit_block(dim=self.dim, num_heads=cfg.num_heads, mlp_ratio=cfg.mlp_ratio, mlp_layer=mlp_layer,
923
+ drop_path=cfg.drop_path, act_layer=act_layer, num_front_tokens=self.n_front_tokens, pos_encoding=cfg.pos_encoding)
924
+ for _ in range(cfg.n_head_self_attn_layers)
925
+ ]) if cfg.n_head_self_attn_layers > 0 else nn.Identity()
926
+ self.scene_head_interaction_layers = nn.Sequential(*[
927
+ SceneHeadInteraction(dim=self.dim, num_heads=cfg.num_heads, mlp_ratio=cfg.mlp_ratio, mlp_layer=mlp_layer,
928
+ drop_path=cfg.drop_path, act_layer=act_layer, pos_encoding=cfg.pos_encoding, num_front_tokens=self.n_front_tokens)
929
+ for _ in range(cfg.n_scene_head_interaction_layers)
930
+ ])
931
+
932
+ self.heatmap_head = nn.Sequential(
933
+ nn.ConvTranspose2d(self.dim, self.dim, kernel_size=2, stride=2),
934
+ nn.Conv2d(self.dim, 1, kernel_size=1, bias=False),
935
+ )
936
+ if self.inout:
937
+ self.inout_head = nn.Sequential(
938
+ nn.Linear(self.dim * 2, 128),
939
+ nn.GELU(),
940
+ nn.Dropout(0.1),
941
+ nn.Linear(128, 1),
942
+ )
943
+
944
+ self.post_init()
945
+
946
+ # ------------------------------------------------------------------ #
947
+ def get_input_head_maps(self, bboxes):
948
+ head_maps = []
949
+ head_rects = []
950
+ for bbox_list in bboxes:
951
+ img_head_maps = []
952
+ img_head_rects = []
953
+ for bbox in bbox_list:
954
+ if bbox is None:
955
+ img_head_maps.append(torch.zeros(self.scene_featmap_h, self.scene_featmap_w))
956
+ else:
957
+ xmin, ymin, xmax, ymax = bbox
958
+ width, height = self.scene_featmap_w, self.scene_featmap_h
959
+ xmin = round(xmin * width); ymin = round(ymin * height)
960
+ xmax = round(xmax * width); ymax = round(ymax * height)
961
+ head_map = torch.zeros((height, width))
962
+ head_map[ymin:ymax, xmin:xmax] = 1
963
+ img_head_maps.append(head_map)
964
+ img_head_rects.append(torch.Tensor([ymin, xmin, ymax, xmax]))
965
+ head_maps.append(torch.stack(img_head_maps))
966
+ head_rects.append(torch.stack(img_head_rects))
967
+ return head_maps, head_rects
968
+
969
+ def get_logits(self, input, return_tokens=False):
970
+ num_ppl_per_img = [len(bbox_list) for bbox_list in input["bboxes"]]
971
+ for head_stream_images in input["head_images"]:
972
+ if sum(num_ppl_per_img) != len(head_stream_images):
973
+ raise ValueError(f"bboxes and head crops mismatch: {sum(num_ppl_per_img)} bboxes vs {len(head_stream_images)} head crops.")
974
+
975
+ scene_featmap = self.scene_branch_backbone(input["images"])
976
+ scene_featmap = self.scene_proj(scene_featmap)
977
+ scene_dino_tokens = scene_featmap.flatten(start_dim=2).permute(0, 2, 1)
978
+ if self.pos_encoding == "sinusoidal":
979
+ scene_featmap = scene_featmap + self.scene_pos_embed
980
+ scene_featmap = repeat_tensors(scene_featmap, num_ppl_per_img)
981
+
982
+ head_featmap = self.head_branch_backbone(input["head_images"])
983
+ head_featmap = self.head_proj(head_featmap)
984
+ head_dino_tokens = head_featmap.flatten(start_dim=2).permute(0, 2, 1)
985
+ if self.pos_encoding == "sinusoidal":
986
+ head_featmap = head_featmap + self.head_pos_embed
987
+
988
+ head_maps, head_rects = self.get_input_head_maps(input["bboxes"])
989
+ head_maps = torch.cat(head_maps, dim=0).to(scene_featmap.device)
990
+ head_rects = torch.cat(head_rects, dim=0).to(scene_featmap.device)
991
+ if self.use_head_prompt:
992
+ head_map_embeddings = head_maps.unsqueeze(dim=1) * self.head_position_token.weight.unsqueeze(-1).unsqueeze(-1)
993
+ scene_featmap = scene_featmap + head_map_embeddings
994
+
995
+ scene_tokens = scene_featmap.flatten(start_dim=2).permute(0, 2, 1)
996
+ head_tokens = head_featmap.flatten(start_dim=2).permute(0, 2, 1)
997
+
998
+ if self.n_reg_tokens > 0:
999
+ scene_tokens = torch.cat([self.scene_register_tokens.expand(sum(num_ppl_per_img), -1, -1), scene_tokens], dim=1)
1000
+ head_tokens = torch.cat([self.head_register_tokens.expand(sum(num_ppl_per_img), -1, -1), head_tokens], dim=1)
1001
+ if self.inout:
1002
+ scene_tokens = torch.cat([self.scene_inout_token.expand(sum(num_ppl_per_img), -1, -1), scene_tokens], dim=1)
1003
+ head_tokens = torch.cat([self.head_inout_token.expand(sum(num_ppl_per_img), -1, -1), head_tokens], dim=1)
1004
+ if self.pos_encoding == "ape":
1005
+ scene_tokens = scene_tokens + self.scene_ape.expand(sum(num_ppl_per_img), -1, -1)
1006
+ head_tokens = head_tokens + self.head_ape.expand(sum(num_ppl_per_img), -1, -1)
1007
+
1008
+ scene_tokens = self.scene_self_attn_layers(scene_tokens)
1009
+ head_tokens = self.head_self_attn_layers(head_tokens)
1010
+ tokens = self.scene_head_interaction_layers({"scene_tokens": scene_tokens, "head_tokens": head_tokens, "head_rects": head_rects})
1011
+ scene_tokens = tokens["scene_tokens"][:, self.n_front_tokens:, :]
1012
+ scene_inout_token = tokens["scene_tokens"][:, 0, :]
1013
+ head_inout_token = tokens["head_tokens"][:, 0, :]
1014
+
1015
+ if self.inout:
1016
+ inout_features = torch.cat((scene_inout_token, head_inout_token), dim=1)
1017
+ inout_preds = self.inout_head(inout_features).squeeze(dim=-1)
1018
+ inout_preds = split_tensors(inout_preds, num_ppl_per_img)
1019
+
1020
+ scene_featmap = scene_tokens.reshape(scene_tokens.shape[0], self.scene_featmap_h, self.scene_featmap_w,
1021
+ scene_tokens.shape[2]).permute(0, 3, 1, 2)
1022
+ heatmap = self.heatmap_head(scene_featmap).squeeze(dim=1)
1023
+ heatmap = torchvision.transforms.functional.resize(heatmap, self.heatmap_out_size)
1024
+ heatmap_preds = split_tensors(heatmap, num_ppl_per_img)
1025
+
1026
+ if return_tokens:
1027
+ return {"scene_tokens": tokens["scene_tokens"], "head_tokens": tokens["head_tokens"],
1028
+ "scene_dino_tokens": scene_dino_tokens, "head_dino_tokens": head_dino_tokens,
1029
+ "heatmap": heatmap_preds, "inout": inout_preds if self.inout else None}
1030
+ return {"heatmap": heatmap_preds, "inout": inout_preds if self.inout else None}
1031
+
1032
+ def forward(self, input):
1033
+ """Inference forward (applies sigmoid). Do NOT use for training (numerical stability)."""
1034
+ logits = self.get_logits(input)
1035
+ heatmap_preds = [torch.sigmoid(h) for h in logits["heatmap"]]
1036
+ inout_preds = [torch.sigmoid(i) for i in logits["inout"]] if logits["inout"] is not None else None
1037
+ return {"heatmap": heatmap_preds, "inout": inout_preds if self.inout else None}
1038
+
1039
+
1040
+ # =========================================================================== #
1041
+ # Image processor (dual-stream: scene + per-person head crops) #
1042
+ # =========================================================================== #
1043
+ class PaGEImageProcessor(BaseImageProcessor):
1044
+ """
1045
+ Produces the input dict expected by PaGEModel.forward from a scene image + head crops.
1046
+
1047
+ Convenience:
1048
+ proc = AutoImageProcessor.from_pretrained(repo, trust_remote_code=True)
1049
+ inputs = proc(scene_pil, head_crops=[pil0, pil1, ...], bboxes=[[(xmin,ymin,xmax,ymax), ...]])
1050
+ out = model(inputs)
1051
+ """
1052
+
1053
+ model_input_names = ["pixel_values"]
1054
+
1055
+ def __init__(self, scene_size=(512, 512), head_size=(256, 256),
1056
+ image_mean=(0.485, 0.456, 0.406), image_std=(0.229, 0.224, 0.225),
1057
+ resample=2, **kwargs):
1058
+ super().__init__(**kwargs)
1059
+ self.scene_size = tuple(scene_size)
1060
+ self.head_size = tuple(head_size)
1061
+ self.image_mean = tuple(image_mean)
1062
+ self.image_std = tuple(image_std)
1063
+ self.resample = resample
1064
+
1065
+ @classmethod
1066
+ def from_dict(cls, image_processor_dict, **kwargs):
1067
+ return cls(**{**image_processor_dict, **kwargs})
1068
+
1069
+ def _to_tensor(self, pil_img, size):
1070
+ import numpy as np
1071
+ from PIL import Image
1072
+ if not isinstance(pil_img, Image.Image):
1073
+ pil_img = to_pil_image(pil_img)
1074
+ pil_img = pil_img.convert("RGB").resize((size[1], size[0]), self.resample) # PIL resize is (W, H)
1075
+ arr = np.asarray(pil_img, dtype=np.float32) / 255.0 # H, W, 3
1076
+ arr = (arr - np.array(self.image_mean, dtype=np.float32)) / np.array(self.image_std, dtype=np.float32)
1077
+ arr = np.transpose(arr, (2, 0, 1)) # 3, H, W
1078
+ return torch.from_numpy(arr)
1079
+
1080
+ def preprocess(self, scene_image, head_crops=None, bboxes=None, **kwargs):
1081
+ """
1082
+ scene_image: PIL image (or tensor) of the full scene.
1083
+ head_crops: list of PIL images, one per person (length == total bboxes across scene).
1084
+ Pass [None] * Np if you only have bboxes (zero head maps); but a real crop is expected.
1085
+ bboxes: list of bbox lists, one per scene image. Each bbox: (xmin, ymin, xmax, ymax) in [0,1].
1086
+ Returns: dict with "images", "head_images", "bboxes" ready for PaGEModel.forward.
1087
+ """
1088
+ if bboxes is None:
1089
+ raise ValueError("bboxes is required.")
1090
+ scene_tensor = self._to_tensor(scene_image, self.scene_size).unsqueeze(0) # 1, 3, H, W
1091
+ head_tensors = [self._to_tensor(hc, self.head_size) for hc in (head_crops or [])]
1092
+ if head_tensors:
1093
+ head_batch = torch.stack(head_tensors, dim=0)
1094
+ else:
1095
+ head_batch = torch.zeros(0, 3, *self.head_size)
1096
+ return {"images": scene_tensor, "head_images": [head_batch], "bboxes": bboxes}