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 
 
 
 
 
 
 
 
 
09ec98f
b8d0a87
09ec98f
 
 
 
 
bcd13a7
 
 
 
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
"""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