Track III · LLM Fundamentals · 07/07

사후학습 개관과 SFTPost-training overview and SFT

사전학습 모델이 어떻게 대화하는 모델이 되는지 사후학습 파이프라인 전체를 조망하고, 그 첫 단계인 SFT를 구현 수준에서 다룬다. chat template과 special token, 프롬프트 토큰 loss masking, 멀티턴과 packing의 attention mask, 데이터 규모와 품질, 그리고 SFT가 왜 forward KL 최소화인지.A view of the whole post-training pipeline that turns a pre-trained model into one that converses, then its first stage, SFT, at the implementation level: chat templates and special tokens, loss masking of prompt tokens, multi-turn data and the attention mask under packing, data scale and quality, and why SFT is forward-KL minimisation.

35 분min post-training · SFT · instruction tuning · chat template · loss masking · packing · forward KL 먼저 볼 것:Before this: 언어 모델링Language modeling, 토크나이저Tokenizers, GPT를 바닥부터GPT from scratch

A base model fresh out of pre-training is a machine that continues internet documents. Give it “What is the capital of France?” and instead of answering it may list a few more quiz questions just like it. The whole process that turns it into a model that answers questions, follows instructions, calls tools and refuses dangerous requests is post-training. This lesson first looks at that whole picture, then covers its first stage, SFT (supervised fine-tuning, instruction tuning), at the implementation level. Track V covers the stages that follow.

The stages of post-training

Today’s typical pipeline looks like this.

StageDataObjectiveWhat it does
Pre-trainingTrillions of tokens of web, code, booksNext-token NLLKnowledge and language ability
Mid-trainingHigh-quality math, code, instructions, long contextNext-token NLL (learning-rate decay)Lays the groundwork for the next stages
SFT(prompt, good response) pairsNLL of the response tokensFormat, dialogue, instruction following
Preference learning(prompt, better response, worse response)Reward model + RL, or DPOStyle, helpfulness, safety
RL (RLVR etc.)Prompts + verifier/rewardKL-regularised expected rewardReasoning, correctness, agent behaviour

InstructGPT (Ouyang et al., 2022) established the three-stage “SFT → reward model → PPO” recipe, and Tülu 3 (Lambert et al., 2024) showed an open recipe running “SFT → DPO → RL with verifiable rewards (RLVR)”. Lambert sees much of post-training as elicitation: putting abilities the pre-trained model already has into a form that is easy to use. SFT is the most direct way to do that. You show examples of the behaviour you want and have the model imitate them.

SFT: maximum likelihood on the response tokens

The data are pairs of a prompt xx and a good response yy. The objective is the same NLL as in the language-modelling lesson, but summed over the response tokens only.

LSFT(θ)=− E(x,y)∼D∑t=1∣y∣log⁡πθ(yt∣x,y<t)\mathcal{L}_{\text{SFT}}(\theta) = -\,\mathbb{E}_{(x, y) \sim \mathcal{D}} \sum_{t=1}^{|y|} \log \pi_\theta(y_t \mid x, y_{<t})

Written in the language of distributions, it becomes clear what is being minimised. If pD(⋅∣x)p_{\mathcal{D}}(\cdot \mid x) is the distribution of demonstration responses for prompt xx, then

Ey∼pD[−log⁡πθ(y∣x)]=H(pD(⋅∣x))+DKL(pD(⋅∣x) ∥ πθ(⋅∣x))\mathbb{E}_{y \sim p_{\mathcal{D}}}[-\log \pi_\theta(y \mid x)] = H(p_{\mathcal{D}}(\cdot \mid x)) + D_{\mathrm{KL}}\big(p_{\mathcal{D}}(\cdot \mid x) \,\|\, \pi_\theta(\cdot \mid x)\big)

The first term does not depend on θ\theta, so SFT = minimising the forward KL from the data distribution to the model. Forward KL punishes heavily when the model gives low probability to places where the data has mass (in pDlog⁡(pD/πθ)p_{\mathcal{D}} \log(p_{\mathcal{D}}/\pi_\theta) it diverges as πθ→0\pi_\theta \to 0). So the model tries to cover (mass-covering) every mode that appears in the demonstrations, and when it is unsure it spreads probability across several answers. The KL-regularised objective of RL, by contrast, is an expectation over the model’s own samples, closer to reverse KL, and tends to concentrate (mode-seeking) on one good mode. This is one reason SFT and RL produce models of different character.

One more important difference: SFT imitates responses written by someone else (off-policy). If a demonstration contains facts the model does not actually know, the model can learn “the format of confidently asserting something plausible”. That is why the fit between the quality of the demonstration data and the model’s ability matters.

Chat template

A conversation is a list of messages with roles. The model sees only integer sequences, so we need a rule that serialises this structure into a token sequence. That rule is the chat template. Below is an example in ChatML format.

<|im_start|>system
You are a helpful assistant.<|im_end|>
<|im_start|>user
How is the weather in Seoul?<|im_end|>
<|im_start|>assistant
<tool_call>{"name": "weather", "city": "Seoul"}</tool_call><|im_end|>
<|im_start|>tool
{"temp": 3, "sky": "clear"}<|im_end|>
<|im_start|>assistant
Seoul is 3 degrees and clear now.<|im_end|>
  • Special tokens: boundary tokens like <|im_start|> and <|im_end|> go in as single tokens, outside BPE, as we saw in the tokeniser lesson. If they were newly added, their embeddings are first learned in SFT.
  • Roles: system (operator instructions), user, assistant, and tool (the result of running a tool). A tool call is usually the assistant generating JSON inside a tag like <tool_call>…</tool_call>. The format differs from model to model.
  • Generation prompt: at inference you append <|im_start|>assistant\n at the end (Hugging Face’s add_generation_prompt=True) so that the model starts generating from the body of the assistant turn. When the model emits <|im_end|>, the turn ends.
  • Jinja: in the Hugging Face ecosystem this rule is stored as a Jinja template inside the tokeniser config and applied with apply_chat_template.

If the template differs by even one character between training and inference (a newline, a space, a default system prompt), the model receives a token sequence it never saw during training. Nothing errors; performance just drops quietly. So the principle is that SFT, RL, evaluation and serving all use the same code for the template.

Loss masking: what to learn

Put NLL on the whole templated token sequence and the model learns “how to generate” the user’s questions and the tool outputs too. Usually we prevent that by putting loss only on the tokens the assistant will generate. The implementation replaces the labels at all other positions with −100-100 (the default ignore_index of PyTorch’s cross_entropy).

  • What we want is p(y∣x)p(y \mid x), not p(x)p(x). There is no reason to spend capacity and gradient on modelling user utterances.
  • It stops prompts such as long system prompts or documents from dominating the gradient.
  • Train on tool outputs and the model learns to make up tool results. Tokens supplied by the environment are not actions of the policy. It is the same principle as removing observation tokens from the policy loss in agent RL.
  • The header of an assistant turn, <|im_start|>assistant\n, is inserted by the template at inference, so it is not trained, while the <|im_end|> that closes the turn is trained. The model has to learn when to stop.

Putting loss on the prompt is not always bad. There are reports that when data is scarce and responses are short, a (small-weight) loss on the prompt tokens helps. But the default is masking.

In multi-turn data there is one more choice. Training on every assistant turn gets several demonstrations out of one conversation. If the earlier turns are low-quality responses produced by another model, or just context for a synthetic conversation, train only on the last turn.

Packing and the attention mask

Examples vary in length. Pad a batch to its longest example and a good share of the compute is wasted on padding. Packing concatenates several examples to fill fixed-length rows completely. But with a plain causal mask, the tokens of the second example can see the first example through attention. Unrelated conversations leak into each other’s context: contamination. The fixes are

  • A per-document (block-diagonal) causal mask: attend only within the same example, and only to the past. FlashAttention’s variable-length (varlen) kernel takes each example’s boundaries (cu_seqlens) and computes this without padding.
  • Restarting position ids: count RoPE positions from 0 again for each example. Only then is a packed example computed exactly as it would be on its own.

사전학습이 끝난 base model은 인터넷 문서를 이어 쓰는 기계다. “프랑스의 수도는?”이라고 넣으면 답 대신 비슷한 퀴즈 문제를 몇 개 더 나열할 수도 있다. 이것을 질문에 답하고, 지시를 따르고, 도구를 부르고, 위험한 요청을 거절하는 모델로 바꾸는 과정 전체가 사후학습(post-training) 이다. 이 레슨은 그 전체 그림을 먼저 보고, 첫 단계인 SFT(supervised fine-tuning, instruction tuning) 를 구현 수준에서 다룬다. Track V는 그 다음 단계들이다.

사후학습의 단계

현재의 일반적인 파이프라인은 다음과 같다.

단계데이터목적함수하는 일
사전학습수조 토큰의 웹·코드·책다음 토큰 NLL지식과 언어 능력
Mid-training고품질 수학·코드·지시문·긴 문맥다음 토큰 NLL (학습률 감쇠)다음 단계의 기반 다지기
SFT(프롬프트, 좋은 응답) 쌍응답 토큰의 NLL형식·대화·지시 따르기
선호 학습(프롬프트, 더 나은 응답, 더 못한 응답)보상모델 + RL, 또는 DPO스타일, 유용성, 안전
RL (RLVR 등)프롬프트 + 검증기/보상KL 정규화된 기대 보상추론, 정확성, agent 행동

InstructGPT(Ouyang et al., 2022)가 “SFT → 보상모델 → PPO”의 3단계를 정립했고, Tülu 3(Lambert et al., 2024)는 “SFT → DPO → 검증 가능한 보상의 RL(RLVR)“로 이어지는 공개 레시피를 보여 주었다. Lambert는 사후학습의 많은 부분을 elicitation, 즉 사전학습이 이미 가진 능력을 꺼내 쓰기 좋은 형태로 만드는 일로 본다. SFT는 그 중 가장 직접적인 방법이다. 원하는 행동의 예시를 보여 주고 따라 하게 한다.

SFT: 응답 토큰에 대한 최대가능도

데이터는 프롬프트 xx와 좋은 응답 yy의 쌍이다. 목적함수는 언어 모델링 레슨의 NLL과 같은데, 응답 토큰에 대해서만 합한다.

LSFT(θ)=− E(x,y)∼D∑t=1∣y∣log⁡πθ(yt∣x,y<t)\mathcal{L}_{\text{SFT}}(\theta) = -\,\mathbb{E}_{(x, y) \sim \mathcal{D}} \sum_{t=1}^{|y|} \log \pi_\theta(y_t \mid x, y_{<t})

이것을 분포의 언어로 쓰면 무엇을 최소화하는지가 보인다. 프롬프트 xx에 대한 시연 응답의 분포를 pD(⋅∣x)p_{\mathcal{D}}(\cdot \mid x)라 하면

Ey∼pD[−log⁡πθ(y∣x)]=H(pD(⋅∣x))+DKL(pD(⋅∣x) ∥ πθ(⋅∣x))\mathbb{E}_{y \sim p_{\mathcal{D}}}[-\log \pi_\theta(y \mid x)] = H(p_{\mathcal{D}}(\cdot \mid x)) + D_{\mathrm{KL}}\big(p_{\mathcal{D}}(\cdot \mid x) \,\|\, \pi_\theta(\cdot \mid x)\big)

첫 항은 θ\theta와 무관하므로 SFT = 데이터 분포에서 모델로의 forward KL 최소화다. forward KL은 데이터가 질량을 가진 곳에 모델이 낮은 확률을 주면 크게 벌한다(pDlog⁡(pD/πθ)p_{\mathcal{D}} \log(p_{\mathcal{D}}/\pi_\theta)에서 πθ→0\pi_\theta \to 0이면 발산). 그래서 모델은 시연에 나온 모든 모드를 덮으려(mass-covering) 하고, 확신이 없을 때 여러 답 사이에 확률을 퍼뜨린다. 반대로 RL의 KL 정규화 목적함수는 모델 자신의 샘플에 대한 기대값이라 reverse KL에 가깝고, 하나의 좋은 모드에 집중(mode-seeking) 하는 경향이 있다. SFT와 RL이 서로 다른 성격의 모델을 만드는 한 가지 이유다.

또 하나 중요한 차이: SFT는 남이 쓴(off-policy) 응답을 따라 한다. 시연이 모델이 실제로 모르는 사실을 담고 있으면 모델은 “그럴듯하게 단정하는 형식”을 배울 수 있다. 시연 데이터의 품질과 모델 능력의 궁합이 중요한 이유다.

채팅 템플릿(Chat template)

대화는 역할(role)이 있는 메시지의 목록이다. 모델은 정수열만 보므로 이 구조를 토큰열로 직렬화하는 규칙이 필요하다. 이것이 chat template이다. 아래는 ChatML 형식의 예다.

<|im_start|>system
너는 도움이 되는 비서다.<|im_end|>
<|im_start|>user
서울 날씨 어때?<|im_end|>
<|im_start|>assistant
<tool_call>{"name": "weather", "city": "Seoul"}</tool_call><|im_end|>
<|im_start|>tool
{"temp": 3, "sky": "맑음"}<|im_end|>
<|im_start|>assistant
서울은 지금 3도이고 맑다.<|im_end|>
  • Special token: <|im_start|>, <|im_end|> 같은 경계 토큰은 토크나이저 레슨에서 본 것처럼 BPE 밖에서 한 토큰으로 들어간다. 새로 추가했다면 embedding은 SFT에서 처음 학습된다.
  • 역할: system(운영자 지시), user, assistant, 그리고 tool(도구 실행 결과). tool 호출은 보통 assistant가 <tool_call>…</tool_call> 같은 태그 안에 JSON을 생성하는 형식이다. 모델마다 형식이 다르다.
  • 생성 프롬프트: 추론할 때는 마지막에 <|im_start|>assistant\n까지 붙여서(Hugging Face의 add_generation_prompt=True) 모델이 assistant 턴의 본문부터 생성하게 한다. 모델이 <|im_end|>를 내면 턴이 끝난다.
  • Jinja: Hugging Face 생태계에서는 이 규칙을 토크나이저 설정 안의 Jinja 템플릿으로 저장하고 apply_chat_template으로 적용한다.

학습 때와 추론 때 템플릿이 한 글자라도 다르면(줄바꿈, 공백, 기본 system 프롬프트) 모델은 학습 때 본 적 없는 토큰열을 받는다. 오류는 나지 않고 성능만 조용히 떨어지므로, 템플릿은 SFT·RL·평가·서빙이 같은 코드를 쓰게 하는 것이 원칙이다.

Loss masking: 무엇을 학습할 것인가

템플릿으로 만든 토큰열 전체에 NLL을 걸면 모델은 사용자 질문과 tool 출력까지 “생성하는 법”을 배운다. 보통은 이를 막기 위해 assistant가 생성할 토큰에만 loss를 준다. 구현은 label에서 나머지 위치를 −100-100으로 바꾸는 것이다(PyTorch cross_entropy의 기본 ignore_index).

  • 우리가 원하는 것은 p(y∣x)p(y \mid x)이지 p(x)p(x)가 아니다. 사용자 발화를 모델링하는 데 용량과 기울기를 쓸 이유가 없다.
  • 긴 system 프롬프트나 문서 같은 프롬프트가 기울기를 지배하는 것을 막는다.
  • tool 출력을 학습하면 모델이 도구 결과를 지어내는 법을 배운다. 환경이 준 토큰은 정책의 행동이 아니다. Agent RL에서 관찰(observation) 토큰을 policy loss에서 빼는 것과 같은 원리다.
  • assistant 턴의 머리말 <|im_start|>assistant\n은 추론 때 템플릿이 넣어 주므로 학습하지 않고, 턴을 닫는 <|im_end|>는 학습한다. 모델은 언제 멈출지 배워야 한다.

프롬프트에도 loss를 거는 것이 항상 나쁘지는 않다. 데이터가 적고 응답이 짧을 때는 프롬프트 토큰에 (작은 가중치의) loss를 주는 것이 도움이 된다는 보고도 있다. 그러나 기본값은 마스킹이다.

멀티턴에서는 선택이 하나 더 있다. 모든 assistant 턴을 학습하면 대화 하나에서 여러 시연을 얻는다. 앞쪽 턴이 다른 모델이 만든 품질 낮은 응답이거나 합성 대화의 맥락일 뿐이라면 마지막 턴만 학습한다.

Packing과 attention mask

예시들은 길이가 제각각이다. 배치를 가장 긴 예시에 맞춰 패딩하면 계산의 상당 부분이 패딩에 버려진다. Packing은 여러 예시를 이어 붙여 고정 길이 행을 꽉 채운다. 그런데 평범한 causal mask를 쓰면 둘째 예시의 토큰이 첫째 예시를 attention으로 볼 수 있다. 서로 무관한 대화가 문맥으로 섞이는 오염이다. 해법은

  • 문서별(block-diagonal) causal mask: 같은 예시 안에서만, 그리고 과거만 보게 한다. FlashAttention의 가변 길이(varlen) 커널은 각 예시의 경계(cu_seqlens)를 받아 이것을 패딩 없이 계산한다.
  • 위치 id 재시작: RoPE의 위치를 예시마다 0부터 다시 센다. 그래야 packing한 예시가 단독으로 들어갔을 때와 똑같이 계산된다.
system user assistant tool | loss 받음 (label = 토큰 id)gets loss (label = token id) label = −100
Two conversations rendered as a token stream with a ChatML-style template (<|im_start|>role … <|im_end|>). A green underline means the token receives SFT loss. By default only the tokens the assistant generates, plus the <|im_end|> that closes its turn, are trained. The assistant header (<|im_start|>assistant) is inserted by the template at inference, so it is not trained. Tool output comes from the environment, so it is not trained either. Turn packing on to concatenate both examples into one row and show the attention mask. Turn the per-document mask off and the tokens of example 2 can see example 1 (red cells). 대화 두 개를 ChatML 형식 템플릿(<|im_start|>역할 … <|im_end|>)으로 렌더링한 토큰열이다. 밑줄이 초록이면 그 토큰이 SFT loss를 받는다. 기본값은 assistant가 생성하는 토큰과 그 턴을 끝내는 <|im_end|>만 학습한다. assistant 머리말(<|im_start|>assistant)은 추론 때 템플릿이 넣어 주므로 학습하지 않는다. tool 출력도 환경이 준 것이라 학습하지 않는다. packing을 켜면 두 예시를 한 행에 이어 붙이고 attention mask를 보여 준다. 문서별 mask를 끄면 예시 2의 토큰이 예시 1을 볼 수 있다(빨간 칸).

What to check in the figure:

  1. With the default settings only some of the tokens receive loss. The tool-call JSON (generated by the assistant) has a green underline; the tool-result JSON (generated by the environment) is grey.
  2. Choose “last turn only” and in example 1 only the “You are welcome.” turn is trained. The earlier tool call and answer serve only as context.
  3. Put the two examples in one batch without packing and the short example 2 is padded to the length of the long example 1, wasting a good share of the slots.
  4. Turn packing on and the per-document mask off and red cells appear in the example-2 region. Example 2’s “What is 2+2?” is attending to the Seoul weather conversation. Hover over a token to highlight its row of the mask.

Data: how much, and what kind

LIMA (Zhou et al., 2023) reported that a 65B model fine-tuned with SFT on only 1,000 carefully chosen examples shows quite good conversational ability, and proposed the Superficial Alignment Hypothesis: “a model’s knowledge and abilities come almost entirely from pre-training, and alignment is learning which format to draw those abilities out in”. For format and style this is a largely correct observation. But later experience is that teaching new skills, such as math, code and tool use, takes far more and far more varied data. The SFT mixture of Tülu 3 combined skill-specific data (instruction following, math, code, safety, multilingual and more) on the scale of hundreds of thousands of examples, much of it synthetic data generated to target particular personas or skills. The mixture was decided by ablations that added and removed each data source and watched the evaluation scores.

The practical feel is this. (1) Quality matters more than quantity; 1% wrong demonstrations become a habit of the whole model. (2) Diversity (of tasks, formats, lengths) is what produces generalisation. (3) Check for contamination of the evaluation data. (4) The learning rate is much smaller than in pre-training, and there are only a few epochs.

Implementing it

First we apply a chat template with a toy tokeniser and build the loss mask while tokenising message by message. We also check that tokenising message by message gives the same result as tokenising the whole string at once (with a real BPE this can differ at the boundaries, so it is a property you must check).

NumPy chat template → token ids + labels (-100 masking)
import numpy as np, re

SPECIAL = ["<|im_start|>", "<|im_end|>", "<tool_call>", "</tool_call>"]
vocab = {s: i for i, s in enumerate(SPECIAL)}               # special tokens get fixed ids

def tokenize(text):
    """Toy tokenizer: split off special tokens first, then words / symbols / newlines."""
    ids = []
    for part in re.split("(" + "|".join(map(re.escape, SPECIAL)) + ")", text):
        if part in SPECIAL:
            ids.append(vocab[part]); continue
        for piece in re.findall(r"\n|[A-Za-z0-9_]+|[^\sA-Za-z0-9_]| ", part):
            ids.append(vocab.setdefault(piece, len(vocab)))
    return ids

def render(m):
    body = f"<tool_call>{m['content']}</tool_call>" if m.get("tool_call") else m["content"]
    return f"<|im_start|>{m['role']}\n", f"{body}<|im_end|>", "\n"   # header, body(+end), tail

def apply_chat_template(msgs, add_generation_prompt=False):
    s = "".join("".join(render(m)) for m in msgs)
    return s + ("<|im_start|>assistant\n" if add_generation_prompt else "")

def build_example(msgs, train_on="all_assistant"):
    last = max(i for i, m in enumerate(msgs) if m["role"] == "assistant")
    ids, labels = [], []
    for i, m in enumerate(msgs):
        head, body, tail = render(m)
        learn = m["role"] == "assistant" and (train_on == "all_assistant" or i == last)
        for seg, on in [(head, False), (body, learn), (tail, False)]:
            t = tokenize(seg)
            ids += t
            labels += t if on else [-100] * len(t)                    # positions we do not train get -100
    return np.array(ids), np.array(labels)

conv = [
    {"role": "system", "content": "You are a helper."},
    {"role": "user", "content": "Cold outside today?"},
    {"role": "assistant", "content": '{"name": "weather", "city": "Seoul"}', "tool_call": True},
    {"role": "tool", "content": '{"temp": 3, "sky": "clear"}'},
    {"role": "assistant", "content": "Currently 3C and sunny."},
]
text = apply_chat_template(conv)
ids, labels = build_example(conv)
assert list(ids) == tokenize(text), "per-message tokenization differs from whole-string tokenization"
print(text)
inv = {v: k for k, v in vocab.items()}
print("tokens that get loss:", "".join(inv[i] if l != -100 else "·" for i, l in zip(ids, labels)).replace("\n", "↵"))
print(f"\nloss on {np.sum(labels != -100)} of {len(ids)} tokens")
print("end of the inference prompt:", repr(apply_chat_template(conv[:2], add_generation_prompt=True)[-40:]))
 

Now we compute the masked SFT loss with fake logits. The logit at position tt predicts token t+1t+1, so the labels are shifted by one. We look at how masking changes the loss value and where the gradient goes.

NumPy Masked SFT loss and its gradient
V = len(vocab)
rng = np.random.default_rng(0)
logits = rng.normal(0, 0.1, size=(len(ids), V))           # say, the small logits of a freshly initialised model: (T, V)

def log_softmax(z):
    z = z - z.max(-1, keepdims=True)
    return z - np.log(np.exp(z).sum(-1, keepdims=True))

def sft_loss(logits, labels):
    lp = log_softmax(logits[:-1])                           # position t
    tgt = labels[1:]                                        # predicts token t+1
    keep = tgt != -100
    nll = -lp[np.arange(len(tgt)), np.where(keep, tgt, 0)]
    loss = (nll * keep).sum() / keep.sum()                  # mean over unmasked tokens
    grad = np.exp(lp); grad[np.arange(len(tgt)), np.where(keep, tgt, 0)] -= 1   # softmax - onehot
    grad *= keep[:, None] / keep.sum()                      # gradient at masked positions is exactly 0
    return loss, grad

loss_masked, g = sft_loss(logits, labels)
loss_all, _ = sft_loss(logits, ids.copy())                  # training on everything, prompt included
print(f"masked loss = {loss_masked:.4f}   ({np.sum(labels[1:] != -100)} loss positions)")
print(f"all-token loss = {loss_all:.4f}   ({len(ids) - 1} loss positions)")
print(f"ln V = {np.log(V):.4f}  (with small logits the prediction is near uniform, so loss ≈ ln V)")
rows = np.abs(g).sum(-1) > 0
print("positions the gradient flows through:", np.flatnonzero(rows).tolist())
print("tokens those positions predict:", [inv[i] for i in labels[1:][rows]])
 

Finally, packing. We concatenate two examples into one row and check that with a per-document causal mask and restarted position ids the output is exactly the same as computing each example on its own. To make position information affect the result, we use a single attention layer with an absolute position embedding added.

NumPy Packing: block-diagonal mask and position-id restart
conv_b = [{"role": "user", "content": "2+5?"}, {"role": "assistant", "content": "7."}]
ids_a, _ = build_example(conv)
ids_b, _ = build_example(conv_b)                              # new words get added to vocab

d = 16
W = {k: rng.normal(0, 0.3, (d, d)) for k in "qkv"}
E = rng.normal(0, 1, (len(vocab), d))
P = rng.normal(0, 1, (128, d))                               # say, a learned absolute position embedding

def attn_layer(ids, pos, mask):
    x = E[ids] + P[pos]
    q, k, v = x @ W["q"], x @ W["k"], x @ W["v"]
    s = np.where(mask, q @ k.T / np.sqrt(d), -np.inf)
    a = np.exp(s - s.max(-1, keepdims=True)); a /= a.sum(-1, keepdims=True)
    return a @ v

alone_b = attn_layer(ids_b, np.arange(len(ids_b)), np.tril(np.ones((len(ids_b),) * 2, bool)))

packed = np.concatenate([ids_a, ids_b])
doc = np.r_[np.zeros(len(ids_a), int), np.ones(len(ids_b), int)]
T = len(packed)
causal = np.tril(np.ones((T, T), bool))
block = causal & (doc[:, None] == doc[None, :])                # only within the same document
pos_cont = np.arange(T)                                          # positions continue across the row
pos_reset = np.r_[np.arange(len(ids_a)), np.arange(len(ids_b))]  # restart at 0 per document

for name, mask, pos in [("plain causal + continued positions", causal, pos_cont),
                        ("block mask + continued positions  ", block, pos_cont),
                        ("block mask + restarted positions  ", block, pos_reset)]:
    out_b = attn_layer(packed, pos, mask)[len(ids_a):]
    print(f"{name}: max diff between example 2 output and computing it alone = {np.abs(out_b - alone_b).max():.2e}")
print(f"\nslots with padding: {2 * max(len(ids_a), len(ids_b))},  slots with packing: {T}")
 

In PyTorch the masked cross-entropy is one line. If you pass labels to a Hugging Face model, the model does the one-position shift internally, so shifting them yourself before passing them in is a bug that shifts twice.

PyTorch PyTorch: masked SFT loss with ignore_index=-100 로컬에서 실행run locally (pip install torch)
import torch
import torch.nn.functional as F

def sft_loss(logits, input_ids, loss_mask):
    """logits: (B, T, V), input_ids: (B, T), loss_mask: (B, T) — 1 means train on that token."""
    labels = input_ids.masked_fill(loss_mask == 0, -100)
    shift_logits = logits[:, :-1, :]          # the prediction at position t
    shift_labels = labels[:, 1:]              # targets token t+1
    return F.cross_entropy(
        shift_logits.reshape(-1, shift_logits.size(-1)),
        shift_labels.reshape(-1),
        ignore_index=-100,                    # the default, but spelled out
        reduction="mean",                     # mean over loss tokens (token-level mean)
    )

# With Hugging Face you usually write this (the model shifts internally):
#   enc = tok.apply_chat_template(messages, tokenize=True, return_dict=True,
#                                 return_assistant_tokens_mask=True)  # when the template supports {% generation %}
#   labels = torch.tensor(enc["input_ids"]).masked_fill(torch.tensor(enc["assistant_masks"]) == 0, -100)
#   loss = model(input_ids=..., labels=labels).loss
 
확인 문제Check yourself

In ChatML-format SFT data, which tokens should receive loss by default?

What the model actually generates at inference is the assistant body and the end-of-turn token. The header is inserted by the template (add_generation_prompt), and the user body and tool results come from outside. In particular, if <|im_end|> is not trained, the model easily fails to stop and goes on to make up the next user turn.

확인 문제Check yourself

The SFT objective (minimising the NLL of demonstration responses) is equivalent to minimising which divergence?

Ey∼pD[−log⁡πθ(y∣x)]=H(pD)+DKL(pD∥πθ)\mathbb{E}_{y \sim p_{\mathcal{D}}}[-\log \pi_\theta(y \mid x)] = H(p_{\mathcal{D}}) + D_{\mathrm{KL}}(p_{\mathcal{D}} \| \pi_\theta). The expectation is taken over the data distribution, so it is forward KL, and it has the property of putting probability wherever the data is (mass-covering). It is the RL-side objective, with its expectation over the model’s own samples, that is closer to reverse KL.

Summary

  • Post-training runs pre-training → mid-training → SFT → preference learning → RL, and much of it is elicitation of abilities already learned in pre-training.
  • SFT minimises the NLL of the response tokens, that is, the forward KL from the demonstration distribution to the model (mass-covering, off-policy).
  • A chat template is the rule that serialises role-tagged messages with special tokens. Training, RL, evaluation and serving must use the same template.
  • The default loss mask trains only the assistant body and the end-of-turn token (everything else excluded with label = −100). Train on tool outputs and the model learns to make up results.
  • Packing removes padding waste, but examples contaminate each other unless there is a per-document causal mask and a position-id restart.
  • Format can be learned from a little high-quality data (LIMA), but new skills need varied, plentiful data (Tülu 3).

그림에서 확인할 것:

  1. 기본 설정에서 loss를 받는 토큰은 전체의 일부뿐이다. tool 호출 JSON(assistant가 생성)은 초록 밑줄, tool 결과 JSON(환경이 생성)은 회색이다.
  2. “마지막 턴만” 을 고르면 예시 1에서 “천만에.” 턴만 학습된다. 앞의 tool 호출과 답변은 문맥으로만 쓰인다.
  3. packing 없이 두 예시를 한 배치에 넣으면 짧은 예시 2가 긴 예시 1에 맞춰 패딩되어 슬롯의 상당 부분이 낭비된다.
  4. packing을 켜고 문서별 mask를 끄면 예시 2 영역에 빨간 칸이 생긴다. 예시 2의 “2+2는?”이 서울 날씨 대화를 attention으로 보고 있다. 토큰에 마우스를 올리면 mask의 그 행이 강조된다.

데이터: 얼마나, 어떤 것을

LIMA(Zhou et al., 2023)는 신중하게 고른 1,000개의 예시만으로 SFT한 65B 모델이 상당히 좋은 대화 능력을 보인다고 보고하고, “모델의 지식과 능력은 거의 전부 사전학습에서 오고, 정렬(alignment)은 어떤 형식으로 그 능력을 꺼낼지 배우는 것”이라는 Superficial Alignment Hypothesis를 제안했다. 형식과 스타일에 대해서는 대체로 맞는 관찰이다. 그러나 수학·코드·tool 사용처럼 새로운 기술을 가르치려면 훨씬 많고 다양한 데이터가 필요하다는 것이 이후의 경험이다. Tülu 3의 SFT 혼합은 지시 따르기, 수학, 코드, 안전, 다국어 등 기술별 데이터 수십만 개 규모를 섞었고, 상당 부분이 특정 페르소나나 기술을 겨냥해 생성한 합성 데이터다. 각 데이터 원천을 추가·제거하며 평가 점수를 보는 ablation으로 혼합을 정했다.

실전의 감각은 이렇다. (1) 품질이 양보다 중요하다. 틀린 시연 1%가 모델 전체의 습관이 된다. (2) 다양성(과제, 형식, 길이)이 일반화를 만든다. (3) 평가 데이터의 오염(contamination)을 확인한다. (4) 학습률은 사전학습보다 훨씬 작고 epoch은 몇 번이다.

직접 구현하기

먼저 장난감 토크나이저로 chat template을 적용하고, 메시지별로 토큰화하면서 loss mask를 만든다. 메시지별로 토큰화한 결과가 전체 문자열을 한 번에 토큰화한 결과와 같은지도 확인한다(실제 BPE에서는 경계에서 달라질 수 있어 반드시 확인해야 하는 성질이다).

NumPy chat template → 토큰 id + label(-100 마스킹)
import numpy as np, re

SPECIAL = ["<|im_start|>", "<|im_end|>", "<tool_call>", "</tool_call>"]
vocab = {s: i for i, s in enumerate(SPECIAL)}               # 특수 토큰은 고정 id

def tokenize(text):
    """장난감 토크나이저: 특수 토큰을 먼저 자르고, 나머지는 단어/기호/줄바꿈 단위."""
    ids = []
    for part in re.split("(" + "|".join(map(re.escape, SPECIAL)) + ")", text):
        if part in SPECIAL:
            ids.append(vocab[part]); continue
        for piece in re.findall(r"\n|[A-Za-z가-힣0-9_]+|[^\sA-Za-z가-힣0-9_]| ", part):
            ids.append(vocab.setdefault(piece, len(vocab)))
    return ids

def render(m):
    body = f"<tool_call>{m['content']}</tool_call>" if m.get("tool_call") else m["content"]
    return f"<|im_start|>{m['role']}\n", f"{body}<|im_end|>", "\n"   # 머리말, 본문(+끝), 꼬리

def apply_chat_template(msgs, add_generation_prompt=False):
    s = "".join("".join(render(m)) for m in msgs)
    return s + ("<|im_start|>assistant\n" if add_generation_prompt else "")

def build_example(msgs, train_on="all_assistant"):
    last = max(i for i, m in enumerate(msgs) if m["role"] == "assistant")
    ids, labels = [], []
    for i, m in enumerate(msgs):
        head, body, tail = render(m)
        learn = m["role"] == "assistant" and (train_on == "all_assistant" or i == last)
        for seg, on in [(head, False), (body, learn), (tail, False)]:
            t = tokenize(seg)
            ids += t
            labels += t if on else [-100] * len(t)                    # 학습 안 할 위치는 -100
    return np.array(ids), np.array(labels)

conv = [
    {"role": "system", "content": "너는 도움이 되는 비서다."},
    {"role": "user", "content": "서울 날씨 어때?"},
    {"role": "assistant", "content": '{"name": "weather", "city": "Seoul"}', "tool_call": True},
    {"role": "tool", "content": '{"temp": 3, "sky": "맑음"}'},
    {"role": "assistant", "content": "서울은 지금 3도이고 맑다."},
]
text = apply_chat_template(conv)
ids, labels = build_example(conv)
assert list(ids) == tokenize(text), "메시지별 토큰화와 전체 토큰화가 달라졌다"
print(text)
inv = {v: k for k, v in vocab.items()}
print("loss 받는 토큰:", "".join(inv[i] if l != -100 else "·" for i, l in zip(ids, labels)).replace("\n", "↵"))
print(f"\n전체 {len(ids)} 토큰 중 loss {np.sum(labels != -100)}개")
print("추론용 프롬프트 끝:", repr(apply_chat_template(conv[:2], add_generation_prompt=True)[-40:]))
 

이제 가짜 logit으로 마스킹된 SFT loss를 계산한다. 위치 tt의 logit이 토큰 t+1t+1을 예측하므로 label을 한 칸 민다. 마스킹이 loss 값과 기울기의 행방을 어떻게 바꾸는지 본다.

NumPy 마스킹된 SFT loss와 그 기울기
V = len(vocab)
rng = np.random.default_rng(0)
logits = rng.normal(0, 0.1, size=(len(ids), V))           # 초기화 직후 모델의 작은 logit이라 치자: (T, V)

def log_softmax(z):
    z = z - z.max(-1, keepdims=True)
    return z - np.log(np.exp(z).sum(-1, keepdims=True))

def sft_loss(logits, labels):
    lp = log_softmax(logits[:-1])                           # 위치 t가
    tgt = labels[1:]                                        # 토큰 t+1을 예측
    keep = tgt != -100
    nll = -lp[np.arange(len(tgt)), np.where(keep, tgt, 0)]
    loss = (nll * keep).sum() / keep.sum()                  # 마스킹된 토큰 평균
    grad = np.exp(lp); grad[np.arange(len(tgt)), np.where(keep, tgt, 0)] -= 1   # softmax - onehot
    grad *= keep[:, None] / keep.sum()                      # 마스킹된 위치의 기울기는 정확히 0
    return loss, grad

loss_masked, g = sft_loss(logits, labels)
loss_all, _ = sft_loss(logits, ids.copy())                  # 프롬프트까지 전부 학습할 때
print(f"masked loss = {loss_masked:.4f}   (loss 위치 {np.sum(labels[1:] != -100)}개)")
print(f"all-token loss = {loss_all:.4f}   (loss 위치 {len(ids) - 1}개)")
print(f"ln V = {np.log(V):.4f}  (logit이 작으면 예측이 균등에 가까워 loss ≈ ln V)")
rows = np.abs(g).sum(-1) > 0
print("기울기가 흐르는 위치:", np.flatnonzero(rows).tolist())
print("그 위치들이 예측하는 토큰:", [inv[i] for i in labels[1:][rows]])
 

마지막으로 packing이다. 두 예시를 한 행에 이어 붙이고, 문서별 causal mask와 위치 id 재시작을 쓰면 각 예시를 따로 계산한 것과 정확히 같은 출력이 나오는지 확인한다. 위치 정보가 결과에 영향을 주도록 절대 위치 embedding을 더한 attention 층 하나를 쓴다.

NumPy packing: block-diagonal mask와 위치 id 재시작
conv_b = [{"role": "user", "content": "2+2는?"}, {"role": "assistant", "content": "4다."}]
ids_a, _ = build_example(conv)
ids_b, _ = build_example(conv_b)                              # 새 단어가 vocab에 추가된다

d = 16
W = {k: rng.normal(0, 0.3, (d, d)) for k in "qkv"}
E = rng.normal(0, 1, (len(vocab), d))
P = rng.normal(0, 1, (128, d))                               # 학습된 절대 위치 embedding이라 치자

def attn_layer(ids, pos, mask):
    x = E[ids] + P[pos]
    q, k, v = x @ W["q"], x @ W["k"], x @ W["v"]
    s = np.where(mask, q @ k.T / np.sqrt(d), -np.inf)
    a = np.exp(s - s.max(-1, keepdims=True)); a /= a.sum(-1, keepdims=True)
    return a @ v

alone_b = attn_layer(ids_b, np.arange(len(ids_b)), np.tril(np.ones((len(ids_b),) * 2, bool)))

packed = np.concatenate([ids_a, ids_b])
doc = np.r_[np.zeros(len(ids_a), int), np.ones(len(ids_b), int)]
T = len(packed)
causal = np.tril(np.ones((T, T), bool))
block = causal & (doc[:, None] == doc[None, :])                # 같은 문서 안에서만
pos_cont = np.arange(T)                                          # 위치를 행 전체에 이어서
pos_reset = np.r_[np.arange(len(ids_a)), np.arange(len(ids_b))]  # 문서마다 0부터

for name, mask, pos in [("평범한 causal + 이어진 위치", causal, pos_cont),
                        ("block mask + 이어진 위치  ", block, pos_cont),
                        ("block mask + 위치 재시작  ", block, pos_reset)]:
    out_b = attn_layer(packed, pos, mask)[len(ids_a):]
    print(f"{name}: 예시 2 출력과 단독 계산의 최대 차이 = {np.abs(out_b - alone_b).max():.2e}")
print(f"\n패딩 방식 슬롯: {2 * max(len(ids_a), len(ids_b))},  packing 슬롯: {T}")
 

PyTorch로 쓰면 마스킹된 cross-entropy는 한 줄이다. Hugging Face 모델에 labels를 넘기면 모델 내부에서 한 칸 밀기를 하므로, 직접 밀어서 넘기면 두 번 밀리는 버그가 된다.

PyTorch PyTorch: ignore_index=-100으로 마스킹된 SFT loss 로컬에서 실행run locally (pip install torch)
import torch
import torch.nn.functional as F

def sft_loss(logits, input_ids, loss_mask):
    """logits: (B, T, V), input_ids: (B, T), loss_mask: (B, T) — 1이면 그 토큰을 학습."""
    labels = input_ids.masked_fill(loss_mask == 0, -100)
    shift_logits = logits[:, :-1, :]          # 위치 t의 예측이
    shift_labels = labels[:, 1:]              # 토큰 t+1을 맞힌다
    return F.cross_entropy(
        shift_logits.reshape(-1, shift_logits.size(-1)),
        shift_labels.reshape(-1),
        ignore_index=-100,                    # 기본값이지만 명시해 둔다
        reduction="mean",                     # loss 토큰 수로 평균 (token-level mean)
    )

# Hugging Face에서는 보통 이렇게 쓴다 (모델이 내부에서 shift한다):
#   enc = tok.apply_chat_template(messages, tokenize=True, return_dict=True,
#                                 return_assistant_tokens_mask=True)  # 템플릿이 {% generation %}을 지원할 때
#   labels = torch.tensor(enc["input_ids"]).masked_fill(torch.tensor(enc["assistant_masks"]) == 0, -100)
#   loss = model(input_ids=..., labels=labels).loss
 
확인 문제Check yourself

ChatML 형식 SFT 데이터에서 기본적으로 loss를 받아야 하는 토큰은?

모델이 추론 때 실제로 생성하는 것은 assistant 본문과 턴 종료 토큰이다. 머리말은 템플릿(add_generation_prompt)이 넣어 주고, user 본문과 tool 결과는 외부에서 들어온다. 특히 <|im_end|>를 학습하지 않으면 모델이 멈출 줄 모르고 다음 user 턴까지 지어내기 쉽다.

확인 문제Check yourself

SFT의 목적함수(시연 응답의 NLL 최소화)는 어떤 발산을 최소화하는 것과 같은가?

Ey∼pD[−log⁡πθ(y∣x)]=H(pD)+DKL(pD∥πθ)\mathbb{E}_{y \sim p_{\mathcal{D}}}[-\log \pi_\theta(y \mid x)] = H(p_{\mathcal{D}}) + D_{\mathrm{KL}}(p_{\mathcal{D}} \| \pi_\theta). 기대값이 데이터 분포에 대해 취해지므로 forward KL이고, 데이터가 있는 곳 어디에든 확률을 두려는(mass-covering) 성질을 갖는다. 모델 자신의 샘플로 기대값을 취하는 RL 쪽 목적함수가 reverse KL에 가깝다.

정리

  • 사후학습은 사전학습 → mid-training → SFT → 선호 학습 → RL로 이어지며, 많은 부분이 사전학습된 능력의 elicitation이다.
  • SFT는 응답 토큰에 대한 NLL 최소화, 곧 시연 분포에서 모델로의 forward KL 최소화다(mass-covering, off-policy).
  • Chat template은 역할 있는 메시지를 special token으로 직렬화하는 규칙이다. 학습·RL·평가·서빙이 같은 템플릿을 써야 한다.
  • 기본 loss mask는 assistant 본문과 턴 종료 토큰만 학습한다(label = −100으로 나머지 제외). tool 출력을 학습하면 결과를 지어내는 법을 배운다.
  • Packing은 패딩 낭비를 없애지만 문서별 causal mask와 위치 id 재시작이 있어야 예시들이 서로 오염되지 않는다.
  • 형식은 적은 고품질 데이터(LIMA)로도 배우지만, 새 기술에는 다양하고 많은 데이터(Tülu 3)가 필요하다.

더 읽을거리Further reading