Cross-Entropy Loss for Language Model Training #
Implements numerically stable cross-entropy loss for teacher-forcing:
loss = -log(softmax(logits)[target])
= -logits[target] + log(sum(exp(logits - max(logits))))
Backward:
dLogits[i] = softmax(logits)[i] - (i == target ? 1 : 0)
This elegant form means the backward pass is just softmax minus one-hot.
Forward: Cross-Entropy Loss #
GPU kernel: Compute cross-entropy loss for a single token.
Uses two-pass approach for numerical stability:
- Find max(logits) via parallel reduction
- Compute log-sum-exp and loss
Input: logits [vocabSize], target [1] (u32 token ID) Output: loss [1] (scalar float)
Uses workgroup shared memory for reductions.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Execute cross-entropy loss forward. Returns loss value by reading back from GPU.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Cross-entropy forward with GPU-side loss accumulation. Adds the per-token loss to an accumulator buffer instead of overwriting. This allows batching all tokens' loss computation without CPU readback.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Execute cross-entropy forward with GPU-side loss accumulation. Call this per-token; loss accumulates on GPU. Read once at end of example.
Equations
- One or more equations did not get rendered due to their size.
Instances For
Backward: dLogits = softmax(logits) - one_hot(target) #
GPU kernel: Compute gradient of cross-entropy loss w.r.t. logits.
dLogits[i] = softmax(logits)[i] - (i == target ? 1 : 0)
Two phases:
- Compute max and sum-exp (same as forward) via shared memory
- Each thread computes its softmax value and subtracts one-hot
Input: logits [vocabSize], target [1] (u32) Output: dLogits [vocabSize]
Equations
- One or more equations did not get rendered due to their size.
Instances For
Execute cross-entropy backward: dLogits = softmax(logits) - one_hot(target)
Equations
- One or more equations did not get rendered due to their size.