Pretraining is running what we have built so far, the GPT architecture and next-token NLL, over trillions of tokens. We have already seen the whole algorithm. The remaining questions are how big, how long, and on what data. Because tens of millions of dollars ride on these decisions, scaling laws, which predict the outcome of a large run from small experiments, came into being.
Training compute: C ≈ 6ND
First, count the cost. The number of floating-point operations (FLOPs) needed to train a Transformer with parameters on tokens is
A single linear layer is enough for the derivation. Let the input be , the weights , and the output . This layer has parameters.
- Forward: each element of takes multiplications and additions, so FLOPs per token. That is 2 per parameter.
- Backward: when comes down from the layer above, we compute two things: to send further down (), and the weight gradient (). That is 4 per parameter.
Together, 6 FLOPs per parameter per token. Most of a Transformer’s computation is matrix multiplications like this, hence . What is left out is the attention score computation (, ), a term proportional to the context length , (forward, per token); when is large and is not very long, it is a few per cent (we compute it in the code below). Inference only runs the forward pass, so it costs about FLOPs per token. This number comes back in the next lesson and in the over-training discussion.
For example, Chinchilla (70B parameters, 1.4T tokens) took FLOPs. If one GPU delivers an effective 400 TFLOP/s, that is about 410,000 GPU-hours.
Kaplan: loss follows a power law
Kaplan et al. (2020) trained hundreds of models and showed that, when no other factor is the bottleneck, the test loss follows a power law in each of the parameter count , the data , and the compute .
That is, a straight line on log–log axes. The exponent is small (): cutting the loss by a fixed fraction takes a model several times larger. Another important observation is that the loss is insensitive to shape (depth, width, number of heads) and depends mainly on the total parameter count.
Kaplan concluded that at fixed compute the optimal model size grows as , i.e. the model should grow much faster than the data. GPT-3 (175B parameters, 300B tokens) is the representative model that followed this prescription.
Chinchilla: scale both together
Hoffmann et al. (2022) re-solved the same question with three methods: (1) for each model size, vary the number of training tokens and find the lower envelope of the loss curves; (2) find the optimal on IsoFLOP curves at fixed compute; (3) fit a parametric function to all the runs. The function of the third method is
is the irreducible loss corresponding to the entropy of the data ( from the language-modelling lesson), the second term is the error from a finite model, and the third the error from finite data. The paper’s fitted values are , , , , .
Now minimise under the constraint . Substitute , differentiate with respect to , and set it to 0:
The exponents are and . With 10× the compute, grow the model and the data each by roughly ×. Methods (1) and (2) gave exponents near 0.5, and the practical rule that came out of them is tokens ≈ 20 × parameters. To test it, Chinchilla (70B, 1.4T tokens) was trained with the same compute as Gopher (280B, 300B tokens), and Chinchilla, 4× smaller, won on most benchmarks.
사전학습(pretraining)은 지금까지 만든 것, 즉 GPT 구조와 다음 토큰 NLL을 수조 개의 토큰에 대해 돌리는 일이다. 알고리즘은 이미 다 봤다. 남은 질문은 얼마나 크게, 얼마나 오래, 어떤 데이터로다. 이 결정에 수천만 달러가 걸리기 때문에, 작은 실험에서 큰 실험의 결과를 예측하는 스케일링 법칙(scaling law) 이 생겼다.
학습 compute: C ≈ 6ND
먼저 비용을 세자. 매개변수 개짜리 Transformer를 토큰 개로 학습하는 데 드는 부동소수점 연산(FLOPs)은
이다. 유도는 선형층 하나로 충분하다. 입력 , 가중치 , 출력 라 하자. 이 층의 매개변수는 개다.
- Forward: 의 각 원소가 번의 곱셈과 덧셈이니 토큰당 FLOPs. 매개변수 하나당 2.
- Backward: 위층에서 가 내려오면 두 가지를 계산한다. 아래층으로 보낼 ()과 가중치 기울기 (). 매개변수 하나당 4.
합쳐서 매개변수당, 토큰당 6 FLOPs다. Transformer 연산의 대부분은 이런 행렬곱이므로 가 된다. 빠진 것은 attention 점수 계산(, )인데, 이는 문맥 길이 에 비례하는 항 (forward, 토큰당)이라 가 크고 가 아주 길지 않으면 몇 % 수준이다(아래 코드에서 계산한다). 추론은 forward만 하므로 토큰당 약 FLOPs다. 이 숫자는 다음 레슨과 over-training 논의에서 다시 나온다.
예를 들어 Chinchilla(70B 매개변수, 1.4T 토큰)는 FLOPs다. GPU 한 장이 실효 400 TFLOP/s를 낸다면 약 41만 GPU-시간이다.
Kaplan: loss는 멱법칙을 따른다
Kaplan et al.(2020)은 수백 개의 모델을 학습해서, 다른 요인이 병목이 아닐 때 test loss가 매개변수 수 , 데이터 , compute 각각에 대해 멱법칙(power law) 을 따른다는 것을 보였다.
로그–로그 축에서 직선이라는 뜻이다. 지수는 작다(). loss를 일정 비율 줄이려면 모델을 몇 배씩 키워야 한다. 또 하나의 중요한 관찰은 loss가 깊이·폭·head 수 같은 모양(shape)에는 둔감하고 총 매개변수 수에 주로 좌우된다는 것이다.
Kaplan은 고정된 compute에서 최적 모델 크기가 로, 데이터보다 모델을 훨씬 빨리 키워야 한다고 결론 내렸다. GPT-3(175B 매개변수, 300B 토큰)가 이 처방을 따른 대표적 예다.
Chinchilla: 둘을 같이 키워라
Hoffmann et al.(2022)은 세 가지 방법으로 같은 질문을 다시 풀었다. (1) 모델 크기별로 학습 토큰 수를 바꿔 가며 loss 곡선의 아래쪽 envelope를 찾기, (2) compute를 고정한 IsoFLOP 곡선에서 최적 찾기, (3) 모든 실험에 파라메트릭 함수를 fit하기. 세 번째 방법의 함수는 이렇다.
는 데이터의 엔트로피에 해당하는 줄일 수 없는 loss(언어 모델링 레슨의 ), 두 번째 항은 모델이 유한해서 생기는 오차, 세 번째 항은 데이터가 유한해서 생기는 오차다. 논문의 fit 값은 , , , , 이다.
이제 제약 아래에서 을 최소화하자. 을 대입하고 으로 미분해 0으로 두면
지수는 , 다. compute를 10배 늘리면 모델과 데이터를 각각 대략 배씩 늘리라는 것이다. 방법 (1), (2)는 지수를 0.5 근처로 주었고, 여기서 나온 실용 규칙이 토큰 수 ≈ 매개변수 수 × 20이다. 이를 검증하려고 Gopher(280B, 300B 토큰)와 같은 compute로 Chinchilla(70B, 1.4T 토큰)를 학습했고, 4배 작은 Chinchilla가 대부분의 벤치마크에서 이겼다.
Things to check in the figure:
- Each curve is U-shaped. At the left end (small model, many tokens) the model-capacity term dominates the loss; at the right end (large model, few tokens) the data term does. Near the minimum it is flat, so halving or doubling from the optimum raises the loss only a little.
- ◆ (the fit’s optimum) and ■ (D = 20N) do not coincide. Minimising this fit as is gives D/N from several tens to over a hundred, growing with compute. Besiroglu et al. (2024) pointed out that the Approach 3 constants reported in the paper do not fit the data well and disagree with the other two methods; their re-fit agreed better with the 20 tokens/parameter rule. The point is not the constants themselves but the structure: a U-shaped curve whose minimum moves along with . These constants also belong to a specific dataset, tokeniser and training recipe, so they do not transfer as is to other settings.
- Lower N/Nopt to 0.1. Spending the same compute on a 10× smaller model raises the loss noticeably, and “the compute that would reach the same loss with the optimal allocation” is much less than the current compute. The difference is the training cost of over-training.
Why Kaplan and Chinchilla differed
Follow-up work points to several causes. Kaplan did not match the learning-rate schedule to the actual training length, so the loss of short runs was overestimated; it counted parameters excluding embeddings; and it fitted mostly on relatively small models. The lesson is that a scaling law is also an empirical fit, sensitive to experimental design. Extrapolation becomes less certain the further it goes from the measured range.
Training “inefficiently” on purpose: over-training
The Chinchilla optimum minimises training compute only. But once a model is deployed, inference costs FLOPs per token for its whole lifetime. For a model that will serve trillions of tokens, it is cheaper overall to spend more compute in training to get a smaller model (Sardana et al., 2024). That is why recent open models are trained on far more tokens than compute-optimal. Llama 3 8B, for example, was trained on more than 15T tokens, about 1,900 tokens per parameter, almost 100× the 20 of the rule. Pushing N/Nopt to the left in the figure is exactly this choice, and its price is the extra training cost relative to “the compute that would reach the same loss with the optimal allocation”. It is not free, though: there are reports that models that have seen more tokens per parameter become more sensitive to post-training quantisation (Kumar et al., 2024, Scaling Laws for Precision).
Data: composition matters as much as quantity
The in a scaling law is a “number of tokens”, but not all tokens are equal. The main stages of a pretraining data pipeline are:
- Collection and extraction: most of it is web dumps such as Common Crawl. Main text is extracted from HTML and the language is identified. Code (GitHub), maths, papers, books and multilingual data are added on top.
- Filtering: besides rule-based filters (length, symbol ratio, repetition), these days keeping only the top documents according to a quality classifier, trained on criteria such as “is this educational text?”, improves performance a lot.
- Deduplication (dedup): remove exact duplicates and near-duplicates found with methods like MinHash. Duplication increases memorisation and wastes compute by showing the same data many times (Lee et al., 2022).
- Data mixture: what percentage of web, code, maths and multilingual data to mix is decided by experiments with small models. The share of code is known to affect reasoning and structuring ability too.
- Repetition: when high-quality data runs short, the same data is seen for several epochs. Muennighoff et al. (2023) measured that up to about 4 epochs it is almost as good as new data, and beyond that its value drops quickly.
Mid-training and annealing
Concentrating high-quality data in the final stretch where the learning rate is lowered to near 0 (annealing) is very effective. With a high learning rate the model “settles” less on recent data, while data seen at a low learning rate leaves a strong mark on the final model. So many recipes put a mid-training stage at the end of pretraining: they raise the share of maths, code and reasoning data, instruction-formatted data and long-context data, and bring the learning rate down to 0. OLMo 2 is an example that separates this stage explicitly. The WSD (warmup-stable-decay) schedule, made of warmup → a long constant phase → a short decay, makes it easy to try several data mixtures by re-running only the decay phase.
Emergence, or an illusion of the metric?
Some abilities (multi-digit addition, certain puzzles) seem to appear suddenly once a model passes a certain size. Schaeffer et al. (2023) showed that much of this suddenness comes from the metric. If the answer is tokens long and the per-token accuracy rises smoothly with size, exact match, which gives credit only when everything is right, is , and this value stays near 0 until gets close to 1, then shoots up. Measured with a continuous metric such as per-token log-prob, the same models give a smooth curve. Not every case of emergence can be explained this way, but it is worth remembering that it is common for the loss to move predictably while benchmarks move like a staircase.
Computing it yourself
First, confirm the basis of 6ND by counting matrix-multiplication FLOPs, and see how large the attention term is.
import numpy as np
def matmul_flops(m, k, n): # (m×k) @ (k×n): m·n·k multiplies and adds each
return 2 * m * k * n
B, d_in, d_out = 1, 4096, 11008 # one linear layer that one token passes through
params = d_in * d_out
fwd = matmul_flops(B, d_in, d_out) # y = x W
bwd = matmul_flops(B, d_out, d_in) + matmul_flops(d_in, B, d_out) # dx = g Wᵀ, dW = xᵀ g
print(f"per parameter: forward {fwd / params:.0f}, backward {bwd / params:.0f}, total {(fwd + bwd) / params:.0f} FLOPs/token")
def model_params(L, d, V): # 12d² per block (attn 4d² + MLP 8d²) + embedding
return 12 * L * d * d + V * d
for name, L, d, V, T in [("GPT-2 small", 12, 768, 50257, 1024), ("7B-class", 32, 4096, 32000, 4096)]:
N = model_params(L, d, V)
attn = 2 * L * T * d # QKᵀ and AV: forward FLOPs per token (Kaplan's 2·n_layer·n_ctx·d)
print(f"{name:<12} N ≈ {N / 1e6:7.0f}M attention term / 2N = {attn / (2 * N):.1%}")
N, D = 70e9, 1.4e12 # Chinchilla
C = 6 * N * D
tput = 400e12 # effective FLOP/s of one GPU (assumption)
print(f"\nChinchilla: C = 6ND = {C:.2e} FLOPs → {C / tput / 3600:,.0f} GPU-hours (assuming effective {tput / 1e12:.0f} TFLOP/s)")Next, minimise the Chinchilla fit numerically. We check that the closed form and a grid search agree, and compute the price of over-training.
E, A, B, alpha, beta = 1.69, 406.4, 410.7, 0.34, 0.28 # Hoffmann et al. (2022) Approach 3 fit
L = lambda N, D: E + A / N**alpha + B / D**beta
def optimal_numeric(C):
logN = np.linspace(6, 14, 80001) # grid search
N = 10**logN
i = np.argmin(L(N, C / (6 * N)))
return N[i], C / (6 * N[i])
G = (alpha * A / (beta * B)) ** (1 / (alpha + beta))
def optimal_closed(C):
N = G * (C / 6) ** (beta / (alpha + beta))
return N, C / (6 * N)
print(" C N_opt D_opt D/N L_opt (closed-form N)")
for C in [1e20, 1e21, 1e22, 1e23, 1e24, 1e25]:
N, D = optimal_numeric(C)
Nc, _ = optimal_closed(C)
print(f"{C:8.0e} {N:9.3g} {D:9.3g} {D / N:5.0f} {L(N, D):.3f} ({Nc:.3g})")
def compute_for_loss(target): # smallest C reaching target loss with optimal allocation
lo, hi = 15.0, 35.0
for _ in range(100):
mid = (lo + hi) / 2
N, D = optimal_closed(10**mid)
lo, hi = (mid, hi) if L(N, D) > target else (lo, mid)
return 10**hi
print("\nover-training: fix C and shrink only N")
C = 1e23
N0, D0 = optimal_closed(C)
for ratio in [1, 1/2, 1/4, 1/10, 1/30]:
N = N0 * ratio; D = C / (6 * N)
Ceq = compute_for_loss(L(N, D))
print(f"N = {ratio:<6.3g}× N_opt ({N:.2g}), D/N = {D / N:7.0f}: L = {L(N, D):.3f}, "
f"optimal compute for same L = {Ceq / C:.2f}× C, inference cost {ratio:.2g}×")Shrinking N to 1/2 of the optimum changes the loss only a little and halves the inference cost. Around 1/10 a good part of the training compute is “wasted”, but if that model serves trillions of tokens, the inference savings quickly exceed it. Finally, a few lines reproduce the emergence illusion. The token NLL falls by a similar ratio at every step, while exact match sticks to 0 until around and then shoots up.
# suppose the NLL of the correct tokens falls smoothly, as a power law in model size
sizes = np.logspace(7, 12, 11)
token_nll = 0.005 + (1e8 / sizes) ** 0.4 # a hypothetical smooth curve (almost straight on log-log)
p_token = np.exp(-token_nll) # probability given to the correct token
k = 10 # if the answer is 10 tokens long, exact match = p^10
print(" N token NLL token prob exact match")
for N, nll, p in zip(sizes, token_nll, p_token):
print(f"{N:9.1e} {nll:6.3f} {p:.3f} {p**k:.3f} " + "█" * int(40 * p**k))Roughly how much compute does it take to pretrain a 7B-parameter model on 2T tokens?
. On GPUs with an effective 400 TFLOP/s that is seconds, about 58,000 GPU-hours. For reference, under the 20 tokens/parameter rule the compute-optimal token count for 7B is 140B, so this model is over-trained by about 14×.
The compute budget grows 100×. With a Chinchilla-style allocation (N and D in the same proportion), roughly how much do the model size and the token count each grow?
With , and , each grows ×. Kaplan-style () would have grown the model about 29× and the data about 3.5×.
Summary
- Training compute : forward 2 (per parameter per token) + backward 4. Inference is about per token.
- Loss follows power laws in , and . Since Chinchilla, the reference point for the optimal allocation at fixed compute is ” and in the same proportion, roughly 20 tokens/parameter”.
- Minimising the parametric fit under gives . The constants are empirical values sensitive to the setting.
- Because of inference cost, real models are deliberately over-trained. The U-shaped curve is flat near the optimum, so the price is smaller than one might think.
- Data quality (filtering, deduplication, mixture, mid-training) greatly changes the value of the same . “Emergence” on benchmarks can be an illusion of non-linear metrics.
그림에서 확인할 것:
- 각 곡선은 U자다. 왼쪽 끝(작은 모델, 많은 토큰)은 모델 용량 항이, 오른쪽 끝(큰 모델, 적은 토큰)은 데이터 항이 loss를 지배한다. 최솟점 근처는 평평해서, 을 최적의 절반이나 두 배로 바꿔도 loss는 조금만 오른다.
- ◆(fit의 최적점)과 ■(D = 20N)이 일치하지 않는다. 이 fit을 그대로 최소화하면 D/N이 수십에서 백 이상으로 나오고 compute가 커질수록 커진다. Besiroglu et al.(2024)은 논문에 보고된 Approach 3의 상수가 데이터를 제대로 fit하지 못하고 다른 두 방법과 어긋난다고 지적했고, 그들이 다시 fit한 결과는 20 토큰/매개변수 규칙과 더 잘 맞았다. 상수 자체보다 “U자 곡선과 그 최솟점이 를 따라 이동한다”는 구조가 요점이다. 또 이 상수들은 특정 데이터·토크나이저·학습 레시피에 대한 것이라 다른 설정에 그대로 옮길 수 없다.
- N/Nopt를 0.1까지 내려 보자. 10배 작은 모델로 같은 compute를 쓰면 loss가 눈에 띄게 오르고, “같은 loss를 최적 배분으로 얻는 compute”는 현재보다 훨씬 적다. 그 차이가 over-training의 학습 비용이다.
Kaplan과 Chinchilla는 왜 달랐나
후속 연구들은 차이의 원인으로 몇 가지를 꼽는다. Kaplan은 학습률 스케줄을 실제 학습 길이에 맞추지 않아 짧게 학습한 모델의 loss가 과대평가되었고, embedding을 뺀 매개변수 수를 썼으며, 상대적으로 작은 모델 위주로 fit했다. 교훈은 스케일링 법칙도 실험 설계에 민감한 경험적 fit이라는 것이다. 외삽(extrapolation)은 측정 범위에서 멀어질수록 불확실하다.
일부러 “비효율적으로” 학습하기: over-training
Chinchilla 최적은 학습 compute만 최소화한다. 그런데 모델을 배포하면 추론 비용이 토큰당 FLOPs씩 평생 든다. 수조 토큰을 서빙할 모델이라면 학습 때 compute를 더 써서라도 작은 모델을 만드는 편이 전체 비용이 싸다(Sardana et al., 2024). 그래서 최근 공개 모델들은 compute-optimal보다 훨씬 많은 토큰으로 학습한다. 예를 들어 Llama 3 8B는 15T 이상의 토큰으로 학습했는데, 매개변수당 약 1,900 토큰으로 20의 거의 100배다. 그림에서 N/Nopt를 왼쪽으로 미는 것이 바로 이 선택이고, 그 대가가 “같은 loss를 최적 배분으로 얻는 compute” 대비 추가 학습 비용이다. 다만 공짜는 아니다. 매개변수당 토큰을 많이 본 모델일수록 학습 후 양자화에 더 민감해진다는 보고도 있다(Kumar et al., 2024, Scaling Laws for Precision).
데이터: 양만큼 중요한 구성
스케일링 법칙의 는 “토큰 수”지만 토큰의 질은 같지 않다. 사전학습 데이터 파이프라인의 주요 단계는 다음과 같다.
- 수집과 추출: 대부분은 Common Crawl 같은 웹 덤프다. HTML에서 본문을 추출하고 언어를 식별한다. 여기에 코드(GitHub), 수학, 논문, 책, 다국어 데이터를 더한다.
- 필터링: 규칙 기반(길이, 기호 비율, 반복) 필터에 더해, 요즘은 “교육적인 글인가” 같은 기준으로 학습한 품질 분류기로 상위 문서만 남기는 방식이 성능을 크게 올린다.
- 중복 제거(dedup): 정확히 같은 문서와 MinHash 같은 방법으로 찾은 거의 같은 문서를 제거한다. 중복은 암기를 늘리고, 같은 데이터를 여러 번 보게 해 compute를 낭비한다(Lee et al., 2022).
- 혼합 비율(data mixture): 웹·코드·수학·다국어를 몇 %씩 섞을지는 작은 모델로 실험해 정한다. 코드 비중은 추론·구조화 능력에도 영향을 준다고 알려져 있다.
- 반복: 고품질 데이터가 부족하면 같은 데이터를 여러 epoch 본다. Muennighoff et al.(2023)은 약 4 epoch까지는 새 데이터와 거의 차이가 없고, 그 이상은 가치가 빠르게 줄어든다고 측정했다.
Mid-training과 annealing
학습률을 끝에서 0 근처까지 낮추는 구간(annealing)에 고품질 데이터를 집중하면 효과가 크다. 학습률이 높을 때는 최근 데이터에 덜 “정착”하고, 낮을 때 본 데이터가 최종 모델에 강하게 남기 때문이다. 그래서 많은 레시피가 사전학습 끝부분에 mid-training 단계를 둔다. 수학·코드·추론 데이터, 지시문 형식의 데이터, 긴 문맥 데이터의 비중을 올리고 학습률을 0까지 내린다. OLMo 2가 이 단계를 명시적으로 분리한 예다. warmup → 긴 일정 구간 → 짧은 감쇠로 이루어진 WSD(warmup-stable-decay) 스케줄은 감쇠 구간만 다시 돌려 여러 데이터 혼합을 실험하기 쉽게 해 준다.
창발인가, 지표의 착시인가
어떤 능력(여러 자리 덧셈, 특정 퍼즐)은 모델이 일정 크기를 넘으면 갑자기 나타나는 것처럼 보인다. Schaeffer et al.(2023)은 이 급격함의 상당 부분이 지표에서 온다고 보였다. 정답이 개 토큰이고 토큰별 정확도 가 크기에 따라 매끄럽게 오른다면, 전부 맞혀야 점수를 주는 exact match는 이고, 이 값은 가 1에 가까워질 때까지 0 근처에 있다가 갑자기 솟는다. 같은 모델을 토큰 단위 log-prob 같은 연속 지표로 재면 매끄러운 곡선이 된다. 모든 창발을 이것으로 설명할 수는 없지만, loss는 예측 가능하게, 벤치마크는 계단처럼 움직이는 일이 흔하다는 점은 기억해 둘 만하다.
직접 계산하기
먼저 6ND의 근거를 행렬곱 FLOPs로 확인하고, attention 항이 얼마나 되는지 본다.
import numpy as np
def matmul_flops(m, k, n): # (m×k) @ (k×n): 곱셈·덧셈 m·n·k번씩
return 2 * m * k * n
B, d_in, d_out = 1, 4096, 11008 # 토큰 1개가 지나는 선형층 하나
params = d_in * d_out
fwd = matmul_flops(B, d_in, d_out) # y = x W
bwd = matmul_flops(B, d_out, d_in) + matmul_flops(d_in, B, d_out) # dx = g Wᵀ, dW = xᵀ g
print(f"매개변수당 forward {fwd / params:.0f}, backward {bwd / params:.0f}, 합 {(fwd + bwd) / params:.0f} FLOPs/토큰")
def model_params(L, d, V): # 블록당 12d² (attn 4d² + MLP 8d²) + embedding
return 12 * L * d * d + V * d
for name, L, d, V, T in [("GPT-2 small", 12, 768, 50257, 1024), ("7B급", 32, 4096, 32000, 4096)]:
N = model_params(L, d, V)
attn = 2 * L * T * d # QKᵀ와 AV: 토큰당 forward FLOPs (Kaplan의 2·n_layer·n_ctx·d)
print(f"{name:<12} N ≈ {N / 1e6:7.0f}M attention 항 / 2N = {attn / (2 * N):.1%}")
N, D = 70e9, 1.4e12 # Chinchilla
C = 6 * N * D
tput = 400e12 # GPU 한 장의 실효 FLOP/s (가정)
print(f"\nChinchilla: C = 6ND = {C:.2e} FLOPs → {C / tput / 3600:,.0f} GPU-시간 (실효 {tput / 1e12:.0f} TFLOP/s 가정)")다음은 Chinchilla fit을 수치적으로 최소화한다. 닫힌 해와 격자 탐색이 같은지 확인하고, over-training의 대가를 계산한다.
E, A, B, alpha, beta = 1.69, 406.4, 410.7, 0.34, 0.28 # Hoffmann et al. (2022) Approach 3 fit
L = lambda N, D: E + A / N**alpha + B / D**beta
def optimal_numeric(C):
logN = np.linspace(6, 14, 80001) # 격자 탐색
N = 10**logN
i = np.argmin(L(N, C / (6 * N)))
return N[i], C / (6 * N[i])
G = (alpha * A / (beta * B)) ** (1 / (alpha + beta))
def optimal_closed(C):
N = G * (C / 6) ** (beta / (alpha + beta))
return N, C / (6 * N)
print(" C N_opt D_opt D/N L_opt (닫힌 해 N)")
for C in [1e20, 1e21, 1e22, 1e23, 1e24, 1e25]:
N, D = optimal_numeric(C)
Nc, _ = optimal_closed(C)
print(f"{C:8.0e} {N:9.3g} {D:9.3g} {D / N:5.0f} {L(N, D):.3f} ({Nc:.3g})")
def compute_for_loss(target): # 최적 배분으로 target loss를 내는 최소 C
lo, hi = 15.0, 35.0
for _ in range(100):
mid = (lo + hi) / 2
N, D = optimal_closed(10**mid)
lo, hi = (mid, hi) if L(N, D) > target else (lo, mid)
return 10**hi
print("\nover-training: C를 고정하고 N만 줄이면")
C = 1e23
N0, D0 = optimal_closed(C)
for ratio in [1, 1/2, 1/4, 1/10, 1/30]:
N = N0 * ratio; D = C / (6 * N)
Ceq = compute_for_loss(L(N, D))
print(f"N = {ratio:<6.3g}× N_opt ({N:.2g}), D/N = {D / N:7.0f}: L = {L(N, D):.3f}, "
f"같은 L의 최적 compute = {Ceq / C:.2f}× C, 추론 비용 {ratio:.2g}×")N을 최적의 1/2로 줄여도 loss 차이는 작고 추론 비용은 절반이 된다. 1/10쯤 되면 학습 compute의 상당 부분이 “낭비”되지만, 그 모델이 수조 토큰을 서빙한다면 추론 절약분이 이를 금방 넘는다. 마지막으로 창발 착시를 몇 줄로 재현한다. 토큰 NLL은 매 단계 비슷한 비율로 줄어드는데, exact match는 근처까지 0에 붙어 있다가 솟는다.
# 모델 크기에 따라 정답 토큰의 NLL이 멱법칙으로 매끄럽게 줄어든다고 하자
sizes = np.logspace(7, 12, 11)
token_nll = 0.005 + (1e8 / sizes) ** 0.4 # 가상의 매끄러운 곡선 (log-log에서 거의 직선)
p_token = np.exp(-token_nll) # 정답 토큰에 준 확률
k = 10 # 정답이 10토큰짜리라면 exact match = p^10
print(" N 토큰 NLL 토큰 확률 exact match")
for N, nll, p in zip(sizes, token_nll, p_token):
print(f"{N:9.1e} {nll:6.3f} {p:.3f} {p**k:.3f} " + "█" * int(40 * p**k))7B 매개변수 모델을 2T 토큰으로 사전학습하는 데 드는 compute는 대략?
. 실효 400 TFLOP/s GPU로는 초, 약 5.8만 GPU-시간이다. 참고로 20 토큰/매개변수 규칙이면 7B의 compute-optimal 토큰 수는 140B이니, 이 모델은 약 14배 over-train된 셈이다.
compute 예산을 100배 늘렸다. Chinchilla식(N, D를 같은 비율로) 배분이라면 모델 크기와 토큰 수는 각각 대략 몇 배?
이고 , 이면 각각 배다. Kaplan식()이었다면 모델을 약 29배, 데이터를 약 3.5배 늘렸을 것이다.
정리
- 학습 compute : forward 2(매개변수·토큰당) + backward 4. 추론은 토큰당 약 .
- loss는 , , 에 대해 멱법칙을 따른다. 고정 compute에서 최적 배분은 Chinchilla 이후 “과 를 같은 비율로, 대략 20 토큰/매개변수”가 기준점이다.
- 파라메트릭 fit 를 아래 최소화하면 . 상수는 설정에 민감한 경험적 값이다.
- 추론 비용 때문에 실제 모델은 의도적으로 over-train한다. 최적점 근처의 U자 곡선이 평평해서 대가가 생각보다 작다.
- 데이터의 질(필터링, 중복 제거, 혼합, mid-training)이 같은 의 가치를 크게 바꾼다. 벤치마크의 “창발”은 비선형 지표의 착시일 수 있다.
더 읽을거리Further reading
- Kaplan et al., Scaling Laws for Neural Language Models (2020) — loss가 N, D, C에 대해 멱법칙을 따른다는 첫 체계적 측정. C ≈ 6N 연산 계산의 출처.The first systematic measurement that loss follows power laws in N, D and C. Source of the C ≈ 6N operation count.
- Hoffmann et al., Training Compute-Optimal Large Language Models (Chinchilla, NeurIPS 2022) — 세 가지 방법으로 compute-optimal 배분을 추정해 N과 D를 같은 비율로 키우라고 결론. 이 레슨 그림의 fit 상수 출처.Estimates the compute-optimal allocation with three methods and concludes that N and D should grow in the same proportion. Source of the fit constants in this lesson's figure.
- Besiroglu, Erdil, Barnett, You, Chinchilla Scaling: A replication attempt (2024) — Chinchilla의 파라메트릭 fit(Approach 3)을 재현하며 보고된 상수가 다른 두 방법과 어긋난다는 점을 지적.Reproduces Chinchilla's parametric fit (Approach 3) and points out that the reported constants disagree with the other two methods.
- Sardana, Portes, Doubov, Frankle, Beyond Chinchilla-Optimal: Accounting for Inference in Language Model Scaling Laws (ICML 2024) — 추론 수요까지 넣으면 compute-optimal보다 작은 모델을 오래 학습하는 것이 최적.Once inference demand is included, it is optimal to train a model smaller than compute-optimal for longer.
- Muennighoff et al., Scaling Data-Constrained Language Models (NeurIPS 2023) — 데이터가 부족할 때 반복 학습(epoch)의 가치를 측정. 몇 epoch까지는 새 데이터와 거의 같다.Measures the value of repeated training (epochs) when data is scarce: up to a few epochs is almost as good as new data.
- Lee et al., Deduplicating Training Data Makes Language Models Better (ACL 2022) — 정확·근사 중복 제거가 암기를 줄이고 같은 성능을 더 적은 step에 낸다.Exact and near-duplicate removal reduces memorisation and reaches the same performance in fewer steps.
- Schaeffer, Miranda, Koyejo, Are Emergent Abilities of Large Language Models a Mirage? (NeurIPS 2023) — 급격한 "창발"의 상당 부분이 exact-match 같은 비선형 지표에서 온다는 분석.An analysis showing that much of the sudden "emergence" comes from non-linear metrics such as exact match.