# Candidate-only supervised loss

Source: https://docs.surogate.ai/engine/reference/candidate-loss/

With the [offline-sidecar distillation path](/engine/guides/distillation/) you can train hard-label classification over a
candidate set you supply. The default, which matches earlier behavior, is
`candidate_objective: cross_entropy`. For each supervised position with target
token `y` and candidate token IDs `S`, the loss is:

```text
L = logsumexp(logits[S]) - logits[y]
```

Vocabulary tokens outside the candidate set get exactly zero gradient. Ignored target
positions (`-100`) contribute neither loss nor gradient. This mode uses no
teacher, teacher probabilities, generated reasoning or reinforcement
learning. With candidate mode off, the standard SFT loss applies. The
data-parallel LoRA normalization correction described below is separate and also applies
to ordinary token-normalized SFT.

```yaml
distillation:
  candidate_only: true
  candidate_objective: cross_entropy  # default; also brier or rps
  top_k: 8          # padded candidate-set width, not a model-selected top-k
  temperature: 1.0
  kd_weight: 1.0
  ce_weight: 0.0
eval_steps: 0
```

The candidate IDs travel in the existing [`.kd` sidecar format](/engine/guides/distillation/#the-kd-sidecar-format), aligned to the
shifted target positions in each token shard. `-1` pads shorter candidate sets.
The sidecar logprob field is unused, so zeros are fine. Candidate IDs must be
unique and in the vocabulary, must include the gold token, and need at least two
valid entries. They are validated before GPU workers are dispatched. Supply the full
candidate set; a top-k approximation from model logits is the wrong input.

The native `step_with_kd(..., candidate_only=True)` API requires the
temperature and weights shown above. The flag is set on both the forward and
backward execution requests. Forward loss, valid counts and candidate accuracy
are computed over the restricted set, and backward writes gradients that are sparse
over the vocabulary into the dense LM-head gradient buffer.


## Brier and ordered RPS

Set `candidate_objective: brier` or `candidate_objective: rps` to train with a proper
score against the same gold-token one-hot target. Both objectives require
`lora: true` ([LoRA settings](/engine/reference/config/#lora-settings)) and `recipe: fp8_hybrid` ([recipes](/engine/reference/config/#mixed-precision--recipe-options)); the configuration and the native
training binding enforce this. They reject expert parallelism before
collective dispatch, while candidate CE keeps its existing expert-parallel behavior.
They accept 2–255 actual allowed candidates per supervised
row, even when a sidecar has more padding slots. Candidate CE
still allows up to 1024 slots/candidates.

For candidate-normalized probabilities `p`, target indicator `t`, and actual
allowed count `C`:

```text
Brier = sum_i (p_i - t_i)^2
RPS   = sum_{k=1}^{C-1} (sum_{i<=k} p_i - sum_{i<=k} t_i)^2 / (C - 1)
```

Brier uses the multiclass sum convention, so for two labels it is twice the scalar
binary Brier score. RPS takes the order of the non-padding sidecar IDs as the
ordinal order. Interspersed `-1` slots add no boundary and do not change the
`C-1` denominator. Never sort these IDs by token ID or teacher probability.
Use RPS only when a whole batch or run is ordinal. The objective flag is global,
so it cannot pick a score per row, and it is the wrong choice for unordered Choice
labels. This page reconstructs the proper scores from their definitions; it makes no
claim about TypeSafe's unpublished RLCD implementation.

All candidate probabilities, CDFs, objective sums and intermediate derivatives
are FP32. The final dense LM-head gradient is cast to the logit dtype.
Derivatives for excluded vocabulary tokens are exactly zero. The kernels emit one raw
objective and gradient per supervised row. The usual global valid-token
normalization applies once, after accumulation and all-reduce; apart from RPS's ordinal
denominator there is no extra division by microbatch, world size or candidate count.
Softcap derivatives and aliased logit/gradient buffers go through the existing path.

The `kd_logprobs` array is only a transport placeholder here. All three
candidate objectives ignore it, even though ordinary KD reads it as
teacher data. These flags do not support soft labels, KL, a teacher model,
EMA, policy rollouts or a mix of CE and proper scores. Keep
`temperature: 1`, `kd_weight: 1`, `ce_weight: 0`, and `eval_steps: 0`.

## Data-parallel LoRA normalization correction

Token-normalized LoRA gradients are averaged across data-parallel ranks, while
valid-token counts are summed globally. The corrected runtime scales by
`world_size / global_valid_count`, which gives the intended global token mean. The
same scale reaches reported norms, clipping and the optimizer's gradient input,
for standard SFT and for candidate CE/Brier/RPS alike. Single-GPU behavior
and custom-loss paths that are not token-normalized are unchanged.

Earlier runtimes divided the averaged gradient by the global count a second time,
so gradients and norms came out smaller by a factor of `world_size`. That does not mean the
learning rate or Adam updates were smaller by the same factor: moment normalization
can cancel a uniform gradient scale, while clipping, epsilon and precision may
still change behavior. On its own it does not explain an observed accuracy gap.
Existing checkpoints keep their measured results. To compare a new objective, train
a fresh SFT/CE control on the same corrected runtime.

The correction covers only the validated non-EP data-parallel path. CE with
expert parallelism is unchanged: it mixes full-world dense reductions
with DP-subgroup expert reductions and needs its own validation.

Current implementation limits:

- It reuses the sidecar loader and the eager KD scheduling path, so CUDA graphs and
  ignored-row LM-head compaction are disabled. It still computes the full
  vocabulary projection and saves no LM-head compute.
- It uses normal token-count normalization and supports gradient accumulation and
  local multi-GPU data parallelism. The KD restrictions on multi-node and
  dispatch-PP execution still apply.
- The built-in `validate()` still computes full-vocabulary CE, so this configuration requires
  `eval_steps: 0`. Evaluate candidate metrics separately with the same prompt
  and allowed-token mapping, and don't report ordinary validation CE as a candidate proper loss.
- In this mode `get_kd_loss()` returns the selected candidate objective, but still as a
  metric local to rank zero. The standard training `loss` is the candidate objective
  reduced across ranks, so the two can differ when ranks see different examples.
- Evaluate probability calibration separately. Hard-label training
  guarantees neither calibration nor correct decisions.

Tests cover FP32/BF16 loss and gradients, small/chunked vocabularies, masked rows,
variable candidate counts, aliased buffers, softcap derivatives, invalid candidate
sets, and LoRA gradient accumulation. The standalone Jev experiment bridge also
checks candidate alignment through the actual shuffled native loader.

Next: the [Knowledge Distillation guide](/engine/guides/distillation/) covers capturing `.kd` sidecars, and the
[Knowledge Distillation settings](/engine/reference/config/#knowledge-distillation) list every `distillation:` key.
