"""LM helpers: run the decoder, then the 248k-vocab head ONLY at the positions that are scored (a full-sequence head is most of the step time and memory on the M4).""" from __future__ import annotations import torch import torch.nn.functional as F def parts(model): m = model.get_base_model() if hasattr(model, "get_base_model") else model return m.model, m.lm_head def hidden(model, attention_mask, input_ids=None, inputs_embeds=None): dec, _ = parts(model) return dec(input_ids=input_ids, inputs_embeds=inputs_embeds, attention_mask=attention_mask, use_cache=False).last_hidden_state def scored_logits(model, h: torch.Tensor, labels: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: """h (B,T,D), labels (B,T) with -100 = not scored. Returns (logits (N,V) fp32, targets (N,)) for next-token prediction at every scored position.""" _, head = parts(model) y = labels[:, 1:] m = y != -100 return head(h[:, :-1][m]).float(), y[m] def ce(model, h, labels) -> torch.Tensor: lg, y = scored_logits(model, h, labels) return F.cross_entropy(lg, y)