Use ViT-Up 0.3: fast image encoder, ft_grid_size, inputs up to 896 px
Browse filesVendors vit_up 0.3.0 (folded query patch embedding, cached cross-attention keys/values). Released configs are translated (image_size -> ft_grid_size, query_embd_grid_size). ViT-Up now encodes the padded image at up to 896 px, its training resolution; the backbone runs on the checkpoint's grid as before.
Files changed (7)
- README.md+5-3
- app.py+19-6
- vit_up/__init__.py+1
- vit_up/model/backbones.py+4-2
- vit_up/model/layers.py+25-10
- vit_up/model/query_encoder.pyAdded+192
- vit_up/model/vit_up.py+42-23
18 unmodified lines19202122232425262718 unmodified lines## How it works1. **Input**: The image is zero-padded to a square, resized to the model's backboneresolution (448×448, or 896×896 for the model trained at 448 + 896 px), andnormalized with ImageNet statistics.2. **Backbone**: DINOv3-S+, DINOv3-B (weights from the non-gated timm mirrors) orDINOv2-S, with the LoRA adapters of the selected ViT-Up checkpoint merged in.3. **Upsampling**: The selected ViT-Up checkpoint queries features on a dense grid of18 unmodified lines192021222324252627282918 unmodified lines## How it works1. **Input**: The image is zero-padded to a square, normalized with ImageNet statistics,and downscaled to at most 896×896 (ViT-Up's training resolution). The backbone sees itat 448×448 (a 28×28 token grid; 896×896 and 56×56 for the model trained at 448 + 896 px).ViT-Up's query encoder computes the patch embeddings of the 3584×3584 upsampled imagedirectly from the input, without building it (ViT-Up 0.3).2. **Backbone**: DINOv3-S+, DINOv3-B (weights from the non-gated timm mirrors) orDINOv2-S, with the LoRA adapters of the selected ViT-Up checkpoint merged in.3. **Upsampling**: The selected ViT-Up checkpoint queries features on a dense grid of
48 unmodified lines49505152535432 unmodified lines878889909192933 unmodified lines97989910010110210310410561 unmodified lines1671681691701711721731741752 unmodified lines1781791801811821831842 unmodified lines18718818919019119219348 unmodified linesDEVICE = "cuda"QUERY_CHUNK_SIZE = 16384PCA_GRIDS = (14, 28, 56)def timm_to_backbone(state: dict, num_layers: int) -> dict:32 unmodified linesdef load_model(checkpoint: str):"""Return (vit_up, backbone with merged LoRA, backbone input resolution, backbone name) of a release."""directory = Path(snapshot_download("Krispin/vit-up", allow_patterns=f"{checkpoint}/*")) / checkpointconfig = yaml.safe_load((directory / "config.yaml").read_text())weights = load_file(directory / "model.safetensors")3 unmodified linesload_lora_state_dict(backbone, {k.removeprefix("backbone."): v for k, v in weights.items()if k.startswith("backbone.")})backbone = backbone.merge_and_unload(safe_merge=True)vit_up = ViTUp(**{k: v for k, v in config["vit_up"].items() if k != "_target_"})vit_up.load_state_dict({k.removeprefix("vit_up."): v for k, v in weights.items() if k.startswith("vit_up.")})return vit_up.to(DEVICE).eval(), backbone.to(DEVICE).eval(), config["image_size"], config["backbone"]print("Loading ViT-Up checkpoints...")61 unmodified linesreturn None, None, "Please provide an input image."size = int(output_resolution)image = image.convert("RGB")vit_up, backbone, image_size, backbone_name = MODELS[checkpoint]original = ORIGINAL_BACKBONES[backbone_name]square = T.functional.to_image(pad_to_square(image))def pixels(side):return NORMALIZE(T.functional.resize(square, [side, side], antialias=True)).unsqueeze(0).to(DEVICE)2 unmodified lineswith torch.autocast("cuda", dtype=torch.bfloat16):reference = [original.hidden_states(pixels(grid * original.patch_size))[-1][0] for grid in PCA_GRIDS]backbone_features = original.hidden_states(pixels(image_size))[-1][0]cache = vit_up.encode(pixels(image_size), backbone, image_size)features = torch.cat([vit_up(chunk, cache)[-1] for chunk in queries.split(QUERY_CHUNK_SIZE, dim=1)], dim=1)features = features[0].reshape(size, size, -1)pca = PCA(torch.cat([grid.flatten(0, 1) for grid in reference]))2 unmodified linesvit_up_image = crop_to_aspect(pca.image(features), *image.size)backbone_image = pca.image(backbone_features).resize((size, size), Image.Resampling.NEAREST)backbone_image = crop_to_aspect(backbone_image, *image.size)info = (f"Model: {CHECKPOINTS[checkpoint]} | Backbone input: {image_size}x{image_size} ({grid}x{grid} tokens) | "f"Feature dim: {features.shape[-1]} | Output resolution: {size}x{size} | Queries: {size * size:,}")return vit_up_image, backbone_image, info48 unmodified lines49505152535455565732 unmodified lines909192939495963 unmodified lines10010110210310410510610710810911011111211361 unmodified lines1751761771781791801811821831841851861872 unmodified lines1901911921931941951962 unmodified lines19920020120220320420520648 unmodified linesDEVICE = "cuda"QUERY_CHUNK_SIZE = 16384PCA_GRIDS = (14, 28, 56)# ViT-Up was trained on 896 px images: larger inputs are downscaled to this before encoding (as ViTUpWrapper does).IMAGE_SIZE_MAX = 896LEGACY_QUERY_IMAGE_SIZE = 3584 # px; the query image of released configs without query_embd_grid_sizedef timm_to_backbone(state: dict, num_layers: int) -> dict:32 unmodified linesdef load_model(checkpoint: str):"""Return (vit_up, backbone with merged LoRA, backbone feature grid size, backbone name) of a release."""directory = Path(snapshot_download("Krispin/vit-up", allow_patterns=f"{checkpoint}/*")) / checkpointconfig = yaml.safe_load((directory / "config.yaml").read_text())weights = load_file(directory / "model.safetensors")3 unmodified linesload_lora_state_dict(backbone, {k.removeprefix("backbone."): v for k, v in weights.items()if k.startswith("backbone.")})backbone = backbone.merge_and_unload(safe_merge=True)# Released configs give the backbone input in px (image_size) and imply a 3584 px query image# (as vit_up.checkpoint.upgrade_config translates them).ft_grid_size = config.get("ft_grid_size") or config["image_size"] // backbone.patch_sizevit_up_config = {k: v for k, v in config["vit_up"].items() if k != "_target_"}vit_up_config.setdefault("query_embd_grid_size", LEGACY_QUERY_IMAGE_SIZE // backbone.patch_size)vit_up = ViTUp(**vit_up_config)vit_up.load_state_dict({k.removeprefix("vit_up."): v for k, v in weights.items() if k.startswith("vit_up.")})return vit_up.to(DEVICE).eval(), backbone.to(DEVICE).eval(), ft_grid_size, config["backbone"]print("Loading ViT-Up checkpoints...")61 unmodified linesreturn None, None, "Please provide an input image."size = int(output_resolution)image = image.convert("RGB")vit_up, backbone, ft_grid_size, backbone_name = MODELS[checkpoint]original = ORIGINAL_BACKBONES[backbone_name]square = T.functional.to_image(pad_to_square(image))image_size = ft_grid_size * backbone.patch_size # backbone input resolution# ViT-Up encodes the image at its own resolution, at most IMAGE_SIZE_MAX (never below the backbone's);# its query encoder computes the patch embeddings of the 3584 px query image directly from it.input_size = min(square.shape[-1], max(IMAGE_SIZE_MAX, image_size))def pixels(side):return NORMALIZE(T.functional.resize(square, [side, side], antialias=True)).unsqueeze(0).to(DEVICE)2 unmodified lineswith torch.autocast("cuda", dtype=torch.bfloat16):reference = [original.hidden_states(pixels(grid * original.patch_size))[-1][0] for grid in PCA_GRIDS]backbone_features = original.hidden_states(pixels(image_size))[-1][0]cache = vit_up.encode(pixels(input_size), backbone, ft_grid_size)features = torch.cat([vit_up(chunk, cache)[-1] for chunk in queries.split(QUERY_CHUNK_SIZE, dim=1)], dim=1)features = features[0].reshape(size, size, -1)pca = PCA(torch.cat([grid.flatten(0, 1) for grid in reference]))2 unmodified linesvit_up_image = crop_to_aspect(pca.image(features), *image.size)backbone_image = pca.image(backbone_features).resize((size, size), Image.Resampling.NEAREST)backbone_image = crop_to_aspect(backbone_image, *image.size)info = (f"Model: {CHECKPOINTS[checkpoint]} | ViT-Up input: {input_size}x{input_size} | "f"Backbone input: {image_size}x{image_size} ({grid}x{grid} tokens) | "f"Feature dim: {features.shape[-1]} | Output resolution: {size}x{size} | Queries: {size * size:,}")return vit_up_image, backbone_image, info
1__version__ = "0.3.0"
24 unmodified lines25262728293031323324 unmodified lines"""Patch embeddings before position encoding, as a (B, H, W, C) map."""raise NotImplementedErrordef hidden_states(self, pixel_values: torch.Tensor, image_size: int | None = None,return_class_token: bool = False):"""Resize to `image_size` and run the backbone, autocasting for low-precision inputs."""if image_size is not None and tuple(pixel_values.shape[-2:]) != (image_size, image_size):pixel_values = F.interpolate(pixel_values, size=(image_size, image_size), mode="bilinear",align_corners=False)24 unmodified lines252627282930313233343524 unmodified lines"""Patch embeddings before position encoding, as a (B, H, W, C) map."""raise NotImplementedErrordef hidden_states(self, pixel_values: torch.Tensor, ft_grid_size: int | None = None,return_class_token: bool = False):"""Run the backbone on an ft_grid_size x ft_grid_size token grid (resizing the input toft_grid_size * patch_size px; None keeps its size), autocasting for low-precision inputs."""image_size = None if ft_grid_size is None else ft_grid_size * self.patch_sizeif image_size is not None and tuple(pixel_values.shape[-2:]) != (image_size, image_size):pixel_values = F.interpolate(pixel_values, size=(image_size, image_size), mode="bilinear",align_corners=False)
84 unmodified lines858687888990919293949596979813 unmodified lines11211311411511611711811912012184 unmodified linesangles = angles.repeat_interleave(2, dim=-1).flatten(-2)return angles.cos(), angles.sin()def forward(self, q_xy: torch.Tensor, h_tokens: int, w_tokens: int):"""Return (q_cos, q_sin, k_cos, k_sin) for normalized query coordinates."""q_cos, q_sin = self._cos_sin(q_xy * q_xy.new_tensor([w_tokens, h_tokens]))ys = torch.arange(h_tokens, device=q_xy.device, dtype=q_xy.dtype) + 0.5xs = torch.arange(w_tokens, device=q_xy.device, dtype=q_xy.dtype) + 0.5grid = torch.stack(torch.meshgrid(xs, ys, indexing="xy"), dim=-1).reshape(1, -1, 2)k_cos, k_sin = self._cos_sin(grid)return q_cos, q_sin, k_cos, k_sinclass CrossAttention(nn.Module):13 unmodified linesdef _heads(self, x: torch.Tensor) -> torch.Tensor:return x.unflatten(-1, (self.num_heads, self.head_dim)).transpose(1, 2)def forward(self, queries: torch.Tensor, tokens: torch.Tensor, rope) -> torch.Tensor:q, k, v = self._heads(self.q_proj(queries)), self._heads(self.k_proj(tokens)), self._heads(self.v_proj(tokens))q_cos, q_sin, k_cos, k_sin = (x[:, None] for x in rope)q = q * q_cos.to(q.dtype) + _rotate_pairs(q) * q_sin.to(q.dtype)k = k * k_cos.to(k.dtype) + _rotate_pairs(k) * k_sin.to(k.dtype)out = F.scaled_dot_product_attention(q, k, v)return self.out_proj(out.transpose(1, 2).flatten(2))84 unmodified lines85868788899091929394959697989910010110210310413 unmodified lines11811912012112212312412512612712812913013113213313413513684 unmodified linesangles = angles.repeat_interleave(2, dim=-1).flatten(-2)return angles.cos(), angles.sin()def queries(self, q_xy: torch.Tensor, h_tokens: int, w_tokens: int):"""(cos, sin) for normalized query coordinates (B, N, 2)."""return self._cos_sin(q_xy * q_xy.new_tensor([w_tokens, h_tokens]))def keys(self, h_tokens: int, w_tokens: int, device=None, dtype=torch.float32):"""(cos, sin) for the centers of an h_tokens x w_tokens token grid, (1, h * w, dim) each."""ys = torch.arange(h_tokens, device=device, dtype=dtype) + 0.5xs = torch.arange(w_tokens, device=device, dtype=dtype) + 0.5grid = torch.stack(torch.meshgrid(xs, ys, indexing="xy"), dim=-1).reshape(1, -1, 2)return self._cos_sin(grid)def forward(self, q_xy: torch.Tensor, h_tokens: int, w_tokens: int):"""Return (q_cos, q_sin, k_cos, k_sin) for normalized query coordinates."""return (*self.queries(q_xy, h_tokens, w_tokens), *self.keys(h_tokens, w_tokens, q_xy.device, q_xy.dtype))class CrossAttention(nn.Module):13 unmodified linesdef _heads(self, x: torch.Tensor) -> torch.Tensor:return x.unflatten(-1, (self.num_heads, self.head_dim)).transpose(1, 2)def prepare(self, tokens: torch.Tensor, k_rope) -> tuple[torch.Tensor, torch.Tensor]:"""Rotated keys and values of the tokens, which depend only on the image."""k, v = self._heads(self.k_proj(tokens)), self._heads(self.v_proj(tokens))k_cos, k_sin = (x[:, None] for x in k_rope)return k * k_cos.to(k.dtype) + _rotate_pairs(k) * k_sin.to(k.dtype), vdef attend(self, queries: torch.Tensor, k: torch.Tensor, v: torch.Tensor, q_rope) -> torch.Tensor:q = self._heads(self.q_proj(queries))q_cos, q_sin = (x[:, None] for x in q_rope)q = q * q_cos.to(q.dtype) + _rotate_pairs(q) * q_sin.to(q.dtype)out = F.scaled_dot_product_attention(q, k, v)return self.out_proj(out.transpose(1, 2).flatten(2))def forward(self, queries: torch.Tensor, tokens: torch.Tensor, rope) -> torch.Tensor:"""rope: (q_cos, q_sin, k_cos, k_sin) from ContinuousRoPE2D."""return self.attend(queries, *self.prepare(tokens, rope[2:]), rope[:2])
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192"""ViT-Up's initial query features: the backbone's patch embeddings of the input image, bilinearlyupsampled to `grid_size * patch_size` pixels per side, sampled at the query coordinates.
Upsampling and patch embedding are both linear, and each upsampled patch depends on only a fewsource pixels per axis, so the composition is computed directly on the input image (`fold=True`)instead of building the large upsampled image (`fold=False`, e.g. 3584 x 3584 px).
Along one axis, with `patch_size * input_size / upsampled_size = p / q` in lowest terms, patchest and t + q read the same weights of source windows p pixels apart:
- Integer ratio on both axes (q = 1, e.g. 448 or 896 px input, 3584 px upsampled, 16 px patches): one strided convolution with the folded kernel (4x4 stride 2 for 448 px, 6x6 stride 4 for 896 px); replicate padding reproduces the upsampler's border clamping.- Otherwise (e.g. 480 x 640 px, or 14 px patches): the image is upsampled along y at the patch rows only (a few source rows per patch row), then each group of patch columns that share their weights (about q + 2 groups: the q phases and the borders) is one strided convolution along x with the patch weights folded in.
Both are exact up to fp32 rounding. The interpolation weights come from `F.interpolate` itself,and the effective patch kernel is read off the backbone by embedding one-hot patches, so LoRAadapters are included and gradients reach them. The fold runs in fp32."""import contextlibimport functoolsfrom fractions import Fraction
import torchimport torch.nn.functional as Ffrom torch import nn
@functools.lru_cache(maxsize=64)def _axis(in_size: int, up_size: int, patch: int, device: torch.device): """Interpolation geometry of one axis (float64 weights from F.interpolate).
Returns (start, weights, (p, q, groups), conv): start (T,) first source pixel of each patch's window, weights (T, patch, K); p / q: patch_size * in_size / up_size in lowest terms; groups: [(first patch, count, first window start, kernel (patch, K))], each a run of patches t, t + q, ... sharing a kernel, whose windows start p pixels apart; conv: (stride, pad_low, pad_high, kernel) if one kernel serves every patch under replicate padding (integer ratio), else None. """ if up_size % patch: raise ValueError(f"Upsampled size {up_size} is not a multiple of the patch size {patch}.") tokens = up_size // patch basis = torch.eye(in_size, dtype=torch.float64)[None] rows = F.interpolate(basis, size=up_size, mode="linear", align_corners=False)[0].T # (up, in) rows = rows.reshape(tokens, patch, in_size) support = rows.abs().sum(1) > 0 # (T, in) first = support.float().argmax(1) last = in_size - 1 - support.flip(1).float().argmax(1) width = int((last - first).max()) + 1 start = first.clamp(max=in_size - width) index = start[:, None] + torch.arange(width) weights = rows.gather(2, index[:, None].expand(-1, patch, -1)) # (T, P, K)
ratio = Fraction(patch * in_size, up_size) step, period = ratio.numerator, ratio.denominator groups = [] for phase in range(min(period, tokens)): members = range(phase, tokens, period) i = 0 while i < len(members): j = i + 1 while (j < len(members) and int(start[members[j]]) - int(start[members[i]]) == step * (j - i) and torch.allclose(weights[members[j]], weights[members[i]], rtol=0, atol=1e-12)): j += 1 groups.append((members[i], j - i, int(start[members[i]]), weights[members[i]].to(device))) i = j
conv = None if period == 1: middle = tokens // 2 kernel = weights[middle] pad_low = step * middle - int(start[middle]) pad_high = (tokens - 1) * step + width - in_size - pad_low if pad_low >= 0 and pad_high >= 0: # Expected rows of every patch under replicate padding; use the conv if they match. padded = (torch.arange(tokens)[:, None] * step + torch.arange(width) - pad_low).clamp(0, in_size - 1) expected = torch.zeros_like(rows).scatter_add_( 2, padded[:, None].expand(-1, patch, -1), kernel.expand(tokens, -1, -1).contiguous()) if torch.allclose(expected, rows, rtol=0, atol=1e-12): conv = (step, pad_low, pad_high, kernel.to(device)) return start.to(device), weights.to(device), (step, period, groups), conv
@contextlib.contextmanagerdef _ieee_convolutions(): """Full fp32 convolutions (TF32 would round the probed patch kernel by ~1e-3).""" cudnn = torch.backends.cudnn conv = getattr(cudnn, "conv", None) if conv is not None and hasattr(conv, "fp32_precision"): target, attribute, value = conv, "fp32_precision", "ieee" else: target, attribute, value = cudnn, "allow_tf32", False previous = getattr(target, attribute) setattr(target, attribute, value) try: yield finally: setattr(target, attribute, previous)
def _patch_kernel(backbone: nn.Module, channels: int) -> tuple[torch.Tensor, torch.Tensor]: """Effective (weight (C_out, C_in, P, P), bias (C_out,)) of backbone.embed_patches, read off by embedding one-hot patches; differentiable with respect to the backbone's (LoRA) weights.""" patch = backbone.patch_size reference = next(backbone.parameters()) count = channels * patch * patch dtype = torch.promote_types(reference.dtype, torch.float32) basis = torch.eye(count + 1, count, device=reference.device, dtype=dtype) basis = basis.reshape(count + 1, channels, patch, patch) with torch.autocast(reference.device.type, enabled=False), _ieee_convolutions(): out = backbone.embed_patches(basis).reshape(count + 1, -1) bias = out[-1] return (out[:-1] - bias).T.reshape(-1, channels, patch, patch), bias
@functools.lru_cache(maxsize=64)def _inverse_cached(order: tuple[int, ...], device: torch.device) -> torch.Tensor: return torch.tensor(order).argsort().to(device)
def _inverse(order: list[int], device: torch.device) -> torch.Tensor: """Indices that put outputs concatenated in `order` back into patch order.""" return _inverse_cached(tuple(order), device)
def embed_upsampled(backbone: nn.Module, images: torch.Tensor, grid_size: int, fold: bool = True) -> torch.Tensor: """backbone.embed_patches(bilinear upsample of images to grid_size * patch_size px), as a contiguous channels-first (B, C, grid_size, grid_size) map (float32 when folded).""" patch = backbone.patch_size up_size = grid_size * patch if not fold: upsampled = F.interpolate(images, size=(up_size, up_size), mode="bilinear", align_corners=False) return backbone.embed_patches(upsampled).permute(0, 3, 1, 2).contiguous()
batch, channels, height, width = images.shape start_y, weights_y, _, conv_y = _axis(height, up_size, patch, images.device) _, _, (step_x, period_x, groups_x), conv_x = _axis(width, up_size, patch, images.device) weight, bias = _patch_kernel(backbone, channels) weight, bias = weight.float(), bias.float() with torch.autocast(images.device.type, enabled=False): images = images.float() if conv_y is not None and conv_x is not None: (stride_y, low_y, high_y, kernel_y), (stride_x, low_x, high_x, kernel_x) = conv_y, conv_x folded = torch.einsum("ocuv,ua,vb->ocab", weight, kernel_y.float(), kernel_x.float()) padded = F.pad(images, (low_x, high_x, low_y, high_y), mode="replicate") return F.conv2d(padded, folded, bias, stride=(stride_y, stride_x)).contiguous()
# y: upsample the patch rows only: (B * T_y, C * P, 1, W), channel (c, row within the patch). rows = start_y[:, None] + torch.arange(weights_y.shape[2], device=images.device) rows = torch.einsum("tua,bctaw->btcuw", weights_y.float(), images[:, :, rows]) rows = rows.reshape(batch * grid_size, channels * patch, 1, width) # x: one strided convolution per group of patch columns sharing a kernel. outputs, order = [], [] for first, count, window, kernel in groups_x: folded = torch.einsum("ocuv,vb->ocub", weight, kernel.float()).flatten(1, 2)[:, :, None] span = rows[..., window:window + (count - 1) * step_x + kernel.shape[1]] outputs.append(F.conv2d(span, folded, stride=(1, step_x))) order.extend(range(first, first + count * period_x, period_x)) out = torch.cat(outputs, dim=-1)[..., _inverse(order, images.device)] out = out + bias[:, None, None] # (B * T_y, C_out, 1, T_x) return out.reshape(batch, grid_size, -1, grid_size).permute(0, 2, 1, 3).contiguous()
class QueryEncoder(nn.Module): """Initial query features: patch embeddings of the input image upsampled to a `grid_size` x `grid_size` patch grid, sampled bilinearly at the query coordinates.
fold: compute the embedding map directly from the input image (exact, much cheaper; see the module docstring). False builds the upsampled image, for comparison. """
def __init__(self, grid_size: int, fold: bool = True): super().__init__() self.grid_size, self.fold = grid_size, fold
def encode(self, pixel_values: torch.Tensor, backbone: nn.Module) -> torch.Tensor: """(B, 3, H, W) -> (B, C, grid_size, grid_size) patch embedding map.""" return embed_upsampled(backbone, pixel_values, self.grid_size, self.fold)
def forward(self, queries: torch.Tensor, patch_embeddings: torch.Tensor) -> torch.Tensor: """(B, N, 2) normalized (x, y) queries -> (B, N, C).""" grid = (queries * 2.0 - 1.0).unsqueeze(2).to(patch_embeddings.dtype) q = F.grid_sample(patch_embeddings, grid, mode="bilinear", padding_mode="border", align_corners=False) return q.squeeze(-1).transpose(1, 2)
def extra_repr(self) -> str: return f"grid_size={self.grid_size}, fold={self.fold}"1234567891025 unmodified lines3637383940414243441 unmodified line46474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394"""ViT-Up: an implicit decoder that queries backbone-aligned features at continuous coordinates."""import torchimport torch.nn.functional as Ffrom torch import nnfrom .backbones import Backbonefrom .layers import MLP, ContinuousRoPE2D, CrossAttention, FiLM, FourierPositionalEncodingdef closest_token_index(queries: torch.Tensor, height: int, width: int) -> torch.Tensor:25 unmodified linesself.norm_post = nn.LayerNorm(dim)self.fusion_mlp = MLP([dim, 4 * dim, dim])def forward(self, q, tokens_hwc, closest_token, rel_pos_enc, rope):q = self.transition_mlp(q)q = q + self.cross_attention(self.norm_q_global(q), self.norm_h_global(tokens_hwc.flatten(1, 2)), rope)q = q + self.norm_h_local(self.featx(closest_token, rel_pos_enc))return q + self.fusion_mlp(self.norm_post(q))1 unmodified lineclass ViTUp(nn.Module):"""Predict the features of `layer_indices` backbone layers at arbitrary query coordinates.Queries start from patch embeddings bilinearly sampled from a high-resolutionimage (`query_image_size`). Each block then moves them to the next selectedbackbone layer's feature space, and a per-layer decoder maps them to its output."""def __init__(self, dim: int, num_heads: int, layer_indices: list[int], query_image_size: int = 3584,num_bands: int = 16, max_resolution: float = 10.0, rope_base: float = 100.0):super().__init__()self.layer_indices = list(layer_indices)self.query_image_size = query_image_sizeself.rel_pos_enc = FourierPositionalEncoding(num_bands, max_resolution)self.q_rope_embeddings = ContinuousRoPE2D(dim // num_heads, base=rope_base)self.vit_up_blocks = nn.ModuleList(ViTUpBlock(dim, num_heads, self.rel_pos_enc.out_dim) for _ in self.layer_indices[1:])self.decoder_mlp = nn.ModuleList(MLP([dim, dim], input_layernorm=True) for _ in self.layer_indices)def encode(self, pixel_values: torch.Tensor, backbone: Backbone, image_size: int | None = None) -> dict:"""Compute the per-image cache shared by all queries of that image."""hidden_states = backbone.hidden_states(pixel_values, image_size)query_image = F.interpolate(pixel_values, size=(self.query_image_size, self.query_image_size),mode="bilinear", align_corners=False)return {"hidden_states": [hidden_states[i] for i in self.layer_indices],"patch_embeddings": backbone.embed_patches(query_image).permute(0, 3, 1, 2).contiguous(),}def forward(self, queries: torch.Tensor, cache: dict) -> list[torch.Tensor]:"""Return features of every selected layer, each (B, N, C), for (B, N, 2) queries in [0, 1]."""hidden_states = cache["hidden_states"]patch_embeddings = cache["patch_embeddings"]grid = (queries * 2.0 - 1.0).unsqueeze(2).to(patch_embeddings.dtype)q = F.grid_sample(patch_embeddings, grid, mode="bilinear", padding_mode="border", align_corners=False)q = q.squeeze(-1).transpose(1, 2)height, width = hidden_states[0].shape[1:3]index = closest_token_index(queries, height, width)rel_pos_enc = self.rel_pos_enc(relative_position(queries, index, height, width))rope = self.q_rope_embeddings(queries, height, width)batch = torch.arange(len(queries), device=queries.device)[:, None]outputs = [self.decoder_mlp[0](q)]for block, decoder, tokens in zip(self.vit_up_blocks, self.decoder_mlp[1:], hidden_states[1:]):closest_token = tokens.flatten(1, 2)[batch, index]q = block(q, tokens, closest_token, rel_pos_enc, rope)outputs.append(decoder(q))return outputs1234567891025 unmodified lines363738394041424344454647481 unmodified line5051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113"""ViT-Up: an implicit decoder that queries backbone-aligned features at continuous coordinates."""import torchfrom torch import nnfrom .backbones import Backbonefrom .layers import MLP, ContinuousRoPE2D, CrossAttention, FiLM, FourierPositionalEncodingfrom .query_encoder import QueryEncoderdef closest_token_index(queries: torch.Tensor, height: int, width: int) -> torch.Tensor:25 unmodified linesself.norm_post = nn.LayerNorm(dim)self.fusion_mlp = MLP([dim, 4 * dim, dim])def prepare(self, tokens_hwc, k_rope):"""Keys and values of one backbone layer's tokens (image-only, computed once per image)."""return self.cross_attention.prepare(self.norm_h_global(tokens_hwc.flatten(1, 2)), k_rope)def forward(self, q, keys_values, closest_token, rel_pos_enc, q_rope):q = self.transition_mlp(q)q = q + self.cross_attention.attend(self.norm_q_global(q), *keys_values, q_rope)q = q + self.norm_h_local(self.featx(closest_token, rel_pos_enc))return q + self.fusion_mlp(self.norm_post(q))1 unmodified lineclass ViTUp(nn.Module):"""Predict the features of `layer_indices` backbone layers at arbitrary query coordinates.Queries start from patch embeddings of the image upsampled to a `query_embd_grid_size`x `query_embd_grid_size` patch grid (224 = 3584 px for 16 px patches, 256 for 14 px),sampled at the query coordinates (see `QueryEncoder`; `fold=False` builds the upsampledimage instead, for comparison). Each block then moves them to the next selected backbonelayer's feature space, and a per-layer decoder maps them to its output.`encode` computes everything that depends only on the image once: backbone hidden states,the patch embedding map and each block's cross-attention keys and values. `forward` thenruns only the query-dependent part."""def __init__(self, dim: int, num_heads: int, layer_indices: list[int], query_embd_grid_size: int,fold: bool = True, num_bands: int = 16, max_resolution: float = 10.0, rope_base: float = 100.0):super().__init__()self.layer_indices = list(layer_indices)self.query_encoder = QueryEncoder(query_embd_grid_size, fold)self.rel_pos_enc = FourierPositionalEncoding(num_bands, max_resolution)self.q_rope_embeddings = ContinuousRoPE2D(dim // num_heads, base=rope_base)self.vit_up_blocks = nn.ModuleList(ViTUpBlock(dim, num_heads, self.rel_pos_enc.out_dim) for _ in self.layer_indices[1:])self.decoder_mlp = nn.ModuleList(MLP([dim, dim], input_layernorm=True) for _ in self.layer_indices)def encode(self, pixel_values: torch.Tensor, backbone: Backbone, ft_grid_size: int | None = None) -> dict:"""Compute the per-image cache shared by all queries of that image.The backbone runs on an ft_grid_size x ft_grid_size token grid (the input is resized toft_grid_size * patch_size px; None keeps the input size); the query encoder uses the input as given."""hidden_states = backbone.hidden_states(pixel_values, ft_grid_size)hidden_states = [hidden_states[i] for i in self.layer_indices]return {"hidden_states": hidden_states,"patch_embeddings": self.query_encoder.encode(pixel_values, backbone),"keys_values": self.keys_values(hidden_states),}def keys_values(self, hidden_states: list[torch.Tensor]) -> list[tuple[torch.Tensor, torch.Tensor]]:"""Each block's cross-attention keys and values of its backbone layer."""height, width = hidden_states[0].shape[1:3]k_rope = self.q_rope_embeddings.keys(height, width, hidden_states[0].device)return [block.prepare(tokens, k_rope) for block, tokens in zip(self.vit_up_blocks, hidden_states[1:])]def forward(self, queries: torch.Tensor, cache: dict) -> list[torch.Tensor]:"""Return features of every selected layer, each (B, N, C), for (B, N, 2) queries in [0, 1]."""hidden_states = cache["hidden_states"]keys_values = cache["keys_values"] if "keys_values" in cache else self.keys_values(hidden_states)q = self.query_encoder(queries, cache["patch_embeddings"])height, width = hidden_states[0].shape[1:3]index = closest_token_index(queries, height, width)rel_pos_enc = self.rel_pos_enc(relative_position(queries, index, height, width))q_rope = self.q_rope_embeddings.queries(queries, height, width)batch = torch.arange(len(queries), device=queries.device)[:, None]outputs = [self.decoder_mlp[0](q)]for block, decoder, tokens, kv in zip(self.vit_up_blocks, self.decoder_mlp[1:], hidden_states[1:],keys_values):closest_token = tokens.flatten(1, 2)[batch, index]q = block(q, kv, closest_token, rel_pos_enc, q_rope)outputs.append(decoder(q))return outputs
README.md+5-3
app.py+19-6
vit_up/__init__.py+1
vit_up/model/backbones.py+4-2
vit_up/model/layers.py+25-10
vit_up/model/query_encoder.pyAdded+192
vit_up/model/vit_up.py+42-23