code-switch-mtp / src /measure /model_handle.py
Anupam-Rawat-IITB's picture
Add code, result files and documentation
3bbd5dd verified
Raw History Blame Contribute Delete
8.15 kB
"""Uniform next-token-distribution interface over causal and encoder-decoder models.
Sarvam-1 and Llama-3.2-1B are causal decoder-only models: input_ids in,
next-token logits at the last position out. ByT5-large is an
encoder-decoder byte-level model with no causal-LM head of its own; it is
driven here by mirroring the growing sequence into both the encoder input
and the decoder input (teacher forcing against itself), a standard trick
for scoring/next-token estimation with T5-family models. This gives ByT5
bidirectional encoder access to the same prefix a causal model only sees
causally, plus causal decoder self-attention over it -- not architecturally
identical to L1-L4's next-token distributions, only comparable at the level
of "a next-token distribution conditioned on this prefix". Documented as a
limitation in docs/experiment-log.md, not silently treated as equivalent.
That mirroring is selectable: SEQ2SEQ_MODE_CAUSAL starves the encoder so
the decoder's causal self-attention is the only route to the prefix, which
is the comparable-to-L1-L4 driving mode. MIRRORED remains the default so
Phase 2's committed results stay reproducible.
"""
import unicodedata
from dataclasses import dataclass
from typing import Optional
import torch
import torch.nn.functional as F
# How an encoder-decoder model is driven to yield a next-token distribution.
# MIRRORED puts the growing prefix in both encoder and decoder inputs; the
# encoder's bidirectional self-attention then sees the whole prefix at once,
# which a causal decoder-only model never does. CAUSAL_DECODER_ONLY starves
# the encoder (a single pad token) so the decoder's causal self-attention is
# the only path to the prefix, matching what L1-L4's causal models get.
SEQ2SEQ_MODE_MIRRORED = "mirrored"
SEQ2SEQ_MODE_CAUSAL = "causal_decoder_only"
# Cap on rows per forward pass in batched queries. Top-K marginalization can
# ask for ~100 rows at once, and on byte-level sequences a row is hundreds of
# tokens long, which overruns an 11GB card. Chunking is purely a memory
# measure: the concatenated result is identical to one large batch.
BATCH_CHUNK_SIZE = 16
@dataclass
class TokenizedText:
"""A tokenized sentence plus enough bookkeeping to locate word boundaries.
Attributes:
ids: token ids, shape (seq_len,).
offsets: (start_char, end_char) per token in the original text, or
None if the tokenizer/mode does not support offset mapping (byte
mode always supports it trivially, computed here directly).
text: the original text.
"""
ids: torch.Tensor
offsets: list
text: str
class ModelHandle:
"""Wraps one (model, tokenizer) pair behind next_token_logits() and encode().
Args:
model: a loaded HF model, already .to(device) and in eval mode.
tokenizer: its tokenizer.
device: e.g. "cuda:0".
is_seq2seq: True for ByT5 (encoder-decoder), False for causal decoders.
is_byte_level: True for ByT5, where "tokens" are raw UTF-8 bytes --
changes how word-boundary offsets are computed (trivial byte
counting instead of a fast tokenizer's offset_mapping).
seq2seq_mode: SEQ2SEQ_MODE_MIRRORED (default, what Phase 2's
committed results were produced with) or SEQ2SEQ_MODE_CAUSAL.
Ignored for causal decoder-only models.
"""
def __init__(
self,
model,
tokenizer,
device: str,
is_seq2seq: bool,
is_byte_level: bool,
seq2seq_mode: str = SEQ2SEQ_MODE_MIRRORED,
) -> None:
self.model = model
self.tokenizer = tokenizer
self.device = device
self.is_seq2seq = is_seq2seq
self.is_byte_level = is_byte_level
self.seq2seq_mode = seq2seq_mode
def _encoder_input_for(self, decoder_batch: torch.Tensor) -> torch.Tensor:
"""Encoder input matching decoder_batch's batch size, per the configured mode.
decoder_batch: (B, T). Returns (B, T) under MIRRORED, or (B, 1) of pad
ids under CAUSAL_DECODER_ONLY -- a minimal encoder input carries no
prefix content, so cross-attention cannot leak it to the decoder.
"""
if self.seq2seq_mode == SEQ2SEQ_MODE_MIRRORED:
return decoder_batch
pad_id = self.tokenizer.pad_token_id
return torch.full((decoder_batch.shape[0], 1), pad_id, dtype=torch.long, device=decoder_batch.device)
def encode(self, text: str) -> TokenizedText:
"""Tokenize text, recovering per-token (start, end) character offsets."""
text = unicodedata.normalize("NFC", text)
if self.is_byte_level:
# one token per UTF-8 byte; offsets are in bytes, not characters --
# word-boundary detection for this condition works on the byte
# string directly (see src/measure/boundary.py), not on `text`.
ids = self.tokenizer(text, return_tensors="pt").input_ids[0]
byte_text = text.encode("utf-8")
offsets = [(i, i + 1) for i in range(len(byte_text))]
# tokenizer appends an end-of-sequence token with no byte span
if len(offsets) < len(ids):
offsets += [(len(byte_text), len(byte_text))] * (len(ids) - len(offsets))
return TokenizedText(ids=ids.to(self.device), offsets=offsets, text=text)
encoding = self.tokenizer(text, return_tensors="pt", return_offsets_mapping=True)
ids = encoding.input_ids[0]
offsets = encoding.offset_mapping[0].tolist()
return TokenizedText(ids=ids.to(self.device), offsets=offsets, text=text)
@torch.no_grad()
def next_token_logits(self, prefix_ids: torch.Tensor) -> torch.Tensor:
"""Given prefix_ids (1D LongTensor, on self.device), return logits over the vocab
for the token immediately following the prefix. Shape: (vocab_size,).
"""
prefix_ids = prefix_ids.unsqueeze(0) # (1, T)
if self.is_seq2seq:
out = self.model(input_ids=self._encoder_input_for(prefix_ids), decoder_input_ids=prefix_ids)
else:
out = self.model(input_ids=prefix_ids)
return out.logits[0, -1, :]
@torch.no_grad()
def next_token_logprobs(self, prefix_ids: torch.Tensor) -> torch.Tensor:
return F.log_softmax(self.next_token_logits(prefix_ids), dim=-1)
@torch.no_grad()
def sample_next_token(self, prefix_ids: torch.Tensor, generator: Optional[torch.Generator] = None) -> int:
"""Ancestral-sample one token from p(next | prefix_ids) at temperature 1, no truncation."""
probs = F.softmax(self.next_token_logits(prefix_ids), dim=-1)
return int(torch.multinomial(probs, 1, generator=generator).item())
@torch.no_grad()
def next_token_logits_batch(self, prefix_batch: torch.Tensor) -> torch.Tensor:
"""Batched version of next_token_logits: prefix_batch (B, T) -> logits (B, vocab_size).
Used for top-K marginalization (one batch row per candidate
continuation) and Monte Carlo rollouts (one batch row per sample) --
both need many next-token queries against sequences of the same
length, which a single batched forward pass answers far more
cheaply than one call per row on this hardware.
"""
chunks = []
for start in range(0, prefix_batch.shape[0], BATCH_CHUNK_SIZE):
sub = prefix_batch[start : start + BATCH_CHUNK_SIZE]
if self.is_seq2seq:
out = self.model(input_ids=self._encoder_input_for(sub), decoder_input_ids=sub)
else:
out = self.model(input_ids=sub)
chunks.append(out.logits[:, -1, :])
return torch.cat(chunks, dim=0)
@torch.no_grad()
def sample_next_token_batch(self, prefix_batch: torch.Tensor, generator: Optional[torch.Generator] = None) -> torch.Tensor:
"""Ancestral-sample one token per row of prefix_batch (B, T) -> (B,) token ids."""
probs = F.softmax(self.next_token_logits_batch(prefix_batch), dim=-1)
return torch.multinomial(probs, 1, generator=generator).squeeze(-1)