"""Constrained CE over answer codes (matches serving softmax). Full-vocab next-token CE left relative Y/N logits dominated by the base prior (eval collapse: all Noul → Y). Scoring only code tokens aligns train with infer. Also: Noul consistency (P(yes|Q)+P(yes|¬Q)→1), optional binary head CE on last-token hidden, and Score ordinal EMD (levels ordered). """ from __future__ import annotations from typing import Any import torch import torch.nn.functional as F def _answer_pos(shift_labels: torch.Tensor) -> int | None: pos = (shift_labels != -100).nonzero(as_tuple=True)[0] if len(pos) == 0: return None return int(pos[0].item()) def code_token_loss( logits: torch.Tensor, labels: torch.Tensor, code_token_ids: torch.Tensor, n_codes: torch.Tensor, soft_labels: torch.Tensor, *, use_soft: bool, sample_weight: torch.Tensor | None = None, force_soft_mask: torch.Tensor | None = None, ) -> torch.Tensor: """Softmax CE / soft-KL over allowed code ids at the answer position. ``logits``: [B, T, V]; ``labels``: [B, T] with -100 mask (gold at the answer index). HF shift: predict token t from logits[:, t-1]. Soft path is KL(teacher‖student) up to H(teacher). ``force_soft_mask``: per-row override to soft-KL (Score rows). """ shift_logits = logits[:, :-1, :].contiguous() shift_labels = labels[:, 1:].contiguous() batch = shift_logits.size(0) losses: list[torch.Tensor] = [] weights: list[torch.Tensor] = [] for b in range(batch): p = _answer_pos(shift_labels[b]) if p is None: continue k = int(n_codes[b].item()) if k < 1: continue ids = code_token_ids[b, :k].long() code_logits = shift_logits[b, p, ids] row_soft = use_soft if force_soft_mask is not None and int(force_soft_mask[b].item()) > 0: row_soft = True if row_soft: target = soft_labels[b, :k].float() target = target / target.sum().clamp_min(1e-8) log_p = F.log_softmax(code_logits, dim=-1) loss_b = -(target * log_p).sum() else: gold_idx = int(soft_labels[b, :k].argmax().item()) loss_b = F.cross_entropy( code_logits.unsqueeze(0), torch.tensor( [gold_idx], device=code_logits.device, dtype=torch.long, ), ) losses.append(loss_b) if sample_weight is not None: weights.append(sample_weight[b].float()) else: weights.append( torch.ones((), device=code_logits.device) ) if not losses: return logits.sum() * 0.0 stacked = torch.stack(losses) w = torch.stack(weights) return (stacked * w).sum() / w.sum().clamp_min(1e-8) def ordinal_emd_loss( logits: torch.Tensor, labels: torch.Tensor, code_token_ids: torch.Tensor, n_codes: torch.Tensor, soft_labels: torch.Tensor, is_score: torch.Tensor, *, sample_weight: torch.Tensor | None = None, ) -> torch.Tensor: """1D Earth-mover distance on ordered Score levels. Penalizes mass 3 levels off more than 1: W1 = Σ|CDF_p − CDF_t|. Only rows with ``is_score>0`` contribute. """ shift_logits = logits[:, :-1, :].contiguous() shift_labels = labels[:, 1:].contiguous() batch = shift_logits.size(0) losses: list[torch.Tensor] = [] weights: list[torch.Tensor] = [] for b in range(batch): if int(is_score[b].item()) <= 0: continue p = _answer_pos(shift_labels[b]) if p is None: continue k = int(n_codes[b].item()) if k < 2: continue ids = code_token_ids[b, :k].long() code_logits = shift_logits[b, p, ids] pred = F.softmax(code_logits.float(), dim=-1) target = soft_labels[b, :k].float() target = target / target.sum().clamp_min(1e-8) # Also expected |level−gold| so hard-off-by-3 is explicit. levels = torch.arange( k, device=code_logits.device, dtype=pred.dtype ) gold = float((target * levels).sum().item()) mae = (pred * (levels - gold).abs()).sum() emd = (pred.cumsum(0) - target.cumsum(0)).abs().sum() losses.append(emd + mae) if sample_weight is not None: weights.append(sample_weight[b].float()) else: weights.append( torch.ones((), device=code_logits.device) ) if not losses: return logits.sum() * 0.0 stacked = torch.stack(losses) w = torch.stack(weights) return (stacked * w).sum() / w.sum().clamp_min(1e-8) def code_yes_probs( logits: torch.Tensor, labels: torch.Tensor, code_token_ids: torch.Tensor, n_codes: torch.Tensor, yes_idx: torch.Tensor, ) -> torch.Tensor: """P(yes) from constrained softmax; -1 where not applicable.""" shift_logits = logits[:, :-1, :].contiguous() shift_labels = labels[:, 1:].contiguous() batch = shift_logits.size(0) out = torch.full( (batch,), -1.0, device=logits.device, dtype=logits.dtype ) for b in range(batch): yi = int(yes_idx[b].item()) if yes_idx is not None else -1 if yi < 0: continue p = _answer_pos(shift_labels[b]) if p is None: continue k = int(n_codes[b].item()) if k < 2 or yi >= k: continue ids = code_token_ids[b, :k].long() probs = F.softmax(shift_logits[b, p, ids].float(), dim=-1) out[b] = probs[yi] return out def consistency_loss( p_yes_q: torch.Tensor, p_yes_neg: torch.Tensor, has_neg: torch.Tensor, ) -> torch.Tensor: """(P(yes|Q) + P(yes|¬Q) − 1)^2 on rows with a negation twin.""" mask = (has_neg > 0) & (p_yes_q >= 0) & (p_yes_neg >= 0) if not mask.any(): return p_yes_q.sum() * 0.0 diff = p_yes_q[mask] + p_yes_neg[mask] - 1.0 return (diff * diff).mean() def trace_token_loss( logits: torch.Tensor, trace_labels: torch.Tensor, ) -> torch.Tensor: """Full-vocab CE on rationale tokens (Path A L_trace). ``trace_labels``: [B, T] with -100 mask; only rationale positions supervised. HF shift: predict token t from logits[:, t-1]. """ shift_logits = logits[:, :-1, :].contiguous() shift_labels = trace_labels[:, 1:].contiguous() if (shift_labels != -100).sum() == 0: return logits.sum() * 0.0 return F.cross_entropy( shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1), ignore_index=-100, ) class CodeTokenTrainer: """Lazy wrapper — real subclass built on first instantiate. Avoids importing transformers at module import time (unit tests). """ def __new__(cls, *args: Any, **kwargs: Any): return _build_trainer_class()(*args, **kwargs) _TRAINER_CLS: type | None = None def _build_trainer_class() -> type: global _TRAINER_CLS if _TRAINER_CLS is not None: return _TRAINER_CLS from transformers import Trainer class _CodeTokenTrainer(Trainer): """Trainer that CE-supervises only the allowed answer codes.""" def __init__( self, *args: Any, use_soft_ce: bool = False, train_sampler: Any | None = None, consistency_weight: float = 0.0, binary_head: Any | None = None, binary_head_weight: float = 0.0, binary_head_balanced: bool = False, score_ordinal_weight: float = 0.0, trace_loss_weight: float = 0.0, **kwargs: Any, ) -> None: self._custom_train_sampler = train_sampler super().__init__(*args, **kwargs) self.use_soft_ce = bool(use_soft_ce) self.consistency_weight = float(consistency_weight) self.binary_head = binary_head self.binary_head_weight = float(binary_head_weight) self.binary_head_balanced = bool(binary_head_balanced) self.score_ordinal_weight = float(score_ordinal_weight) self.trace_loss_weight = float(trace_loss_weight) def _get_train_sampler(self, train_dataset: Any = None): if self._custom_train_sampler is not None: return self._custom_train_sampler try: return super()._get_train_sampler(train_dataset) except TypeError: return super()._get_train_sampler() def compute_loss( self, model: Any, inputs: dict[str, Any], return_outputs: bool = False, num_items_in_batch: int | None = None, ): code_token_ids = inputs.pop("code_token_ids") n_codes = inputs.pop("n_codes") soft_labels = inputs.pop("soft_labels") sample_weight = inputs.pop("sample_weight", None) yes_idx = inputs.pop("yes_idx", None) has_neg = inputs.pop("has_neg", None) neg_input_ids = inputs.pop("neg_input_ids", None) neg_attention = inputs.pop("neg_attention_mask", None) neg_labels = inputs.pop("neg_labels", None) neg_soft = inputs.pop("neg_soft_labels", None) trace_labels = inputs.pop("trace_labels", None) inputs.pop("label_id", None) inputs.pop("has_soft", None) is_noul = inputs.pop("is_noul", None) is_score = inputs.pop("is_score", None) force_soft = inputs.pop("force_soft", None) inputs.pop("has_trace", None) labels = inputs.get("labels") outputs = model(**inputs) loss = code_token_loss( outputs.logits, labels, code_token_ids, n_codes, soft_labels, use_soft=self.use_soft_ce, sample_weight=sample_weight, force_soft_mask=force_soft, ) # Path A: λ_t L_trace on short rationale tokens. if ( self.trace_loss_weight > 0 and trace_labels is not None ): t_loss = trace_token_loss( outputs.logits, trace_labels ) loss = loss + self.trace_loss_weight * t_loss # Score ordinal: EMD + expected |level−teacher| (off-by-3 > 1). if ( self.score_ordinal_weight > 0 and is_score is not None and (is_score > 0).any() ): ord_loss = ordinal_emd_loss( outputs.logits, labels, code_token_ids, n_codes, soft_labels, is_score, sample_weight=sample_weight, ) loss = loss + self.score_ordinal_weight * ord_loss # Negation consistency + CE on ¬Q (dual forward). if ( self.consistency_weight > 0 and neg_input_ids is not None and has_neg is not None and (has_neg > 0).any() ): neg_out = model( input_ids=neg_input_ids, attention_mask=neg_attention, ) loss = loss + code_token_loss( neg_out.logits, neg_labels, code_token_ids, n_codes, neg_soft if neg_soft is not None else soft_labels, use_soft=self.use_soft_ce, sample_weight=sample_weight, ) if yes_idx is not None: p_q = code_yes_probs( outputs.logits, labels, code_token_ids, n_codes, yes_idx, ) p_n = code_yes_probs( neg_out.logits, neg_labels, code_token_ids, n_codes, yes_idx, ) cons = consistency_loss(p_q, p_n, has_neg) loss = loss + self.consistency_weight * cons # Optional dedicated binary head on last non-pad hidden. if ( self.binary_head is not None and self.binary_head_weight > 0 and is_noul is not None and yes_idx is not None ): hidden = outputs.hidden_states if hidden is None: # Re-forward with hidden states if model omitted them. outputs2 = model( **{ k: v for k, v in inputs.items() if k in ("input_ids", "attention_mask") }, output_hidden_states=True, ) hidden = outputs2.hidden_states if hidden is not None: h = hidden[-1] attn = inputs["attention_mask"] # Last non-pad index per row. lengths = attn.long().sum(dim=1) - 1 b_idx = torch.arange(h.size(0), device=h.device) pooled = h[b_idx, lengths.clamp_min(0)] logits2 = self.binary_head(pooled) # Target: 1 if gold is yes-code else 0. gold = soft_labels.argmax(dim=-1) target = (gold == yes_idx.clamp_min(0)).long() # Only noul rows. mask = is_noul > 0 if mask.any(): logits_m = logits2[mask] target_m = target[mask] weight = None if self.binary_head_balanced: # Inverse-frequency class weights so Y/N # each contribute ~half the binary CE # (train aux; LM Y/N remains serving). n0 = (target_m == 0).sum().clamp_min(1) n1 = (target_m == 1).sum().clamp_min(1) tot = (n0 + n1).to(logits_m.dtype) weight = torch.stack( [ tot / (2.0 * n0.to(logits_m.dtype)), tot / (2.0 * n1.to(logits_m.dtype)), ] ) bce = F.cross_entropy( logits_m, target_m, weight=weight ) loss = ( loss + self.binary_head_weight * bce ) return (loss, outputs) if return_outputs else loss _TRAINER_CLS = _CodeTokenTrainer return _TRAINER_CLS