Supervised fine-tuning: which tokens receive the loss?
监督微调
Build shifted response masks, include EOS and compare token versus example averaging in a real small training loop.
supervised-finetuningTwo trainers can use the same answers and learn different probabilities
Consider two authored conversations. After an assistant marker, the first response is Y EOS; the second is Y Y Y EOS. If every response token has equal weight, the four transitions following Y split equally between another Y and EOS. If each conversation instead receives equal total weight, the shorter answer has more influence per token. The best next-token probability for EOS after Y becomes 0.6 rather than 0.5.
Both procedures are supervised fine-tuning, or SFT. They differ in the objective actually optimized. A dataset and a label such as “cross-entropy” do not fully specify the training recipe.
InstructGPT, section 3.1, separates learning from demonstrations, fitting a reward model to comparisons, and optimizing a policy with PPO. This chapter concerns the demonstration step. Li and Liang, section 3.3, give the conditional sequence-likelihood objective also used when adapting a language model for a downstream generation task.
Shift the targets before applying their mask
For a causal sequence , position predicts the next token . If the response begins at sequence index , the aligned supervised targets are:
Here names the immediate context token in our bigram example. A Transformer uses the whole allowed prefix instead. The mask belongs to the predicted target, not simply the unshifted input position. Include the end-of-sequence target if learning to stop is part of the intended behavior.
With prompt and response , conditional generation factorizes as:
Teacher forcing supplies the reference response prefix during training. The prompt remains available as context even if its own token predictions do not contribute direct loss. Loss masking is different from deleting input tokens or masking attention.
For record , define its summed supervised loss and number of supervised targets:
A token-average objective is:
An equal-example objective that first averages within each response is:
The first gives more total weight to long responses. The second gives each example the same total weight. Neither is universally correct; choose according to the target behavior and document the reduction. Averaging separately across unequal microbatches and then averaging those means can silently produce another weighting unless denominators are accounted for.
For a supervised position with normalized weight , logits , softmax probabilities and target class , the derivative is:
Zero weight removes that position’s direct loss gradient. It does not imply that a prompt embedding receives no gradient through later response predictions. In our independent bigram table some rows remain unchanged; shared neural parameters do not have the same row separation.
For a freely fitted categorical distribution after context , the weighted maximum-likelihood limit is:
Apply this only to a context with positive total weight. For the two example responses, token weighting gives two Y and two EOS targets after Y. Equal-example weighting gives total weights 0.25 and 0.375 respectively, hence for EOS. Unobserved classes have zero probability in the ideal limit, which finite softmax logits only approach.
Train the objective you meant to specify
The complete NumPy program uses five token IDs and a trainable five-by-five bigram logit table. It shifts each transcript independently, supervises response tokens including EOS, and runs both reductions. It does not pack conversations together or implement padding.
"""Response loss masks and weighting in an authored five-token bigram model."""
import json
import numpy as np
# BOS=0, USER=1, ASSISTANT=2, Y=3, EOS=4; no padding in either record.
RECORDS=[([0,1,2,3,4],3),([0,1,2,3,3,3,4],3)]
def examples(records=RECORDS,mode='token',include_prompt=False):
if mode not in ('token','sequence') or not records:raise ValueError('A nonempty batch and known reduction required')
contexts=[];targets=[];weights=[]
for tokens,start in records:
if len(tokens)<2 or not isinstance(start,int) or not 1<=start<len(tokens):raise ValueError('Response must contain a target')
if any(type(t) is not int or not 0<=t<5 for t in tokens):raise ValueError('Token outside vocabulary')
mask=np.ones(len(tokens)-1) if include_prompt else (np.arange(1,len(tokens))>=start).astype(float)
if mode=='sequence':mask/=mask.sum()
contexts.extend(tokens[:-1]);targets.extend(tokens[1:]);weights.extend(mask)
weights=np.array(weights);weights/=weights.sum()
return np.array(contexts),np.array(targets),weights
def objective(logits,rows):
z=np.asarray(logits,float)
if z.shape!=(5,5) or not np.isfinite(z).all():raise ValueError('Finite5x5 logits required')
x,y,w=rows;v=z[x];v=v-v.max(axis=1,keepdims=True);logp=v-np.log(np.exp(v).sum(axis=1,keepdims=True))
loss=-float(w@logp[np.arange(len(y)),y]);g=np.exp(logp);g[np.arange(len(y)),y]-=1;g*=w[:,None]
out=np.zeros_like(z);np.add.at(out,x,g)
return loss,out
def train(mode='token',steps=1200):
if type(steps) is not int or not 0<=steps<=10000:raise ValueError('Bounded integer steps required')
rows=examples(mode=mode);z=np.zeros((5,5));history=[]
for i in range(steps+1):
loss,g=objective(z,rows)
if i%200==0 or i==steps:history.append(dict(step=i,loss=loss))
if i<steps:z-=g
p=np.exp(z-z.max(axis=1,keepdims=True));p/=p.sum(axis=1,keepdims=True)
return z,p,history
def demo():
result={}
for mode in ['token','sequence']:
z,p,history=train(mode);x,y,w=examples(mode=mode)
result[mode]=dict(weights=w.tolist(),eos_after_y=float(p[3,4]),initial_loss=history[0]['loss'],final_loss=history[-1]['loss'],trace=history,prompt_rows_unchanged=bool(np.array_equal(z[:2],np.zeros((2,5)))))
x,y,w=examples();result.update(contexts=x.tolist(),targets=y.tolist(),response_tokens=int(np.count_nonzero(w)),scope='Two authored transcripts; response mask includes EOS; bigram context deliberately limited; no padding or cross-record packing')
return result
if __name__=='__main__':print(json.dumps(demo(),allow_nan=False))
There are six supervised response targets. Token averaging assigns each weight . Equal-example averaging assigns the short answer’s two targets weight each and the long answer’s four targets weight each.
Starting from uniform logits, both losses equal . After 1,200 updates, EOS after Y has probability approximately 0.499246 under token averaging and 0.599196 under example averaging. Final losses are approximately 0.463778 and 0.422312, but they use different objectives and should not be compared as if they were one quality metric.
The tests check every shifted target and mask position, both EOS targets, the hand-derived frequency limits, and all 25 logit derivatives against finite differences. The BOS and USER rows have zero direct loss gradient here and remain unchanged. The response still depends on the assistant context token, demonstrating why a loss mask is not context deletion.
For vocabulary size and prediction positions, the table uses parameter storage and a dense evaluation uses work including gradient allocation. These costs describe this small bigram model, not Transformer fine-tuning.
A clean loss mask does not make demonstrations trustworthy
The model learns to imitate the provided answers, including mistakes and unwanted style. Minimized training loss does not establish truthfulness, robustness or preference alignment. Our bigram model cannot distinguish long-range conversation context, even with perfectly aligned targets.
Real chat data requires a fixed tokenizer and chat template, correct turn boundaries, and an explicit choice of which assistant turns to supervise. Padding targets must be excluded. When packing independent records, use the intended attention boundaries as well as loss boundaries; simply concatenating text can leak one example into another. These mechanisms are absent from this program and need their own checks in a training system.
Keep validation examples separate by the relevant unit, such as user, document or task family. InstructGPT section 3.2 describes user-based splits and prompt deduplication in its own data pipeline. That is evidence for that experiment, not a universal guarantee that every SFT dataset is leakage-free.
Check what each example contributes
- Does response-only loss require deleting prompt tokens? Answer: No. The prompt remains conditioning context. The loss mask only determines which predicted targets are directly supervised.
- What are the six positive weights under the two reductions? Answer: Token averaging gives six copies of . Equal-example averaging gives for the short response and four copies of for the long one.
- Why is the ideal
EOSprobability afterYequal to 0.6 under example averaging? Answer: EOS receives weight ; another Y receives . Normalize: . - One microbatch has two supervised tokens and another has six. Is the mean of their mean losses the global token average? Answer: Generally not. It weights the microbatches equally. Weight their loss sums by the total eight supervised tokens, or equivalently weight their means by and .
SFT is a specified learning stage, not a complete alignment recipe
InstructGPT makes the demonstration, comparison and policy-optimization stages distinct. Li and Liang show how the same generation likelihood can underlie different choices of trainable parameters. Changing from full fine-tuning to a small adaptation module need not change which targets the objective supervises.
A reproducible SFT report records the demonstration source, split unit, chat template, masks, reductions, stopping rule and evaluation tasks. Continue with LoRA to change parameterization while keeping the training objective explicit.
Make a prediction, then check
Does removing prompt positions from the loss remove the prompt from the model input?
Learning objectives
- Align causal targets and response masks without deleting prompt context.
- Derive how reduction changes the effective data distribution.
- Separate demonstration learning from preference optimization.
Prerequisites & connections
Explore related knowledge →References
- Training language models to follow instructions with human feedback — arXiv v1
Long Ouyang; Jeff Wu; Xu Jiang and coauthors · 2022 - Prefix-Tuning: Optimizing Continuous Prompts for Generation
Xiang Lisa Li; Percy Liang · 2021
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author additionally viewed InstructGPT v1 PDF6 sections3.1/3.2 and read selected subsequent text; Li/Liang ACL2021 PDF4/5 conditional likelihood and prefix method. Seven paired equations and four explained exercises. Original shifted response-mask bigram training, EOS, token/example weights, all25 derivatives and analytic.5/.6 optima. Prompt loss mask not input deletion; no packing/padding or full-model training.
- Single AI author additionally viewed InstructGPT v1 PDF6 sections3.1/3.2 and read selected subsequent text; Li/Liang ACL2021 PDF4/5 conditional likelihood and prefix method. Seven paired equations and four explained exercises. Original shifted response-mask bigram training, EOS, token/example weights, all25 derivatives and analytic.5/.6 optima. Prompt loss mask not input deletion; no packing/padding or full-model training.
- Four computed SVG variants per topic;11 numeric/geometry tests and36 responsive cases passed. Twelve selected captures checked:seven final directly viewed,five byte-identical to previously viewed images. Full article acceptance recorded separately.
Source locations checked:
- Training language models to follow instructions with human feedback — arXiv v1 · Existing Source/access date preserved; additionally viewed PDF6 sections3.1/3.2 demonstration/RM/PPO and user-based split/deduplication, plus selected text310–390. No model reproduction.
- Prefix-Tuning: Optimizing Continuous Prompts for Generation · Viewed PDF4/5: section3.3 likelihood, Figure2,4.1–4.3 per-layer prefix, frozen weights, backpropagation and reparameterization. No generation benchmark reproduced.
Related topics