File size: 18,953 Bytes
b7e49b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# SPDX-License-Identifier: Apache-2.0
"""Clean-room PyTorch reference of Depth Pro 2 (S, B, L, H+) and its shared focal-length (FOV) estimator.

Written from the official code (apple-aiml-research/ml-depth-pro-2 @ aa389cbb) and timm's DINOv3 ``Eva``, with no
dependency on either: it reads the Hugging Face ``model.safetensors`` of apple/DepthPro2-{S,B,L,H,focal} directly.
It is the in-bundle accuracy reference (tests compare the device path with it) and the definition of every stage the
device port splits the network into:

* ``preprocess``: uint8 RGB -> ImageNet-normalized, replicate-padded to a multiple of 32.
* ``embed``: 16x16 patch embedding + class token + 4 register tokens.
* ``blocks``: the DINOv3 transformer. A *within-frame* block attends over each frame's own tokens. A *cross-frame*
  block (``CFG.cross_frame_blocks``) runs once over the class/register tokens averaged over the frames followed by the
  patch tokens of ALL frames, and keeps each frame's class/register tokens unchanged.
* ``reassemble`` + ``decoder`` + ``head``: per frame, the DPT pyramid (1/4, 1/8, 1/16, 1/32) -> inverse depth at 1/1.
* ``fov``: a DINOv3 ViT-S trunk at <= 512 px on the short side plus an attention head -> (hfov, vfov) per frame.

Depth in meters is ``f_px / (width * inverse_depth)``.
"""

from __future__ import annotations

import json
import math
import os
from dataclasses import dataclass
from typing import Dict, List, Optional, Sequence, Tuple

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

IMAGENET_MEAN = (0.485, 0.456, 0.406)
IMAGENET_STD = (0.229, 0.224, 0.225)
INPUT_MULTIPLE = 32
PATCH = 16
NUM_PREFIX = 5  # class token + 4 register tokens
HEAD_DIM = 64
ROPE_TEMPERATURE = 100.0
LN_EPS = 1e-5


@dataclass(frozen=True)
class SizeConfig:
    name: str
    dim: int
    depth: int
    heads: int
    mlp_hidden: int
    swiglu: bool
    reassembled_blocks: Tuple[int, int, int, int]
    cross_frame_blocks: Tuple[int, ...]
    dims_reassemble: Tuple[int, int, int, int]
    dim_decoder: int
    params_m: int


#: The four released sizes (official ``PRESETS`` + timm DINOv3 presets). H+ uses a SwiGLU MLP (SiLU gate, hidden 5120).
SIZES: Dict[str, SizeConfig] = {
    "S": SizeConfig("S", 384, 12, 6, 1536, False, (2, 5, 8, 11), (5, 7, 9, 11), (48, 96, 192, 384), 64, 24),
    "B": SizeConfig("B", 768, 12, 12, 3072, False, (2, 5, 8, 11), (5, 7, 9, 11), (96, 192, 384, 768), 128, 97),
    "L": SizeConfig("L", 1024, 24, 16, 4096, False, (5, 11, 17, 23), (9, 11, 13, 15, 17, 19, 21, 23),
                    (256, 512, 1024, 1024), 256, 334),
    "H": SizeConfig("H", 1280, 32, 20, 5120, True, (7, 15, 23, 31), (11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31),
                    (256, 512, 1024, 1024), 256, 872),
}

#: FOV estimator: DINOv3 ViT-S/16 trunk (taps 2, 5, 8, 11 incl. prefix tokens) + 2-block attention head.
FOV_TRUNK = SizeConfig("fov", 384, 12, 6, 1536, False, (2, 5, 8, 11), (5, 7, 9, 11), (0, 0, 0, 0), 0, 24)
FOV_HEAD_DIM = 248
FOV_HEAD_HEADS = 4
FOV_POOL = 2
FOV_MAX_SHORT = 512
FOV_MAX_ASPECT = 1.7778
FOV_MIN_DEG, FOV_MAX_DEG = 1.0, 179.0


def load_safetensors(path: str) -> Dict[str, torch.Tensor]:
    from safetensors.torch import load_file

    return {k: v.float() for k, v in load_file(path).items()}


def size_from_config_json(path: str) -> str:
    with open(path) as f:
        preset = json.load(f)["backbone_preset"]
    for key, tag in (("S", "small"), ("B", "base"), ("L", "large"), ("H", "huge_plus")):
        if f"vit_{tag}_patch16_dinov3" in preset:
            return key
    raise ValueError(f"unknown backbone_preset {preset!r}")


# ----------------------------------------------------------------------------------------------- input / geometry


def padded_hw(height: int, width: int) -> Tuple[int, int]:
    return height + (-height % INPUT_MULTIPLE), width + (-width % INPUT_MULTIPLE)


def preprocess(frames_u8: np.ndarray) -> torch.Tensor:
    """uint8 RGB ``(H, W, 3)`` or ``(T, H, W, 3)`` -> normalized float32 ``(T, 3, H, W)`` (not padded)."""
    if frames_u8.ndim == 3:
        frames_u8 = frames_u8[None]
    if frames_u8.dtype != np.uint8 or frames_u8.shape[-1] != 3:
        raise TypeError(f"expected uint8 (T, H, W, 3), got {frames_u8.dtype} {frames_u8.shape}")
    x = torch.from_numpy(np.ascontiguousarray(frames_u8)).permute(0, 3, 1, 2).float().div_(255.0)
    mean = torch.tensor(IMAGENET_MEAN).view(1, 3, 1, 1)
    std = torch.tensor(IMAGENET_STD).view(1, 3, 1, 1)
    return (x - mean) / std


def pad_to_multiple(x: torch.Tensor) -> torch.Tensor:
    h, w = x.shape[-2:]
    ph, pw = -h % INPUT_MULTIPLE, -w % INPUT_MULTIPLE
    return F.pad(x, (0, pw, 0, ph), mode="replicate") if (ph or pw) else x


def rope_table(gh: int, gw: int, head_dim: int = HEAD_DIM) -> Tuple[torch.Tensor, torch.Tensor]:
    """DINOv3 RoPE (timm ``RotaryEmbeddingDinoV3``, normalize_coords='max', rotate-half layout): sin, cos ``(gh*gw, D)``."""
    q = head_dim // 4
    periods = ROPE_TEMPERATURE ** (2.0 * torch.arange(q, dtype=torch.float32) / (head_dim // 2))
    denom = float(max(gh, gw))
    ys = torch.arange(0.5, gh, dtype=torch.float32) / denom
    xs = torch.arange(0.5, gw, dtype=torch.float32) / denom
    grid = torch.stack(torch.meshgrid(ys, xs, indexing="ij"), dim=-1)
    coords = (2.0 * grid - 1.0).reshape(-1, 2)  # (HW, 2): (y, x)
    angles = (2 * math.pi * coords[:, :, None] / periods[None, None, :]).flatten(1)  # (HW, D/2): y freqs, x freqs
    sin, cos = angles.sin(), angles.cos()
    return torch.cat([sin, sin], -1), torch.cat([cos, cos], -1)


def apply_rope(x: torch.Tensor, sin: torch.Tensor, cos: torch.Tensor) -> torch.Tensor:
    x1, x2 = x.chunk(2, dim=-1)
    return x * cos + torch.cat([-x2, x1], dim=-1) * sin


# ----------------------------------------------------------------------------------------------- transformer


def layer_norm(x: torch.Tensor, w: Dict[str, torch.Tensor], prefix: str) -> torch.Tensor:
    return F.layer_norm(x, (x.shape[-1],), w[prefix + ".weight"], w[prefix + ".bias"], LN_EPS)


def block_qkv(x: torch.Tensor, w: Dict[str, torch.Tensor], p: str, heads: int,
              rope: Optional[Tuple[torch.Tensor, torch.Tensor]], num_prefix: int):
    """norm1 -> qkv (no bias) -> heads; RoPE on the tokens after ``num_prefix``. ``x``: (B, L, C) -> 3 x (B, h, L, d)."""
    b, n, _ = x.shape
    y = layer_norm(x, w, p + ".norm1")
    qkv = F.linear(y, w[p + ".attn.qkv.weight"], w.get(p + ".attn.qkv.bias"))
    q, k, v = qkv.reshape(b, n, 3, heads, -1).permute(2, 0, 3, 1, 4).unbind(0)
    if rope is not None:
        sin, cos = rope
        q = torch.cat([q[:, :, :num_prefix], apply_rope(q[:, :, num_prefix:], sin, cos)], dim=2)
        k = torch.cat([k[:, :, :num_prefix], apply_rope(k[:, :, num_prefix:], sin, cos)], dim=2)
    return q, k, v


def mlp(x: torch.Tensor, w: Dict[str, torch.Tensor], p: str, swiglu: bool) -> torch.Tensor:
    if swiglu:
        g = F.linear(x, w[p + ".mlp.fc1_g.weight"], w[p + ".mlp.fc1_g.bias"])
        u = F.linear(x, w[p + ".mlp.fc1_x.weight"], w[p + ".mlp.fc1_x.bias"])
        h = F.silu(g) * u
    else:
        h = F.gelu(F.linear(x, w[p + ".mlp.fc1.weight"], w[p + ".mlp.fc1.bias"]))
    return F.linear(h, w[p + ".mlp.fc2.weight"], w[p + ".mlp.fc2.bias"])


def block_finish(x: torch.Tensor, attended: torch.Tensor, w: Dict[str, torch.Tensor], p: str, swiglu: bool):
    """attention (B, h, L, d) -> proj -> gamma_1 residual -> norm2 -> MLP -> gamma_2 residual."""
    merged = attended.transpose(1, 2).reshape(x.shape[0], x.shape[1], -1)
    x = x + w[p + ".gamma_1"] * F.linear(merged, w[p + ".attn.proj.weight"], w[p + ".attn.proj.bias"])
    return x + w[p + ".gamma_2"] * mlp(layer_norm(x, w, p + ".norm2"), w, p, swiglu)


def block(x: torch.Tensor, w, p: str, cfg: SizeConfig, rope, num_prefix: int = NUM_PREFIX) -> torch.Tensor:
    q, k, v = block_qkv(x, w, p, cfg.heads, rope, num_prefix)
    return block_finish(x, F.scaled_dot_product_attention(q, k, v), w, p, cfg.swiglu)


def cross_frame_block(tokens: torch.Tensor, w, p: str, cfg: SizeConfig, rope) -> torch.Tensor:
    """(T, P+N, C): one joint sequence [mean_t prefix ; patches of all frames]; prefix tokens are kept per frame."""
    t, _, c = tokens.shape
    prefix, patches = tokens[:, :NUM_PREFIX], tokens[:, NUM_PREFIX:]
    x = torch.cat([prefix.mean(dim=0, keepdim=True), patches.reshape(1, -1, c)], dim=1)
    sin, cos = rope
    y = block(x, w, p, cfg, (sin.repeat(t, 1), cos.repeat(t, 1)))
    return torch.cat([prefix, y[:, NUM_PREFIX:].reshape(t, -1, c)], dim=1)


def embed(x: torch.Tensor, w: Dict[str, torch.Tensor], pfx: str) -> torch.Tensor:
    """Padded frames (T, 3, H, W) -> tokens (T, 5 + gh*gw, C)."""
    tok = F.conv2d(x, w[pfx + "patch_embed.proj.weight"], w[pfx + "patch_embed.proj.bias"], stride=PATCH)
    tok = tok.flatten(2).transpose(1, 2)
    t = tok.shape[0]
    return torch.cat([w[pfx + "cls_token"].expand(t, -1, -1), w[pfx + "reg_token"].expand(t, -1, -1), tok], dim=1)


# ----------------------------------------------------------------------------------------------- DPT decoder


def conv(x, w, name, stride=1, padding=0, bias=True):
    return F.conv2d(x, w[name + ".weight"], w.get(name + ".bias") if bias else None, stride=stride, padding=padding)


def deconv(x, w, name, stride, bias=True):
    return F.conv_transpose2d(x, w[name + ".weight"], w.get(name + ".bias") if bias else None, stride=stride)


def reassemble(features: Sequence[torch.Tensor], grid: Tuple[int, int], w) -> List[torch.Tensor]:
    """Tapped patch tokens (T, N, C) x 4 -> pyramid at 1/4, 1/8, 1/16, 1/32."""
    out = []
    for i, f in enumerate(features):
        x = f.transpose(1, 2).reshape(f.shape[0], -1, *grid).contiguous()
        x = conv(x, w, f"encoder.reassemble.{i}.0")
        if i == 0:
            x = deconv(x, w, "encoder.reassemble.0.1", 4)
        elif i == 1:
            x = deconv(x, w, "encoder.reassemble.1.1", 2)
        elif i == 3:
            x = conv(x, w, "encoder.reassemble.3.1", stride=2, padding=1)
        out.append(x)
    return out


def residual(x, w, name):
    y = conv(F.relu(x), w, name + ".residual.1", padding=1)
    y = conv(F.relu(y), w, name + ".residual.3", padding=1)
    return x + y


def fusion(x, w, i: int, skip: Optional[torch.Tensor]):
    p = f"decoder.fusions.{i}"
    if skip is not None:
        x = x + residual(skip, w, p + ".resnet1")
    x = residual(x, w, p + ".resnet2")
    x = deconv(x, w, p + ".deconv", 2, bias=False)
    return conv(x, w, p + ".out_conv")


def decoder(pyramid: Sequence[torch.Tensor], w) -> torch.Tensor:
    x = fusion(conv(pyramid[3], w, "decoder.convs.3", padding=1, bias=False), w, 3, None)
    for i in (2, 1, 0):
        x = fusion(x, w, i, conv(pyramid[i], w, f"decoder.convs.{i}", padding=1, bias=False))
    return x


def head(x: torch.Tensor, w) -> torch.Tensor:
    x = conv(x, w, "head.0", padding=1)
    x = deconv(x, w, "head.1", 2)
    x = F.relu(conv(x, w, "head.2", padding=1))
    return F.relu(conv(x, w, "head.4"))


# ----------------------------------------------------------------------------------------------- model


class DepthPro2Reference:
    """Float32 CPU reference. ``w``: the size's safetensors; ``fov_w``: DepthPro2-focal's (optional)."""

    def __init__(self, size: str, w: Dict[str, torch.Tensor], fov_w: Optional[Dict[str, torch.Tensor]] = None):
        self.cfg = SIZES[size]
        self.w = w
        self.fov_w = fov_w

    @classmethod
    def from_dirs(cls, size_dir: str, fov_dir: Optional[str]) -> "DepthPro2Reference":
        size = size_from_config_json(os.path.join(size_dir, "config.json"))
        w = load_safetensors(os.path.join(size_dir, "model.safetensors"))
        fw = load_safetensors(os.path.join(fov_dir, "model.safetensors")) if fov_dir else None
        return cls(size, w, fw)

    # -- encoder
    def encode(self, x: torch.Tensor) -> Tuple[List[torch.Tensor], Tuple[int, int]]:
        """Padded frames (T, 3, H, W) -> 4 tapped patch-token tensors (T, N, C), grid (gh, gw)."""
        cfg, w = self.cfg, self.w
        grid = (x.shape[-2] // PATCH, x.shape[-1] // PATCH)
        rope = rope_table(*grid)
        tokens = embed(x, w, "encoder.")
        taps = []
        for i in range(cfg.depth):
            p = f"encoder.blocks.{i}"
            if i in cfg.cross_frame_blocks:
                tokens = cross_frame_block(tokens, w, p, cfg, rope)
            else:
                tokens = block(tokens, w, p, cfg, rope)
            if i in cfg.reassembled_blocks:
                taps.append(tokens[:, NUM_PREFIX:])
        return taps, grid

    def decode(self, taps: Sequence[torch.Tensor], grid: Tuple[int, int]) -> torch.Tensor:
        """Per frame: pyramid -> decoder -> head. Returns inverse depth (T, 1, Hp, Wp)."""
        outs = []
        for t in range(taps[0].shape[0]):
            pyr = reassemble([f[t:t + 1] for f in taps], grid, self.w)
            outs.append(head(decoder(pyr, self.w), self.w))
        return torch.cat(outs)

    def inverse_depth(self, x: torch.Tensor) -> torch.Tensor:
        """Normalized frames (T, 3, H, W) at native size -> inverse depth (T, H, W)."""
        h, w = x.shape[-2:]
        taps, grid = self.encode(pad_to_multiple(x))
        return self.decode(taps, grid)[:, 0, :h, :w]

    # -- FOV
    def fov_deg(self, x: torch.Tensor) -> torch.Tensor:
        if self.fov_w is None:
            raise RuntimeError("no focal (FOV) weights loaded")
        return fov_forward(x, self.fov_w)

    def focal_length_px(self, x: torch.Tensor) -> torch.Tensor:
        return median_focal_length_px(self.fov_deg(x), *x.shape[-2:])

    def infer(self, frames_u8: np.ndarray, f_px: Optional[float] = None) -> Dict[str, torch.Tensor]:
        """uint8 image (H, W, 3) or clip (T, H, W, 3): inverse depth, depth (m), focal length (px)."""
        x = preprocess(frames_u8)
        inv = self.inverse_depth(x)
        f = torch.tensor(float(f_px)) if f_px is not None else (
            self.focal_length_px(x) if self.fov_w is not None else None)
        out = {"inverse_depth": inv}
        if f is not None:
            out["focallength_px"] = f.reshape(())
            out["depth"] = f / (x.shape[-1] * inv)
        return out


# ----------------------------------------------------------------------------------------------- FOV estimator


def fov_input_size(height: int, width: int) -> Tuple[int, int]:
    short = max(32, min(FOV_MAX_SHORT, min(height, width) // 32 * 32))
    scale = short / min(height, width)
    return max(32, round(height * scale / 32) * 32), max(32, round(width * scale / 32) * 32)


def fov_resize(x: torch.Tensor) -> torch.Tensor:
    new_h, new_w = fov_input_size(*x.shape[-2:])
    x = F.interpolate(x, size=(new_h, new_w), mode="bilinear", antialias=True)
    lo, hi = min(new_h, new_w), max(new_h, new_w)
    if hi <= FOV_MAX_ASPECT * lo:
        return x
    keep = max(32, int(FOV_MAX_ASPECT * lo) // 32 * 32)
    off = (hi - keep) // 2
    return x[..., off:off + keep] if new_w > new_h else x[..., off:off + keep, :]


def sincos_2d(gh: int, gw: int, dim: int) -> torch.Tensor:
    g = max(gh, gw)
    ys = (torch.arange(gh) + 0.5 - gh / 2) / g
    xs = (torch.arange(gw) + 0.5 - gw / 2) / g
    yy, xx = torch.meshgrid(ys, xs, indexing="ij")
    freq = torch.pi * 2.0 ** torch.linspace(0.0, 7.0, dim // 4)
    return torch.cat([f(c.reshape(-1, 1) * freq) for c in (yy, xx) for f in (torch.sin, torch.cos)], dim=-1)


def fov_trunk(y: torch.Tensor, fw) -> Tuple[torch.Tensor, Tuple[int, int]]:
    """Resized frames -> concatenated taps (T, 5 + gh*gw, 4*384). Cross-frame blocks keep their input prefix."""
    cfg = FOV_TRUNK
    grid = (y.shape[-2] // PATCH, y.shape[-1] // PATCH)
    rope = rope_table(*grid)
    tokens = embed(y, fw, "trunk.")
    taps = []
    for i in range(cfg.depth):
        out = block(tokens, fw, f"trunk.blocks.{i}", cfg, rope)
        if i in cfg.cross_frame_blocks:
            out = torch.cat([tokens[:, :NUM_PREFIX], out[:, NUM_PREFIX:]], dim=1)
        tokens = out
        if i in cfg.reassembled_blocks:
            taps.append(tokens)
    return torch.cat(taps, dim=-1), grid


def fov_head(tokens: torch.Tensor, grid: Tuple[int, int], fw) -> torch.Tensor:
    t = tokens.shape[0]
    gh, gw = grid
    taps = tokens.split(FOV_TRUNK.dim, dim=-1)
    x = torch.cat([layer_norm(tp, fw, f"head.tap_norms.{i}") for i, tp in enumerate(taps)], dim=-1)
    x = F.linear(x, fw["head.proj.weight"], fw["head.proj.bias"])
    prefix, x = x[:, :NUM_PREFIX], x[:, NUM_PREFIX:]
    x = x.transpose(1, 2).reshape(t, FOV_HEAD_DIM, gh, gw)
    x = F.avg_pool2d(x, FOV_POOL, ceil_mode=True)
    x = x.flatten(2).transpose(1, 2) + sincos_2d(*x.shape[-2:], FOV_HEAD_DIM)
    x = torch.cat([fw["head.query"].expand(t, -1, -1), prefix + fw["head.prefix_embed"], x], dim=1)
    hc = SizeConfig("fovhead", FOV_HEAD_DIM, 2, FOV_HEAD_HEADS, 4 * FOV_HEAD_DIM, False, (), (), (0, 0, 0, 0), 0, 0)
    for i in range(2):
        p = f"head.blocks.{i}"
        x = block_head(x, fw, p, hc)
    return F.linear(layer_norm(x[:, 0], fw, "head.norm"), fw["head.out.weight"], fw["head.out.bias"])


def block_head(x, w, p, cfg: SizeConfig):
    """timm ``vision_transformer.Block`` (qkv bias, no layer scale, GELU MLP)."""
    q, k, v = block_qkv(x, w, p, cfg.heads, None, 0)
    a = F.scaled_dot_product_attention(q, k, v).transpose(1, 2).reshape(x.shape)
    x = x + F.linear(a, w[p + ".attn.proj.weight"], w[p + ".attn.proj.bias"])
    return x + mlp(layer_norm(x, w, p + ".norm2"), w, p, False)


def crop_angles_to_full(angles: torch.Tensor, crop_hw, full_hw) -> torch.Tensor:
    (ch, cw), (h, w) = crop_hw, full_hw
    a = torch.deg2rad(angles.float())
    fx = (cw / 2) / torch.tan(a[..., 0] / 2)
    fy = (ch / 2) / torch.tan(a[..., 1] / 2)
    return torch.rad2deg(torch.stack([2 * torch.atan((w / 2) / fx), 2 * torch.atan((h / 2) / fy)], dim=-1))


def fov_forward(x: torch.Tensor, fw) -> torch.Tensor:
    """Normalized frames (T, 3, H, W) at native size -> (T, 2) horizontal / vertical FoV in degrees."""
    height, width = x.shape[-2:]
    y = fov_resize(x)
    tokens, grid = fov_trunk(y, fw)
    logits = fov_head(tokens, grid, fw)
    return fov_logits_to_deg(logits, (height, width), tuple(y.shape[-2:]))


def fov_logits_to_deg(logits: torch.Tensor, full_hw, crop_hw) -> torch.Tensor:
    height, width = full_hw
    fov = FOV_MIN_DEG + torch.sigmoid(logits) * (FOV_MAX_DEG - FOV_MIN_DEG)
    fh, fwid = fov_input_size(height, width)
    if tuple(crop_hw) == (fh, fwid):
        return fov
    return crop_angles_to_full(fov, (crop_hw[0] * height / fh, crop_hw[1] * width / fwid), (height, width))


def median_focal_length_px(fov_deg: torch.Tensor, height: int, width: int) -> torch.Tensor:
    hfov, vfov = fov_deg.median(dim=0).values
    if width < height:
        return 0.5 * width / torch.tan(torch.deg2rad(hfov) / 2.0)
    return 0.5 * height / torch.tan(torch.deg2rad(vfov) / 2.0)