| from __future__ import annotations |
|
|
| from typing import Dict, Optional |
|
|
| import torch |
|
|
|
|
| def sampled_token_opd_loss( |
| student_logp: torch.Tensor, |
| teacher_logp: torch.Tensor, |
| valid_mask: Optional[torch.Tensor] = None, |
| advantage_clip: float = 10.0, |
| ) -> tuple[torch.Tensor, Dict[str, torch.Tensor]]: |
| """Policy-gradient style sampled-token OPD loss. |
| |
| Teacher and student tensors must score the exact same response token IDs. |
| The advantage is detached so gradients only flow through student_logp. |
| """ |
| if student_logp.shape != teacher_logp.shape: |
| raise ValueError( |
| f"logp shape mismatch: student={tuple(student_logp.shape)} " |
| f"teacher={tuple(teacher_logp.shape)}" |
| ) |
| if valid_mask is None: |
| valid_mask = torch.ones_like(student_logp, dtype=torch.bool) |
| if valid_mask.shape != student_logp.shape: |
| raise ValueError("valid_mask must have the same shape as log-probabilities") |
| if not bool(valid_mask.any()): |
| raise ValueError("sampled-token OPD received no valid response tokens") |
|
|
| raw_advantage = teacher_logp.float() - student_logp.detach().float() |
| advantage = raw_advantage.clamp(-advantage_clip, advantage_clip) |
| token_loss = -(advantage * student_logp.float()) |
| loss = token_loss.masked_select(valid_mask).mean() |
|
|
| selected_raw = raw_advantage.masked_select(valid_mask) |
| selected_adv = advantage.masked_select(valid_mask) |
| clip_fraction = (selected_raw.abs() > advantage_clip).float().mean() |
| stats = { |
| "advantage_mean": selected_adv.mean().detach(), |
| "advantage_std": selected_adv.std(unbiased=False).detach(), |
| "advantage_positive_fraction": (selected_adv > 0).float().mean().detach(), |
| "advantage_clip_fraction": clip_fraction.detach(), |
| "student_logp_mean": student_logp.float().masked_select(valid_mask).mean().detach(), |
| "teacher_logp_mean": teacher_logp.float().masked_select(valid_mask).mean().detach(), |
| } |
| return loss, stats |
|
|
|
|
| def response_token_logps( |
| logits: torch.Tensor, |
| response_ids: torch.Tensor, |
| response_start: int, |
| ) -> torch.Tensor: |
| """Gather next-token log-probabilities for a response appended to a prompt. |
| |
| logits has shape [B, prompt_len + response_len, vocab]. response_start is |
| the prompt length. The returned tensor has shape [B, response_len]. |
| """ |
| if logits.dim() != 3 or response_ids.dim() != 2: |
| raise ValueError("Expected logits [B,L,V] and response_ids [B,T]") |
| response_len = response_ids.shape[1] |
| if response_len < 1: |
| raise ValueError("response_ids must not be empty") |
| start = response_start - 1 |
| end = start + response_len |
| if start < 0 or end > logits.shape[1]: |
| raise ValueError( |
| f"Invalid response slice start={start}, end={end}, logits_len={logits.shape[1]}" |
| ) |
| prediction_logits = logits[:, start:end, :].float() |
| log_probs = prediction_logits.log_softmax(dim=-1) |
| return log_probs.gather(-1, response_ids.unsqueeze(-1)).squeeze(-1) |
|
|
|
|