vigneshwar234 commited on
Commit
0f2c365
·
verified ·
1 Parent(s): 8b3bcfa

Add source: tmt/training/loss.py

Browse files
Files changed (1) hide show
  1. tmt/training/loss.py +57 -0
tmt/training/loss.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ loss.py — TMT combined training loss.
3
+
4
+ Total loss = cross_entropy(logits, targets)
5
+ + 0.1 * exit_gate_auxiliary_loss
6
+
7
+ The auxiliary loss encourages exit gates to be decisive (confident 0 or 1)
8
+ without forcing specific tokens to exit. The coefficient 0.1 keeps it small
9
+ enough not to override the language modelling objective.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ from typing import List, Tuple
14
+
15
+ import torch
16
+ import torch.nn.functional as F
17
+ from torch import Tensor
18
+
19
+
20
+ def compute_loss(
21
+ logits: Tensor,
22
+ targets: Tensor,
23
+ confidences: List[Tensor],
24
+ exit_gate_coeff: float = 0.1,
25
+ ignore_index: int = -100,
26
+ ) -> Tuple[Tensor, Tensor, Tensor]:
27
+ """
28
+ Args:
29
+ logits: (B, S, V) model output logits
30
+ targets: (B, S) integer ground-truth token ids
31
+ confidences: list of (B, S) per-layer gate confidence scores
32
+ exit_gate_coeff: weight for auxiliary exit gate loss
33
+ ignore_index: token id to exclude from cross-entropy
34
+
35
+ Returns:
36
+ total_loss: scalar
37
+ ce_loss: scalar cross-entropy component
38
+ gate_loss: scalar auxiliary gate component
39
+ """
40
+ B, S, V = logits.shape
41
+
42
+ # Standard next-token cross-entropy (flat over B*S)
43
+ ce_loss = F.cross_entropy(
44
+ logits.reshape(B * S, V),
45
+ targets.reshape(B * S),
46
+ ignore_index=ignore_index,
47
+ )
48
+
49
+ # Exit gate auxiliary: encourage decisiveness
50
+ # Loss = -E[|conf - 0.5|] — penalise uncertainty
51
+ gate_loss = torch.zeros(1, device=logits.device)
52
+ for conf in confidences:
53
+ gate_loss = gate_loss + -(conf - 0.5).abs().mean()
54
+ gate_loss = gate_loss / max(len(confidences), 1)
55
+
56
+ total_loss = ce_loss + exit_gate_coeff * gate_loss
57
+ return total_loss, ce_loss, gate_loss