Topic 54 of 62 · Wider ML toolkit
Binary and multi-label loss: BCE with logits
EasyWhen should a Transformer head use binary cross-entropy instead of softmax cross-entropy?
1 · Start with the intuition
First ask whether the answers exclude one another. A next token is one choice from a vocabulary, so softmax makes sense. A document can be both “finance” and “legal”, so its labels should not compete for a single unit of probability. Give each label a separate Bernoulli prediction.
2 · How the mechanism works
Mechanism step 1 of 3 · no question to answer
Match the target structure
Use categorical CE for one of C classes. Use BCE for a binary decision or C independent multi-label decisions.
Next, we will look at: Pass raw logits. Move on when this operation makes sense.
Visualizing the behavior
Three independent label probabilities, not one distribution
DerivedTarget labels [1,0,1]
3 · The governing equation
p_c = sigmoid(z_c) L_c = −y_c log p_c − (1−y_c) log(1−p_c) Stable unweighted form: max(z_c,0) − z_c y_c + log(1+exp(−|z_c|)) L = mean over valid examples and labels
Notation: z is a raw logit; y is a floating target in [0,1]. Unlike a categorical distribution, the label probabilities need not sum to one. Padding/missing-label masks require an explicit masked reduction.
Independent sigmoid outputs let multiple labels be true at once. A softmax would force those labels to suppress one another. For one binary label, a single-logit BCE and a two-logit softmax CE can express the same Bernoulli model. Weighting positives changes the objective and the meaning of predicted scores, so a default threshold of 0.5 need not be optimal or calibrated.
4 · Put concrete numbers on it
Worked numbers (from stated assumptions)5 · Common misconception to avoid
Do not apply sigmoid before BCEWithLogitsLoss, and do not use softmax for genuinely multi-label targets. A class weight is not a substitute for checking precision, recall, and calibration.
Scenario practice · Choose the loss for the scenario
10 scenarios, ordered Easy → Medium → Hard. Choose the best option, then rate your confidence. A first miss gives a nudge and one retry; a second miss or reveal gives an explanation and zero credit.
Session-only practice. Changing level, leaving, or reloading resets this set.
6 · Self-check & interview synthesis
Explain it in your own words first
Before revealing the reference answer, try answering the opening question aloud in four beats: what it is → how the math works → what trade-off it makes → a concrete number or failure mode.
Follow-up question interviewers often ask next
MediumCan BCE train a next-token vocabulary head?
Show follow-up reasoning
It could assign independent token indicators, but that is a different objective without the categorical competition appropriate to one next token. Standard language modeling uses softmax cross-entropy.