File size: 3,649 Bytes
8cbfa56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"""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


@dataclass(frozen=True)
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