Download code/pocket_math/losses.py from Palaestra/pocket-math-ops: direct link, hf CLI and curl.
- Browser
- Download file 3.65 kB
-
https://huggingface.co/datasets/Palaestra/pocket-math-ops/resolve/main/code/pocket_math/losses.py
- Command line
-
hf download hf://datasets/Palaestra/pocket-math-ops/code/pocket_math/losses.py
-
curl -L -o losses.py https://huggingface.co/datasets/Palaestra/pocket-math-ops/resolve/main/code/pocket_math/losses.py
3.65 kB
| """Token-level losses. Distillation and RL share one clipped policy-gradient loss; only the advantage differs. | |
| Distillation (on-policy, reverse KL): advantage of token t is log p_teacher(t) - log p_student(t) | |
| (Lu et al. 2025, "On-Policy Distillation", Thinking Machines). RL (DAPO, Yu et al. 2025): the | |
| group-normalised verifier reward of the whole answer, given to each of its tokens. Both are | |
| summed over tokens and divided by the batch's token count (token-level normalisation). | |
| """ | |
| from __future__ import annotations | |
| from collections import defaultdict | |
| from dataclasses import dataclass | |
| import torch | |
| import torch.nn.functional as F | |
| class PGConfig: | |
| clip_low: float = 0.2 | |
| clip_high: float = 0.28 | |
| tis_cap: float = 2.0 | |
| kl_weight: float = 1.0 | |
| reward_weight: float = 0.0 | |
| adv_clip: float = 5.0 | |
| def token_advantages(cfg: PGConfig, lp: torch.Tensor, teacher_lp: torch.Tensor | None, | |
| seq_adv: float | None) -> torch.Tensor: | |
| adv = torch.zeros_like(lp) | |
| if cfg.kl_weight and teacher_lp is not None: | |
| adv = adv + cfg.kl_weight * (teacher_lp - lp.detach()).clamp(-cfg.adv_clip, cfg.adv_clip) | |
| if cfg.reward_weight and seq_adv is not None: | |
| adv = adv + cfg.reward_weight * seq_adv | |
| return adv | |
| def pg_loss_sum(cfg: PGConfig, lp: torch.Tensor, adv: torch.Tensor, sampler_lp: torch.Tensor, | |
| mask: torch.Tensor, lp_old: torch.Tensor | None = None) -> tuple[torch.Tensor, dict[str, float]]: | |
| """Sum over masked tokens of the clipped PG loss, with truncated importance sampling | |
| (Yao et al. 2025) correcting for the generator's numerics differing from the trainer's.""" | |
| old = lp.detach() if lp_old is None else lp_old | |
| ratio = torch.exp(lp - old) | |
| pg = -torch.minimum(ratio * adv, ratio.clamp(1 - cfg.clip_low, 1 + cfg.clip_high) * adv) | |
| behaviour = torch.where(torch.isnan(sampler_lp), old, sampler_lp) | |
| w = torch.exp(old - behaviour).clamp(max=cfg.tis_cap) | |
| m = mask.to(lp.dtype) | |
| loss = (w * pg * m).sum() | |
| with torch.no_grad(): | |
| n = m.sum().clamp(min=1) | |
| stats = { | |
| "tis_mean": float((w * m).sum() / n), | |
| "tis_capped": float(((w >= cfg.tis_cap) * m).sum() / n), | |
| "ratio_clipped": float((((ratio < 1 - cfg.clip_low) | (ratio > 1 + cfg.clip_high)) * m).sum() / n), | |
| } | |
| return loss, stats | |
| def sft_loss_sum(lp: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: | |
| return -(lp * mask.to(lp.dtype)).sum() | |
| def dpo_loss(lp_chosen: torch.Tensor, lp_rejected: torch.Tensor, ref_chosen: torch.Tensor, | |
| ref_rejected: torch.Tensor, beta: float) -> torch.Tensor: | |
| """Sequence log-probs (sums over the continuation tokens) in, scalar loss out.""" | |
| return -F.logsigmoid(beta * ((lp_chosen - ref_chosen) - (lp_rejected - ref_rejected))) | |
| def group_advantages(rewards: list[float], groups: list[str], std_norm: bool = True, | |
| eps: float = 1e-6) -> list[float]: | |
| """GRPO advantage: reward minus its group's mean, divided by the group's std when std_norm.""" | |
| by_group: dict[str, list[float]] = defaultdict(list) | |
| for r, g in zip(rewards, groups, strict=True): | |
| by_group[g].append(r) | |
| stats = {} | |
| for g, rs in by_group.items(): | |
| t = torch.tensor(rs, dtype=torch.float64) | |
| stats[g] = (float(t.mean()), float(t.std(unbiased=False))) | |
| out = [] | |
| for r, g in zip(rewards, groups, strict=True): | |
| mean, std = stats[g] | |
| out.append((r - mean) / (std + eps) if std_norm else r - mean) | |
| return out | |