"""Laya Vision's decision readout: the prompt rules and the head. Standalone: imports only ``torch``. Every user of the decision format renders and scores a question with this file, so a question is rendered and scored the same way everywhere; ``hf/prepare_hf_upload.py`` copies it into the upload directory beside the HF modeling code. Ported from Laya Vision (https://github.com/r33drichards/laya-vision, Apache-2.0): ``laya/common.py`` (``render_options``) and ``laya/vlm.py`` (``VLMDecisionModel``). Shape suffixes: B batch (one row per question), S sequence, D hidden size, K options (padded to the batch maximum), T question types. """ from __future__ import annotations import json from collections.abc import Callable, Sequence from typing import TypeVar import torch import torch.nn as nn QUESTION_TYPE_IDS = {"choice": 0, "score": 1, "noul": 2} NOUL_OPTIONS = ( "false: no, the statement does not hold", "true: yes, the statement holds", ) OPTIONS_CUE = "Options:" OPTION_BULLET = "- " OPTION_END = "\n" PADDED_LOGIT = -1e4 Prompt = TypeVar("Prompt") def render_options(question_type: str, criteria: Sequence[str] | None) -> list[str]: """Option texts in label order (Laya's ``render_options``).""" if question_type == "noul": return list(NOUL_OPTIONS) if question_type == "score": return [f"level {i}: {c}" for i, c in enumerate(criteria or ())] return list(criteria or ()) def render_state_text(context: str | None) -> str: """The state's text as Laya serializes it: a state ``{"image", "context"}`` becomes the JSON of its non-image keys, or nothing without a context.""" if not context: return "" return json.dumps({"context": context}, ensure_ascii=False) def render_question(question_type: str, instructions: str, state_text: str) -> str: """The user-turn text after the images: the state, then the typed question.""" question = f"{question_type} question: {instructions}" return f"{state_text}\n{question}" if state_text else question def option_end_id(encode: Callable[[str], list[int]]) -> int: """The token closing each option line, whose hidden state is read out. ``encode`` is the raw tokenizer without BOS / EOS. SentencePiece-style tokenizers prefix a bare newline with a space piece; it is dropped so the terminator is the newline token alone. """ ids = encode(OPTION_END) if len(ids) == 2: ids = ids[1:] if len(ids) != 1: raise ValueError( f"the option terminator must be one token, got {ids} for {OPTION_END!r}" ) return ids[0] def build_options_tail( encode: Callable[[str], list[int]], options: Sequence[str], order: Sequence[int], *, newline_id: int, max_option_tokens: int, ) -> tuple[list[int], list[int], int]: """Token ids of ``Options:`` and one line per option, in ``order``. Returns ``(tail, markers, span_start)``: ``markers[j]`` is the position in ``tail`` of the newline closing the j-th listed option, ``span_start`` the position where the option lines begin. Each option keeps at most ``max_option_tokens`` tokens. """ tail = encode(OPTIONS_CUE) + [newline_id] span_start = len(tail) markers = [] for i in order: text = OPTION_BULLET + options[i].replace(OPTION_END, " ") tail += encode(text)[:max_option_tokens] + [newline_id] markers.append(len(tail) - 1) return tail, markers, span_start def fit_state_text( render: Callable[[str], Prompt], num_tokens: Callable[[Prompt], int], state_text: str, *, tail_len: int, max_len: int, name: str = "question", ) -> Prompt: """``render(state_text)``, the state shortened (its start kept) until the prompt and the ``tail_len`` option tokens fit ``max_len``.""" prompt = render(state_text) while num_tokens(prompt) + tail_len > max_len and state_text: excess = num_tokens(prompt) + tail_len - max_len state_text = state_text[: max(0, len(state_text) - 4 * excess - 1)] prompt = render(state_text) if num_tokens(prompt) + tail_len > max_len: raise ValueError( f"{name}: question + options + images exceed max_len={max_len}" ) return prompt def calibrated_probs( logits_BK: torch.Tensor, question_type_B: torch.Tensor, temperature_T: torch.Tensor, ) -> torch.Tensor: """Option probabilities with one temperature per question type (``temperature_T`` indexed by ``QUESTION_TYPE_IDS``).""" temperature_B1 = temperature_T.to(logits_BK)[question_type_B][:, None] return torch.softmax(logits_BK / temperature_B1, dim=-1) class LayaDecisionHead(nn.Module): """Laya's ``VLMDecisionModel`` head over backbone hidden states ``[B, S, D]``. A question-type embedding is added to every hidden state, 2 bidirectional pre-norm transformer layers run over the row, the state at each option's closing newline is gathered, and a shared scorer (LayerNorm-Linear-GELU-Linear) gives one logit per option. """ def __init__(self, dim: int, *, num_layers: int = 2, dropout: float = 0.1): super().__init__() layer = nn.TransformerEncoderLayer( dim, max(1, dim // 64), 4 * dim, dropout, batch_first=True, norm_first=True ) self.layers = ( nn.TransformerEncoder(layer, num_layers, enable_nested_tensor=False) if num_layers > 0 else None ) self.type_emb = nn.Embedding(len(QUESTION_TYPE_IDS), dim) self.scorer = nn.Sequential( nn.LayerNorm(dim), nn.Linear(dim, dim), nn.GELU(), nn.Linear(dim, 1) ) def forward( self, hidden_BSD: torch.Tensor, attention_mask_BS: torch.Tensor, marker_pos_BK: torch.Tensor, marker_mask_BK: torch.Tensor, question_type_B: torch.Tensor, ) -> torch.Tensor: """Option logits ``[B, K]`` in float32, padded options at ``PADDED_LOGIT``.""" # The head runs in the backbone's compute dtype (bf16 under FSDP mixed # precision or a bf16 HF load). h_BSD = hidden_BSD + self.type_emb(question_type_B)[:, None, :].to( hidden_BSD.dtype ) if self.layers is not None: h_BSD = self.layers(h_BSD, src_key_padding_mask=~attention_mask_BS.bool()) idx_BKD = marker_pos_BK.clamp(min=0)[:, :, None].expand(-1, -1, h_BSD.size(-1)) m_BKD = torch.gather(h_BSD, 1, idx_BKD) logits_BK = self.scorer(m_BKD).squeeze(-1).float() return logits_BK.masked_fill(~marker_mask_BK.bool(), PADDED_LOGIT)