""" DocSEAM: Document Selective Enrichment via Anchored Masking. A small, injectable module placed after a pretrained VLM's vision encoder (post-merger) and before the language model. It fuses each page with both neighbors through asymmetric, salience-gated cross-page attention. Key design: - Joint masked self-attention over concatenated [Z_prev; Z_curr; Z_next] - Asymmetric mask: curr <->{prev,next}, prev/next self-attend + read curr, prev <-> next blocked - Directional salience gate: learned content-conditioned gates decide which boundary tokens send to and receive from each neighbor - Zero-init output projections -> exact no-op at initialization - Clone QKV/FFN from host vision block for stable injection """ import math from typing import Optional import torch import torch.nn as nn import torch.nn.functional as F _ACT_FACTORIES = { "gelu_tanh": lambda: nn.GELU(approximate="tanh"), "gelu_pytorch_tanh": lambda: nn.GELU(approximate="tanh"), "gelu": lambda: nn.GELU(), "silu": lambda: nn.SiLU(), "relu": lambda: nn.ReLU(), } def _make_activation(name: str) -> nn.Module: if name not in _ACT_FACTORIES: raise ValueError(f"Unknown activation {name!r}. Known: {sorted(_ACT_FACTORIES)}") return _ACT_FACTORIES[name]() def _make_norm(hidden_size: int, eps: float = 1e-6) -> nn.LayerNorm: return nn.LayerNorm(hidden_size, eps=eps) # --------------------------------------------------------------------------- # Positional feature for salience gate # --------------------------------------------------------------------------- def cross_page_pos_feature(dist_frac: torch.Tensor, num_freqs: int = 4) -> torch.Tensor: """Continuous sinusoidal positional feature for distance-from-edge. Args: dist_frac: [...] float in [0, 1], capped fractional distance. num_freqs: number of frequency bands. Returns: [..., 1 + 2*num_freqs] tensor (no learnable params). """ freqs = (2.0 ** torch.arange(num_freqs, device=dist_frac.device, dtype=dist_frac.dtype)) * math.pi angles = dist_frac.unsqueeze(-1) * freqs # [..., num_freqs] return torch.cat([dist_frac.unsqueeze(-1), torch.sin(angles), torch.cos(angles)], dim=-1) def compute_pos_features( h: int, w: int, cap_frac: float, device: torch.device, dtype: torch.dtype, ) -> torch.Tensor: """Compute per-token positional features for a page grid. Args: h: grid height (post-merger rows). w: grid width (post-merger cols). cap_frac: CAP_FRAC — fraction of page height for capping distance. device, dtype: tensor placement. Returns: [h*w, 18] tensor of positional features. """ num_freqs = 4 n_tokens = h * w # Row index for each token (tokens are stored row-major) row_idx = torch.arange(h, device=device, dtype=dtype).unsqueeze(1).expand(h, w).reshape(n_tokens) h_real = float(h) cap_p = cap_frac * h_real # Distance from top edge, capped dist_top = torch.clamp(row_idx, max=cap_p) / h_real # Distance from bottom edge, capped dist_bot = torch.clamp(h_real - 1.0 - row_idx, max=cap_p) / h_real # Sinusoidal expansion (9 dims each, 18 total) feat_top = cross_page_pos_feature(dist_top, num_freqs) # [n_tokens, 9] feat_bot = cross_page_pos_feature(dist_bot, num_freqs) # [n_tokens, 9] return torch.cat([feat_top, feat_bot], dim=-1) # [n_tokens, 18] @torch.no_grad() def _find_content_frontiers( content_mask: torch.Tensor, h: int, w: int, ) -> Optional[tuple[torch.Tensor, torch.Tensor]]: """Find first/last ink rows from a per-token content mask.""" content = content_mask.reshape(h, w).float() row_score = content.amax(dim=1) if row_score.numel() == 0: return None max_score = row_score.max() threshold = torch.maximum(max_score * 0.25, row_score.new_tensor(0.03)) active_rows = torch.nonzero(row_score >= threshold, as_tuple=False).flatten() if active_rows.numel() == 0: active_rows = torch.nonzero(row_score > 0, as_tuple=False).flatten() if active_rows.numel() == 0: return None return active_rows[0].to(device=content.device), active_rows[-1].to(device=content.device) def compute_frontier_pos_features( h: int, w: int, cap_frac: float, device: torch.device, dtype: torch.dtype, content_mask: Optional[torch.Tensor], ) -> torch.Tensor: """Compute positional gate features relative to first/last ink rows. Blank page margins outside the detected content band are treated as far from the frontier, so the gate cannot use physical whitespace as the easy shortcut for "near a boundary". """ if content_mask is None: return compute_pos_features(h, w, cap_frac, device, dtype) content_mask = content_mask.to(device=device) frontiers = _find_content_frontiers(content_mask, h, w) if frontiers is None: return compute_pos_features(h, w, cap_frac, device, dtype) top_frontier, bottom_frontier = frontiers num_freqs = 4 n_tokens = h * w row_idx = torch.arange(h, device=device, dtype=dtype).unsqueeze(1).expand(h, w).reshape(n_tokens) h_real = float(h) cap_p = cap_frac * h_real far = row_idx.new_full(row_idx.shape, cap_p) top_frontier = top_frontier.to(device=device, dtype=dtype) bottom_frontier = bottom_frontier.to(device=device, dtype=dtype) dist_top_raw = row_idx - top_frontier dist_bottom_raw = bottom_frontier - row_idx dist_top = torch.where(dist_top_raw >= 0, torch.clamp(dist_top_raw, max=cap_p), far) / h_real dist_bot = torch.where(dist_bottom_raw >= 0, torch.clamp(dist_bottom_raw, max=cap_p), far) / h_real feat_top = cross_page_pos_feature(dist_top, num_freqs) feat_bot = cross_page_pos_feature(dist_bot, num_freqs) return torch.cat([feat_top, feat_bot], dim=-1) def compute_edge_targets( h: int, w: int, tau_frac: float, device: torch.device, dtype: torch.dtype, ) -> tuple[torch.Tensor, torch.Tensor]: """Soft top/bottom edge targets for directional gate regularization.""" n_tokens = h * w row_idx = torch.arange(h, device=device, dtype=dtype).unsqueeze(1).expand(h, w).reshape(n_tokens) denom = max(float(h - 1), 1.0) tau = max(float(tau_frac), 1e-4) dist_top = row_idx / denom dist_bottom = (float(h - 1) - row_idx) / denom target_top = torch.exp(-dist_top / tau) target_bottom = torch.exp(-dist_bottom / tau) return target_top, target_bottom def compute_ink_edge_targets( target_top: torch.Tensor, target_bottom: torch.Tensor, content_mask: torch.Tensor, ) -> tuple[torch.Tensor, torch.Tensor]: """Apply a detached per-token ink/content mask to edge targets.""" content_mask = content_mask.to(device=target_top.device, dtype=target_top.dtype) return target_top * content_mask, target_bottom * content_mask @torch.no_grad() def compute_ink_frontier_targets( content_mask: torch.Tensor, h: int, w: int, tau_frac: float, ) -> tuple[torch.Tensor, torch.Tensor]: """Soft targets around the first/last ink rows, not the physical page edge.""" content = content_mask.reshape(h, w).float() row_score = content.amax(dim=1) if row_score.numel() == 0: zeros = content.reshape(-1).to(dtype=content_mask.dtype) return zeros, zeros max_score = row_score.max() threshold = torch.maximum(max_score * 0.25, row_score.new_tensor(0.03)) active_rows = torch.nonzero(row_score >= threshold, as_tuple=False).flatten() if active_rows.numel() == 0: active_rows = torch.nonzero(row_score > 0, as_tuple=False).flatten() if active_rows.numel() == 0: zeros = content.reshape(-1).to(dtype=content_mask.dtype) return zeros, zeros top_frontier = active_rows[0].to(device=content.device, dtype=content.dtype) bottom_frontier = active_rows[-1].to(device=content.device, dtype=content.dtype) row_idx = torch.arange(h, device=content.device, dtype=content.dtype).unsqueeze(1) denom = max(float(h - 1), 1.0) tau = max(float(tau_frac), 1e-4) top_band = torch.exp(-torch.abs(row_idx - top_frontier) / (denom * tau)) bottom_band = torch.exp(-torch.abs(row_idx - bottom_frontier) / (denom * tau)) target_top = (top_band * content).reshape(-1).to(dtype=content_mask.dtype) target_bottom = (bottom_band * content).reshape(-1).to(dtype=content_mask.dtype) return target_top, target_bottom # --------------------------------------------------------------------------- # Asymmetric attention mask builder # --------------------------------------------------------------------------- def build_asymmetric_mask( n_prev: int, n_curr: int, n_next: int, device: torch.device, dtype: torch.dtype, ) -> torch.Tensor: """Build the [3N, 3N] additive mask for the triplet attention. Allowed flows: prev -> {prev, curr} (self-attend + read center) curr -> {prev, curr, next} (reads both neighbors — BIDIRECTIONAL) next -> {curr, next} (self-attend + read center) BLOCKED: prev <-> next (two pages apart, no direct link) Returns: [total, total] additive float mask. 0 = allowed, -inf = blocked. """ total = n_prev + n_curr + n_next min_val = torch.finfo(dtype).min mask = torch.full((total, total), min_val, device=device, dtype=dtype) # Ranges p_s, p_e = 0, n_prev c_s, c_e = n_prev, n_prev + n_curr n_s, n_e = n_prev + n_curr, total # prev -> prev (self-attend) mask[p_s:p_e, p_s:p_e] = 0.0 # prev -> curr (read center) mask[p_s:p_e, c_s:c_e] = 0.0 # curr -> prev (read prev neighbor) mask[c_s:c_e, p_s:p_e] = 0.0 # curr -> curr (self-attend) mask[c_s:c_e, c_s:c_e] = 0.0 # curr -> next (read next neighbor) mask[c_s:c_e, n_s:n_e] = 0.0 # next -> curr (read center) mask[n_s:n_e, c_s:c_e] = 0.0 # next -> next (self-attend) mask[n_s:n_e, n_s:n_e] = 0.0 # prev <-> next: BLOCKED (stays at min_val) return mask # --------------------------------------------------------------------------- # DocSEAM Block (single transformer layer over the triplet) # --------------------------------------------------------------------------- class DocSEAMBlock(nn.Module): """Single DocSEAM transformer layer: salience-gated, asymmetric-masked self-attention over [Z_prev; Z_curr; Z_next] + FFN. Args: hidden_size: token dimension (post-merger, = LLM hidden_size). num_heads: attention heads. intermediate_size: FFN inner dimension. cap_frac: CAP_FRAC for salience gate positional features. proj_init_std: if > 0, init output projections with normal(0, std); otherwise zero-init (default for exact no-op). activation: activation function name for FFN. """ POS_FEAT_DIM = 18 # 2 * (1 + 2*4) def __init__( self, hidden_size: int, num_heads: int, intermediate_size: int = 4096, cap_frac: float = 0.20, proj_init_std: float = 0.0, activation: str = "gelu_pytorch_tanh", ): super().__init__() self.hidden_size = hidden_size self.num_heads = num_heads self.head_dim = hidden_size // num_heads self.cap_frac = cap_frac # --- Norms --- self.norm1 = _make_norm(hidden_size) self.norm2 = _make_norm(hidden_size) # --- Attention QKV (fused) + output projection --- self.qkv = nn.Linear(hidden_size, hidden_size * 3, bias=True) self.proj = nn.Linear(hidden_size, hidden_size, bias=True) # --- FFN (2-linear GELU, mirroring Qwen3.5 vision block) --- self.act = _make_activation(activation) self.fc1 = nn.Linear(hidden_size, intermediate_size, bias=True) self.fc2 = nn.Linear(intermediate_size, hidden_size, bias=True) # --- Directional salience gate MLPs (D+18 -> D/4 -> 1) --- gate_input_dim = hidden_size + self.POS_FEAT_DIM gate_hidden_dim = hidden_size // 4 self.mlp_send_to_next = nn.Sequential( nn.Linear(gate_input_dim, gate_hidden_dim), nn.GELU(), nn.Linear(gate_hidden_dim, 1), ) self.mlp_recv_from_prev = nn.Sequential( nn.Linear(gate_input_dim, gate_hidden_dim), nn.GELU(), nn.Linear(gate_hidden_dim, 1), ) self.mlp_send_to_prev = nn.Sequential( nn.Linear(gate_input_dim, gate_hidden_dim), nn.GELU(), nn.Linear(gate_hidden_dim, 1), ) self.mlp_recv_from_next = nn.Sequential( nn.Linear(gate_input_dim, gate_hidden_dim), nn.GELU(), nn.Linear(gate_hidden_dim, 1), ) # --- Init --- self._init_weights(proj_init_std) def _init_weights(self, proj_init_std: float): """Zero-init output projections and salience gate final layers.""" # Output projection: zero or tiny-normal if proj_init_std > 0: nn.init.normal_(self.proj.weight, std=proj_init_std) nn.init.zeros_(self.proj.bias) nn.init.normal_(self.fc2.weight, std=proj_init_std) nn.init.zeros_(self.fc2.bias) else: nn.init.zeros_(self.proj.weight) nn.init.zeros_(self.proj.bias) nn.init.zeros_(self.fc2.weight) nn.init.zeros_(self.fc2.bias) # Salience gate final layers: zero-init so gates start neutral. for mlp in ( self.mlp_send_to_next, self.mlp_recv_from_prev, self.mlp_send_to_prev, self.mlp_recv_from_next, ): nn.init.zeros_(mlp[-1].weight) nn.init.zeros_(mlp[-1].bias) def _compute_salience_bias( self, tokens: torch.Tensor, pos_feats: torch.Tensor, n_prev: int, n_curr: int, n_next: int, ) -> torch.Tensor: """Compute additive salience bias for cross-page attention cells. Args: tokens: [total, D] the normalized concatenated tokens. pos_feats: [total, 18] positional features for all tokens. n_prev, n_curr, n_next: token counts per page. Returns: [total, total] additive bias (0 for same-page cells, gate values for cross-page cells). """ total = n_prev + n_curr + n_next # Concatenate features for gate input gate_input = torch.cat([tokens, pos_feats], dim=-1) # [total, D+18] # Compute per-token directional scores. s_send_to_next = self.mlp_send_to_next(gate_input).squeeze(-1) # [total] s_recv_from_prev = self.mlp_recv_from_prev(gate_input).squeeze(-1) # [total] s_send_to_prev = self.mlp_send_to_prev(gate_input).squeeze(-1) # [total] s_recv_from_next = self.mlp_recv_from_next(gate_input).squeeze(-1) # [total] # Cache for visualization. self._last_salience = { "s_send_to_next": s_send_to_next.detach(), "s_recv_from_prev": s_recv_from_prev.detach(), "s_send_to_prev": s_send_to_prev.detach(), "s_recv_from_next": s_recv_from_next.detach(), } # log_sigmoid for numerical stability. log_send_to_next = F.logsigmoid(s_send_to_next) # [total] log_recv_from_prev = F.logsigmoid(s_recv_from_prev) # [total] log_send_to_prev = F.logsigmoid(s_send_to_prev) # [total] log_recv_from_next = F.logsigmoid(s_recv_from_next) # [total] # Build bias: only apply to cross-page cells bias = torch.zeros(total, total, device=tokens.device, dtype=tokens.dtype) # Ranges p_s, p_e = 0, n_prev c_s, c_e = n_prev, n_prev + n_curr n_s, n_e = n_prev + n_curr, total # curr query reads prev key: current receives from previous; previous sends to next. bias[c_s:c_e, p_s:p_e] = ( log_recv_from_prev[c_s:c_e].unsqueeze(1) + log_send_to_next[p_s:p_e].unsqueeze(0) ) # curr query reads next key: current receives from next; next sends to previous. bias[c_s:c_e, n_s:n_e] = ( log_recv_from_next[c_s:c_e].unsqueeze(1) + log_send_to_prev[n_s:n_e].unsqueeze(0) ) # prev query reads curr key: previous receives from next; current sends to previous. bias[p_s:p_e, c_s:c_e] = ( log_recv_from_next[p_s:p_e].unsqueeze(1) + log_send_to_prev[c_s:c_e].unsqueeze(0) ) # next query reads curr key: next receives from previous; current sends to next. bias[n_s:n_e, c_s:c_e] = ( log_recv_from_prev[n_s:n_e].unsqueeze(1) + log_send_to_next[c_s:c_e].unsqueeze(0) ) return bias def _compute_gate_scores(self, tokens: torch.Tensor, pos_feats: torch.Tensor) -> dict[str, torch.Tensor]: gate_input = torch.cat([tokens, pos_feats], dim=-1) return { "s_send_to_next": self.mlp_send_to_next(gate_input).squeeze(-1), "s_recv_from_prev": self.mlp_recv_from_prev(gate_input).squeeze(-1), "s_send_to_prev": self.mlp_send_to_prev(gate_input).squeeze(-1), "s_recv_from_next": self.mlp_recv_from_next(gate_input).squeeze(-1), } def compute_gate_aux_loss( self, triplet_tokens: torch.Tensor, pos_feats: torch.Tensor, target_top: Optional[torch.Tensor], target_bottom: Optional[torch.Tensor], target_content: Optional[torch.Tensor], frontier_top: Optional[torch.Tensor], frontier_bottom: Optional[torch.Tensor], edge_prior_weight: float, ink_prior_weight: float, frontier_prior_weight: float, gate_l1_weight: float, gate_budget_weight: float, gate_budget_target: float, margin_penalty_weight: float = 0.0, ) -> torch.Tensor: normed = self.norm1(triplet_tokens) scores = self._compute_gate_scores(normed, pos_feats) loss = normed.new_zeros(()) def weighted_open_loss(score: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: open_loss = F.binary_cross_entropy_with_logits( score, torch.ones_like(score), reduction="none", ) weight = weight.detach() return (open_loss * weight).sum() / weight.sum().clamp_min(1.0) if edge_prior_weight > 0 and target_top is not None and target_bottom is not None: edge_loss = ( F.binary_cross_entropy_with_logits(scores["s_send_to_next"], target_bottom) + F.binary_cross_entropy_with_logits(scores["s_recv_from_prev"], target_top) + F.binary_cross_entropy_with_logits(scores["s_send_to_prev"], target_top) + F.binary_cross_entropy_with_logits(scores["s_recv_from_next"], target_bottom) ) / 4.0 loss = loss + float(edge_prior_weight) * edge_loss if ink_prior_weight > 0 and target_top is not None and target_bottom is not None and target_content is not None: ink_top, ink_bottom = compute_ink_edge_targets(target_top, target_bottom, target_content) ink_loss = ( weighted_open_loss(scores["s_send_to_next"], ink_bottom) + weighted_open_loss(scores["s_recv_from_prev"], ink_top) + weighted_open_loss(scores["s_send_to_prev"], ink_top) + weighted_open_loss(scores["s_recv_from_next"], ink_bottom) ) / 4.0 loss = loss + float(ink_prior_weight) * ink_loss if frontier_prior_weight > 0 and frontier_top is not None and frontier_bottom is not None: frontier_loss = ( weighted_open_loss(scores["s_send_to_next"], frontier_bottom) + weighted_open_loss(scores["s_recv_from_prev"], frontier_top) + weighted_open_loss(scores["s_send_to_prev"], frontier_top) + weighted_open_loss(scores["s_recv_from_next"], frontier_bottom) ) / 4.0 loss = loss + float(frontier_prior_weight) * frontier_loss if ( margin_penalty_weight > 0 and target_top is not None and target_bottom is not None and target_content is not None ): blank = (1.0 - target_content.detach()).clamp(0.0, 1.0) margin_top = target_top.detach() * blank margin_bottom = target_bottom.detach() * blank def weighted_close_loss(score: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: close_loss = F.binary_cross_entropy_with_logits( score, torch.zeros_like(score), reduction="none", ) return (close_loss * weight).sum() / weight.sum().clamp_min(1.0) margin_loss = ( weighted_close_loss(scores["s_send_to_next"], margin_bottom) + weighted_close_loss(scores["s_recv_from_prev"], margin_top) + weighted_close_loss(scores["s_send_to_prev"], margin_top) + weighted_close_loss(scores["s_recv_from_next"], margin_bottom) ) / 4.0 loss = loss + float(margin_penalty_weight) * margin_loss if gate_l1_weight > 0: gate_l1 = torch.stack([torch.sigmoid(score).mean() for score in scores.values()]).mean() loss = loss + float(gate_l1_weight) * gate_l1 if gate_budget_weight > 0: gate_means = torch.stack([torch.sigmoid(score).mean() for score in scores.values()]) target = gate_means.new_tensor(float(gate_budget_target)) gate_budget = F.relu(gate_means - target).square().mean() loss = loss + float(gate_budget_weight) * gate_budget return loss def forward( self, triplet_tokens: torch.Tensor, attn_mask: torch.Tensor, pos_feats: torch.Tensor, n_prev: int, n_curr: int, n_next: int, ) -> torch.Tensor: """Forward pass through one DocSEAM layer. Args: triplet_tokens: [total, D] concatenated [Z_prev; Z_curr; Z_next]. attn_mask: [total, total] additive mask (0=allowed, -inf=blocked). pos_feats: [total, 18] positional features for all tokens. n_prev, n_curr, n_next: token counts per page. Returns: [total, D] updated tokens (all 3 pages updated). """ total = triplet_tokens.shape[0] # --- Attention --- normed = self.norm1(triplet_tokens) # QKV projection qkv = self.qkv(normed) # [total, 3*D] q = qkv[:, :self.hidden_size] k = qkv[:, self.hidden_size:2 * self.hidden_size] v = qkv[:, 2 * self.hidden_size:] # Reshape for multi-head attention: [1, num_heads, total, head_dim] q = q.view(total, self.num_heads, self.head_dim).transpose(0, 1).unsqueeze(0) k = k.view(total, self.num_heads, self.head_dim).transpose(0, 1).unsqueeze(0) v = v.view(total, self.num_heads, self.head_dim).transpose(0, 1).unsqueeze(0) # Compute salience bias salience_bias = self._compute_salience_bias(normed, pos_feats, n_prev, n_curr, n_next) # Combine asymmetric mask + salience bias # attn_mask: [total, total], salience_bias: [total, total] combined_mask = attn_mask + salience_bias # [total, total] # Expand for SDPA: [1, 1, total, total] (broadcast over batch and heads) combined_mask = combined_mask.unsqueeze(0).unsqueeze(0) # SDPA attention attn_out = F.scaled_dot_product_attention(q, k, v, attn_mask=combined_mask) # [1, num_heads, total, head_dim] -> [total, D] attn_out = attn_out.squeeze(0).transpose(0, 1).contiguous().view(total, -1) # Residual + projection triplet_tokens = triplet_tokens + self.proj(attn_out) # --- FFN --- triplet_tokens = triplet_tokens + self.fc2(self.act(self.fc1(self.norm2(triplet_tokens)))) return triplet_tokens # --------------------------------------------------------------------------- # DocSEAM module (stack of DocSEAMBlock layers) # --------------------------------------------------------------------------- class DocSEAM(nn.Module): """Triplet-Context Encoder with salience-gated cross-page Attention. Operates on post-merger vision tokens. For each page, builds a triplet [Z_{p-1}, Z_p, Z_{p+1}], runs stacked DocSEAMBlock layers, and returns only the enriched center page tokens E_p. Args: hidden_size: token dimension (post-merger = LLM hidden_size). num_heads: attention heads. intermediate_size: FFN inner dimension. num_layers: number of stacked DocSEAM layers (default 2). cap_frac: CAP_FRAC for salience gate (default 0.20). proj_init_std: init std for output projections (0 = zero-init). activation: FFN activation name. """ def __init__( self, hidden_size: int = 2560, num_heads: int = 16, intermediate_size: int = 4096, num_layers: int = 2, cap_frac: float = 0.20, proj_init_std: float = 0.0, activation: str = "gelu_pytorch_tanh", ): super().__init__() self.hidden_size = hidden_size self.num_heads = num_heads self.num_layers = num_layers self.cap_frac = cap_frac self.edge_prior_weight = 0.0 self.ink_prior_weight = 0.0 self.frontier_prior_weight = 0.0 self.gate_l1_weight = 0.0 self.gate_budget_weight = 0.0 self.gate_budget_target = 0.20 self.edge_prior_tau = 0.08 self.pos_feature_mode = "physical" self.margin_penalty_weight = 0.0 self.use_checkpoint = True self.use_reentrant_checkpoint = True self.layers = nn.ModuleList([ DocSEAMBlock( hidden_size=hidden_size, num_heads=num_heads, intermediate_size=intermediate_size, cap_frac=cap_frac, proj_init_std=proj_init_std, activation=activation, ) for _ in range(num_layers) ]) @staticmethod def _row_band_indices( h: int, w: int, start_row: int, end_row: int, offset: int, device: torch.device, ) -> torch.Tensor: rows = torch.arange(start_row, end_row, device=device) cols = torch.arange(w, device=device) return offset + (rows[:, None] * w + cols[None, :]).reshape(-1) @torch.no_grad() def _compute_attention_flow( self, layer: DocSEAMBlock, triplet_tokens: torch.Tensor, attn_mask: torch.Tensor, pos_feats: torch.Tensor, n_prev: int, n_curr: int, n_next: int, h_prev: int, w_prev: int, h_curr: int, w_curr: int, h_next: int, w_next: int, ) -> dict[str, torch.Tensor | float | int]: """Compute selected cross-page attention-flow slices for diagnostics. This avoids materializing the full [heads, total, total] attention matrix. Probabilities are still normalized against all allowed keys, matching SDPA. """ band_frac = float(getattr(self, "attention_flow_band_frac", self.cap_frac)) chunk_size = int(getattr(self, "attention_flow_chunk_size", 64)) chunk_size = max(1, chunk_size) prev_band_rows = max(1, int(math.ceil(h_prev * band_frac))) curr_band_rows = max(1, int(math.ceil(h_curr * band_frac))) next_band_rows = max(1, int(math.ceil(h_next * band_frac))) prev_bottom = self._row_band_indices( h_prev, w_prev, h_prev - prev_band_rows, h_prev, 0, triplet_tokens.device ) center_top = self._row_band_indices( h_curr, w_curr, 0, curr_band_rows, n_prev, triplet_tokens.device ) center_bottom = self._row_band_indices( h_curr, w_curr, h_curr - curr_band_rows, h_curr, n_prev, triplet_tokens.device ) next_top = self._row_band_indices( h_next, w_next, 0, next_band_rows, n_prev + n_curr, triplet_tokens.device ) normed = layer.norm1(triplet_tokens) qkv = layer.qkv(normed) q = qkv[:, : layer.hidden_size] k = qkv[:, layer.hidden_size : 2 * layer.hidden_size] q = q.view(-1, layer.num_heads, layer.head_dim).transpose(0, 1).float() k = k.view(-1, layer.num_heads, layer.head_dim).transpose(0, 1).float() salience_bias = layer._compute_salience_bias(normed, pos_feats, n_prev, n_curr, n_next) combined_mask = (attn_mask + salience_bias).float() scale = 1.0 / math.sqrt(layer.head_dim) def summarize(query_idx: torch.Tensor, source_start: int, source_len: int, focus_idx: torch.Tensor): source_sum = torch.zeros(source_len, device="cpu", dtype=torch.float64) query_mass = torch.zeros(query_idx.numel(), device="cpu", dtype=torch.float64) denom = 0 source_slice = slice(source_start, source_start + source_len) local_focus = (focus_idx - source_start).detach().cpu() for start in range(0, query_idx.numel(), chunk_size): q_chunk_idx = query_idx[start : start + chunk_size] q_chunk = q[:, q_chunk_idx, :] logits = torch.einsum("hqd,hkd->hqk", q_chunk, k) * scale logits = logits + combined_mask[q_chunk_idx].unsqueeze(0) probs = torch.softmax(logits, dim=-1) source_probs = probs[:, :, source_slice] source_sum += source_probs.sum(dim=(0, 1)).detach().cpu().double() query_mass[start : start + q_chunk_idx.numel()] = ( source_probs.sum(dim=-1).mean(dim=0).detach().cpu().double() ) denom += source_probs.shape[0] * source_probs.shape[1] source_avg = source_sum / max(denom, 1) source_mass = float(source_avg.sum().item()) focus_mass = float(source_avg[local_focus].sum().item()) return source_avg.float(), query_mass.float(), source_mass, focus_mass / max(source_mass, 1e-12) prev_source, center_top_mass, top_to_prev_mass, prev_bottom_frac = summarize( center_top, 0, n_prev, prev_bottom ) next_source, center_bottom_mass, bottom_to_next_mass, next_top_frac = summarize( center_bottom, n_prev + n_curr, n_next, next_top ) center_top_map = torch.zeros(n_curr, dtype=torch.float32) center_bottom_map = torch.zeros(n_curr, dtype=torch.float32) center_top_local = (center_top - n_prev).detach().cpu() center_bottom_local = (center_bottom - n_prev).detach().cpu() center_top_map[center_top_local] = center_top_mass center_bottom_map[center_bottom_local] = center_bottom_mass return { "prev_source_from_center_top": prev_source, "center_top_to_prev": center_top_map, "center_bottom_to_next": center_bottom_map, "next_source_from_center_bottom": next_source, "top_to_prev_mass": top_to_prev_mass, "bottom_to_next_mass": bottom_to_next_mass, "prev_mass_bottom_band_frac": prev_bottom_frac, "next_mass_top_band_frac": next_top_frac, "band_frac": band_frac, "prev_band_rows": prev_band_rows, "curr_band_rows": curr_band_rows, "next_band_rows": next_band_rows, } def _process_triplet( self, z_prev: torch.Tensor, z_curr: torch.Tensor, z_next: torch.Tensor, h_prev: int, w_prev: int, h_curr: int, w_curr: int, h_next: int, w_next: int, detach_neighbors: bool = False, record_meta: Optional[dict] = None, ink_prev: Optional[torch.Tensor] = None, ink_curr: Optional[torch.Tensor] = None, ink_next: Optional[torch.Tensor] = None, ) -> torch.Tensor: """Process a single triplet and return enriched center page tokens. Args: z_prev: [M_prev, D] previous page tokens (or self-fallback copy). z_curr: [M_curr, D] center page tokens. z_next: [M_next, D] next page tokens (or self-fallback copy). h_prev, w_prev: grid dims of previous page. h_curr, w_curr: grid dims of center page. h_next, w_next: grid dims of next page. detach_neighbors: if True, detach prev/next features (Stage A). Returns: [M_curr, D] enriched center page tokens. """ if detach_neighbors: z_prev = z_prev.detach() z_next = z_next.detach() n_prev, n_curr, n_next = z_prev.shape[0], z_curr.shape[0], z_next.shape[0] # Concatenate triplet triplet = torch.cat([z_prev, z_curr, z_next], dim=0) # [total, D] # Build asymmetric mask (can be cached if sizes repeat) attn_mask = build_asymmetric_mask(n_prev, n_curr, n_next, triplet.device, triplet.dtype) # Compute positional features for each page. pos_feature_mode = str(getattr(self, "pos_feature_mode", "physical") or "physical").lower() if pos_feature_mode == "frontier": pf_prev = compute_frontier_pos_features( h_prev, w_prev, self.cap_frac, triplet.device, triplet.dtype, ink_prev ) pf_curr = compute_frontier_pos_features( h_curr, w_curr, self.cap_frac, triplet.device, triplet.dtype, ink_curr ) pf_next = compute_frontier_pos_features( h_next, w_next, self.cap_frac, triplet.device, triplet.dtype, ink_next ) else: pf_prev = compute_pos_features(h_prev, w_prev, self.cap_frac, triplet.device, triplet.dtype) pf_curr = compute_pos_features(h_curr, w_curr, self.cap_frac, triplet.device, triplet.dtype) pf_next = compute_pos_features(h_next, w_next, self.cap_frac, triplet.device, triplet.dtype) pos_feats = torch.cat([pf_prev, pf_curr, pf_next], dim=0) # [total, 18] edge_prior_weight = float(getattr(self, "edge_prior_weight", 0.0) or 0.0) ink_prior_weight = float(getattr(self, "ink_prior_weight", 0.0) or 0.0) frontier_prior_weight = float(getattr(self, "frontier_prior_weight", 0.0) or 0.0) gate_l1_weight = float(getattr(self, "gate_l1_weight", 0.0) or 0.0) gate_budget_weight = float(getattr(self, "gate_budget_weight", 0.0) or 0.0) gate_budget_target = float(getattr(self, "gate_budget_target", 0.20) or 0.20) margin_penalty_weight = float(getattr(self, "margin_penalty_weight", 0.0) or 0.0) use_aux_loss = self.training and torch.is_grad_enabled() and ( edge_prior_weight > 0 or ink_prior_weight > 0 or frontier_prior_weight > 0 or gate_l1_weight > 0 or gate_budget_weight > 0 or margin_penalty_weight > 0 ) if use_aux_loss: tau = float(getattr(self, "edge_prior_tau", 0.08) or 0.08) prev_top, prev_bottom = compute_edge_targets(h_prev, w_prev, tau, triplet.device, triplet.dtype) curr_top, curr_bottom = compute_edge_targets(h_curr, w_curr, tau, triplet.device, triplet.dtype) next_top, next_bottom = compute_edge_targets(h_next, w_next, tau, triplet.device, triplet.dtype) target_top = torch.cat([prev_top, curr_top, next_top], dim=0) target_bottom = torch.cat([prev_bottom, curr_bottom, next_bottom], dim=0) if ink_prev is not None and ink_curr is not None and ink_next is not None: target_content = torch.cat( [ ink_prev.reshape(-1).detach(), ink_curr.reshape(-1).detach(), ink_next.reshape(-1).detach(), ], dim=0, ).to(device=triplet.device, dtype=triplet.dtype) else: target_content = None if frontier_prior_weight > 0 and ink_prev is not None and ink_curr is not None and ink_next is not None: prev_frontier_top, prev_frontier_bottom = compute_ink_frontier_targets( ink_prev.detach().to(device=triplet.device), h_prev, w_prev, tau, ) curr_frontier_top, curr_frontier_bottom = compute_ink_frontier_targets( ink_curr.detach().to(device=triplet.device), h_curr, w_curr, tau, ) next_frontier_top, next_frontier_bottom = compute_ink_frontier_targets( ink_next.detach().to(device=triplet.device), h_next, w_next, tau, ) frontier_top = torch.cat( [prev_frontier_top, curr_frontier_top, next_frontier_top], dim=0, ).to(device=triplet.device, dtype=triplet.dtype) frontier_bottom = torch.cat( [prev_frontier_bottom, curr_frontier_bottom, next_frontier_bottom], dim=0, ).to(device=triplet.device, dtype=triplet.dtype) else: frontier_top = None frontier_bottom = None else: target_top = None target_bottom = None target_content = None frontier_top = None frontier_bottom = None # Run through DocSEAM layers for layer_idx, layer in enumerate(self.layers): if use_aux_loss: aux_loss = layer.compute_gate_aux_loss( triplet, pos_feats, target_top, target_bottom, target_content, frontier_top, frontier_bottom, edge_prior_weight=edge_prior_weight, ink_prior_weight=ink_prior_weight, frontier_prior_weight=frontier_prior_weight, gate_l1_weight=gate_l1_weight, gate_budget_weight=gate_budget_weight, gate_budget_target=gate_budget_target, margin_penalty_weight=margin_penalty_weight, ) self._aux_loss = aux_loss if self._aux_loss is None else self._aux_loss + aux_loss self._aux_loss_terms += 1 if getattr(self, "record_attention_flow", False): flow = self._compute_attention_flow( layer, triplet, attn_mask, pos_feats, n_prev, n_curr, n_next, h_prev, w_prev, h_curr, w_curr, h_next, w_next, ) meta = {} if record_meta is None else dict(record_meta) meta.update({ "layer": layer_idx, "n_prev": n_prev, "n_curr": n_curr, "n_next": n_next, "prev_grid": (h_prev, w_prev), "curr_grid": (h_curr, w_curr), "next_grid": (h_next, w_next), }) meta.update(flow) self._last_attention_flow_records.append(meta) if self.training and torch.is_grad_enabled() and bool(getattr(self, "use_checkpoint", True)): from torch.utils.checkpoint import checkpoint if not triplet.requires_grad: triplet.requires_grad_(True) triplet = checkpoint( layer, triplet, attn_mask, pos_feats, n_prev, n_curr, n_next, use_reentrant=bool(getattr(self, "use_reentrant_checkpoint", True)), ) else: triplet = layer(triplet, attn_mask, pos_feats, n_prev, n_curr, n_next) if getattr(self, "record_salience", False): salience = layer._last_salience meta = {} if record_meta is None else dict(record_meta) meta.update({ "layer": layer_idx, "n_prev": n_prev, "n_curr": n_curr, "n_next": n_next, "prev_grid": (h_prev, w_prev), "curr_grid": (h_curr, w_curr), "next_grid": (h_next, w_next), }) meta.update({key: value.detach().cpu() for key, value in salience.items()}) self._last_salience_records.append(meta) # Extract center page tokens only return triplet[n_prev:n_prev + n_curr] def forward( self, page_tokens: list[torch.Tensor], page_grid_dims: list[tuple[int, int]], pages_per_document: list[int], detach_neighbors: bool = False, page_ink_masks: Optional[list[torch.Tensor]] = None, ) -> list[torch.Tensor]: """Process all pages across all documents in the batch. Args: page_tokens: list of [M_p, D] tensors, one per page (all docs). page_grid_dims: list of (h_p, w_p) tuples, one per page. pages_per_document: list of page counts per document. detach_neighbors: if True, detach neighbor features (Stage A). Returns: list of [M_p, D] enriched page tokens (same order/shapes as input). """ if getattr(self, "record_salience", False): self._last_salience_records = [] if getattr(self, "record_attention_flow", False): self._last_attention_flow_records = [] self._aux_loss = None self._aux_loss_terms = 0 enriched = [] page_idx = 0 for doc_num_pages in pages_per_document: doc_start = page_idx doc_end = page_idx + doc_num_pages for p in range(doc_start, doc_end): # Get current page z_curr = page_tokens[p] h_curr, w_curr = page_grid_dims[p] ink_curr = page_ink_masks[p] if page_ink_masks is not None else None # Get previous page (self-fallback if first page of document) if p == doc_start: z_prev = z_curr # self-fallback h_prev, w_prev = h_curr, w_curr ink_prev = ink_curr else: z_prev = page_tokens[p - 1] h_prev, w_prev = page_grid_dims[p - 1] ink_prev = page_ink_masks[p - 1] if page_ink_masks is not None else None # Get next page (self-fallback if last page of document) if p == doc_end - 1: z_next = z_curr # self-fallback h_next, w_next = h_curr, w_curr ink_next = ink_curr else: z_next = page_tokens[p + 1] h_next, w_next = page_grid_dims[p + 1] ink_next = page_ink_masks[p + 1] if page_ink_masks is not None else None e_p = self._process_triplet( z_prev, z_curr, z_next, h_prev, w_prev, h_curr, w_curr, h_next, w_next, detach_neighbors=detach_neighbors, ink_prev=ink_prev, ink_curr=ink_curr, ink_next=ink_next, record_meta={ "doc_start": doc_start, "doc_end": doc_end, "curr_page_index": p, "prev_page_index": p if p == doc_start else p - 1, "next_page_index": p if p == doc_end - 1 else p + 1, "prev_is_self_fallback": p == doc_start, "next_is_self_fallback": p == doc_end - 1, }, ) enriched.append(e_p) page_idx = doc_end return enriched def get_aux_loss(self) -> Optional[torch.Tensor]: """Return the mean auxiliary gate loss accumulated during the last forward.""" if self._aux_loss is None or self._aux_loss_terms <= 0: return None return self._aux_loss / float(self._aux_loss_terms) @torch.no_grad() def clone_init_from_vision_block(self, vision_block: nn.Module): """Clone QKV and FFN first-linear weights from a Qwen3.5 vision block. This ensures DocSEAM starts from a good feature space. The output projections remain at zero-init so the module is an exact no-op. Args: vision_block: a Qwen3_5VisionBlock with .attn.qkv, .mlp.linear_fc1, .norm1, .norm2. """ def _copy(dst, src): dst.data.copy_(src.data.to(dst.dtype)) def _copy_norm(dst_norm, src_norm): if hasattr(src_norm, "weight") and src_norm.weight is not None: _copy(dst_norm.weight, src_norm.weight) if hasattr(dst_norm, "bias") and dst_norm.bias is not None: if hasattr(src_norm, "bias") and src_norm.bias is not None: _copy(dst_norm.bias, src_norm.bias) else: dst_norm.bias.data.zero_() for layer in self.layers: # Clone QKV from vision block's fused qkv _copy(layer.qkv.weight, vision_block.attn.qkv.weight) if vision_block.attn.qkv.bias is not None: _copy(layer.qkv.bias, vision_block.attn.qkv.bias) else: layer.qkv.bias.data.zero_() # Clone FFN first linear _copy(layer.fc1.weight, vision_block.mlp.linear_fc1.weight) if vision_block.mlp.linear_fc1.bias is not None: _copy(layer.fc1.bias, vision_block.mlp.linear_fc1.bias) else: layer.fc1.bias.data.zero_() # Clone norms _copy_norm(layer.norm1, vision_block.norm1) _copy_norm(layer.norm2, vision_block.norm2)