바이트에서 학습된 Transformer까지: 언어 모델 처음부터 만들기
CPU용 프로젝트: 바이트 인코딩, 인과 어텐션, 손실, AdamW, 체크포인트, 생성. 실행 가능한 Python과 한계를 설명합니다.
출처 및 버전 정보
이 글의 목차
1. 무엇을 만들며 언어 모델은 무엇을 배우는가
“node 107: status is”를 완성하는 운영 콘솔을 생각해 보세요. 인과 Transformer의 가중치를 무작위로 초기화하고 직접 만든 합성 말뭉치로 학습한 뒤 체크포인트를 저장하고 바이트를 생성합니다. 사전 학습 가중치, 외부 데이터셋, 모델 API는 필요 없습니다. PyTorch의 텐서, 자동 미분, 최적화기를 사용하므로 처음부터란 구조와 학습 흐름을 구현한다는 뜻이지 GPU 커널까지 작성한다는 뜻은 아닙니다.
학습부터 생성까지의 전체 흐름
작은 화면에서는 가로로 스크롤하거나 원본 크기로 여세요. 원본 그림 보기
언어 모델은 앞선 토큰에 조건화한 다음 토큰 분포를 추정합니다. 가중치는 통계적 규칙을 담으며 검증된 사실 데이터베이스가 아닙니다. 134,912개 파라미터 모델은 CPU에서 실행되지만 범용 비서나 지시 수행 모델은 아닙니다. 상태 문장의 형식을 배우는 것과 어느 노드가 바쁜지 아는 것은 다릅니다.
행렬 곱, 확률 분포, 연쇄 법칙이 선행 지식입니다. 행렬 곱은 특징을 섞고 softmax는 점수를 확률로 바꾸며 연쇄 법칙은 오차 신호를 각 층으로 전달합니다. 익숙하지 않다면 글 끝의 기초 자료부터 보세요.
2. 환경과 프로젝트 파일 준비
전체 프로젝트를 새 디렉터리에 압축 해제한다. tiny_lm.py에는 모델·말뭉치·학습·검사가 있고 generate.py는 옆에 두는 추론 진입점이다. 각 함수를 다시 구현할 때 참조한다. 본문 코드는 실제 프로젝트의 발췌이며 무조건 이어 붙이는 독립 프로그램이 아니다.
측정 환경은 Linux, Python 3.12, PyTorch 2.5.1 CPU다. 가상 환경에 고정 버전을 설치한다. 설치는 소프트웨어를 내려받지만 학습은 내장 원본 데이터를 쓰며 API나 GPU가 필요 없다. 다른 환경은 호환 공식 wheel이 필요하고 수치가 조금 다를 수 있다.
산출물 tiny.pt는 설정·가중치·최적화기·단계·난수 상태를 저장한다. 먼저 구성 방법을 배우고 별도 프로세스에서 읽는다. 학습·검사·생성 명령은 마지막 실습에서 실행한다. 시작 시 사전 학습 가중치는 필요 없다.
unzip from-zero-lm.zip -d tokenlab-lm
cd tokenlab-lm
python3.12 -m venv .venv
. .venv/bin/activate
python -m pip install torch==2.5.1 --index-url https://download.pytorch.org/whl/cpu3. 문서에서 학습 쌍으로
말뭉치는 문서 120개로 짝수 ID는 ready, 홀수는 busy입니다. 창을 만들기 전에 0–99는 학습, 100–119는 검증으로 분리합니다. 같은 문서의 창이 두 집합에 흩어지는 것은 막지만 문법 템플릿은 동일하므로 작은 합성 분포 안에서의 보간을 측정합니다.
UTF-8 바이트는 토크나이저 학습 없이
T+1 바이트 중 앞 T개는 입력, 뒤 T개는 정답입니다. [65,66,67,10]은 [65,66,67] → [66,67,10]이 됩니다. 배치 형태는 [B,T]입니다. 문서 연결 시 줄바꿈을 넘는 창이 생기므로 부적절하다면 문서 경계와 손실 마스크를 넣어야 합니다.
데이터 계약 구현
학습 루프 전에 tiny_lm.py에 corpus()와 batch()를 구현한다. corpus()는 두 바이트열을 반환하고 batch()는 선택한 분할만 torch.long ID로 바꾼다. T+1바이트가 필요하므로 N바이트에서 유효 시작점은 0부터 N−T−1까지 N−T개다. 각 샘플은 길이 32인 입력과 정답을 반환하며 16개를 묶으면 둘 다 [16,32]다. 매번 시드를 초기화하지 말고 같은 난수 생성기의 상태를 진행시킨다.
구현 발췌 · 실행할 때 전체 프로젝트 사용
def corpus():
# Original synthetic sentences. Split document IDs BEFORE window extraction.
docs = [f'node {i:03d}: status is {"ready" if i % 2 == 0 else "busy"}.\n' for i in range(120)]
return ''.join(docs[:100]).encode(), ''.join(docs[100:]).encode()
def batch(raw, generator, size=16):
data=torch.tensor(list(raw), dtype=torch.long)
t=CFG['context']
starts=torch.randint(len(data)-t, (size,), generator=generator)
return torch.stack([data[i:i+t] for i in starts]), torch.stack([data[i+1:i+t+1] for i in starts])분할은 통계적 경계다. --text 사용 전에 말뭉치를 준비하고 각 분할을 32바이트보다 크게 만든다. 구현은 문서를 연결하며 문서 단위 마스크나 중복 제거를 제공하지 않는다. 데이터를 늘리면 분포와 각 구절이 추출되는 빈도가 함께 바뀐다.
하나의 시퀀스에서 세 개의 예측 목표로
작은 화면에서는 가로로 스크롤하거나 원본 크기로 여세요. 원본 그림 보기
4. 인과 경계를 가진 가중 읽기, 어텐션
구현은
softmax 전에 미래 키 j>i를 −∞로 가리고 키 축으로 정규화한 뒤 V와 곱합니다. 스케일된 logits [0,log 3]은 확률 [0.25,0.75]입니다. 값 [2,0], [0,4]의 가중합은 [0.5,3]입니다. 첫 위치에서 두 번째 키를 가리면 [2,0]만 남습니다. 안정적인 softmax를 사용하며 배치 축으로 정규화하면 안 됩니다.
네 [T,16] 헤드를 [T,64]로 합친 후 출력 투영합니다. 점수만 float32 65,536개, 층당 256 KiB입니다. 밀집 어텐션은 T에 대해 제곱 비용이며 별도 투영 비용도 있습니다. FlashAttention과 KV 캐시는 구현하지 않았습니다. 어텐션 가중치는 혼합 계수이지 인과 설명의 증명이 아닙니다.
헤드 분할과 결합 추적
QKV 투영은 [16,32,64]를 [16,32,192]로 바꾸고 chunk는 폭 64인 세 텐서를 반환한다. 각각 [16,32,4,16]으로 reshape한 뒤 시간축과 헤드축을 바꿔 [16,4,32,16]을 만든다. 점수는 [16,4,32,32]이며 마지막 축이 key이므로 softmax(dim=-1)은 query별 참조 위치를 정규화한다. 삼각 마스크는 배치와 헤드에 broadcast되는 저장 buffer이며 학습 파라미터가 아니다.
구현 발췌 · 실행할 때 전체 프로젝트 사용
class Attention(nn.Module):
def __init__(self, width, heads, context):
super().__init__()
assert width % heads == 0
self.heads, self.dim = heads, width // heads
self.qkv = nn.Linear(width, 3 * width)
self.out = nn.Linear(width, width)
self.register_buffer('mask', torch.ones(context, context, dtype=torch.bool).tril())
def forward(self, x):
b, t, c = x.shape
q, k, v = self.qkv(x).chunk(3, dim=-1)
q, k, v = [a.view(b, t, self.heads, self.dim).transpose(1, 2) for a in (q, k, v)]
scores = q @ k.transpose(-2, -1) / math.sqrt(self.dim)
scores = scores.masked_fill(~self.mask[:t, :t], float('-inf'))
mixed = scores.softmax(dim=-1) @ v
return self.out(mixed.transpose(1, 2).contiguous().view(b, t, c))집계 결과 [16,4,32,16]을 전치하고 contiguous로 만든 뒤 폭 64로 결합한다. 전치를 생략하면 시간과 헤드 특징이 섞인다. 분모는 헤드 차원의 √16=4이지 모델 폭의 √64=8이 아니다. softmax 후 단순히 0으로 만들면 확률합이 줄어들므로 정규화 전에 점수를 가린다.
인과 어텐션: 마스크에서 가중 벡터까지
작은 화면에서는 가로로 스크롤하거나 원본 크기로 여세요. 원본 그림 보기
5. 디코더의 모든 텐서 추적
각 pre-norm 블록은 LayerNorm(X)의 어텐션 출력을 잔차로 더한 뒤 새 상태를 정규화하여 FFN에 넣습니다. FFN은 위치별로 64→256, GELU, 256→64를 수행합니다. 어텐션은 위치를 섞고 FFN은 특징을 변환합니다. 잔차 경로는 깊이를 통과하는 직접 경로를 남기지만 모든 최적화 문제를 해결하지는 않습니다.
최종 LayerNorm과 독립된 [64,256] 출력 투영이 [16,32,256] logits를 만듭니다. 입력과 출력 가중치는 공유하지 않습니다. 총 134,912개 파라미터이며 float32 가중치만 539,648바이트입니다. 기울기, Adam 상태, 활성값 메모리는 별도입니다.
LayerNorm은 각 토큰의 D개 특징에서 평균과 분산을 구하고 학습된 스케일과 편향을 적용합니다. 다른 샘플이나 미래를 섞지 않습니다. GELU는 비선형성을 더합니다. 수식은 열벡터로
의존 순서대로 디코더 조립
Attention, Block, TinyLM 순서로 구현한다. nn.Module이 하위 계층을 등록하므로 parameters()와 state_dict()가 가중치를 추적한다. ID는 embedding 행의 인덱스이며 수치 크기로 곱하는 값이 아니다. 위치 embedding은 같은 바이트가 나타난 위치를 구분한다. 잔차 덧셈은 원소별 연산이므로 분기 출력도 [B,T,D]여야 한다. 두 블록 뒤 선형 헤드가 64개 특징을 정규화하지 않은 256개 점수로 변환한다.
구현 발췌 · 실행할 때 전체 프로젝트 사용
class Block(nn.Module):
def __init__(self, c):
super().__init__()
d=c['width']
self.n1, self.n2 = nn.LayerNorm(d), nn.LayerNorm(d)
self.attn = Attention(d, c['heads'], c['context'])
self.ff = nn.Sequential(nn.Linear(d, 4*d), nn.GELU(), nn.Linear(4*d, d))
def forward(self, x):
x = x + self.attn(self.n1(x))
return x + self.ff(self.n2(x))
class TinyLM(nn.Module):
def __init__(self, cfg=CFG):
super().__init__()
self.cfg = cfg
self.tokens = nn.Embedding(cfg['vocab'], cfg['width'])
self.positions = nn.Embedding(cfg['context'], cfg['width'])
self.blocks = nn.Sequential(*[Block(cfg) for _ in range(cfg['layers'])])
self.norm = nn.LayerNorm(cfg['width'])
self.head = nn.Linear(cfg['width'], cfg['vocab'], bias=False)
self.apply(self.init)
@staticmethod
def init(m):
if isinstance(m, (nn.Linear, nn.Embedding)):
nn.init.normal_(m.weight, std=.02)
if getattr(m, 'bias', None) is not None: nn.init.zeros_(m.bias)
def forward(self, ids):
if ids.ndim != 2 or not 0 < ids.shape[1] <= self.cfg['context']:
raise ValueError('Expected [batch, time], 1 <= time <= context')
x = self.tokens(ids) + self.positions(torch.arange(ids.shape[1], device=ids.device))
return self.head(self.norm(self.blocks(x)))생성과 재로드에서 CFG를 단일 구조 정의로 사용한다. 폭·어휘·계층 수가 바뀌면 가중치 형태도 달라져 이전 체크포인트를 그대로 사용할 수 없다. forward는 32개를 넘는 위치를 거부한다. 문맥 확장은 위치표와 마스크 수정 및 어텐션 메모리의 제곱 증가를 함께 고려해야 한다.
| 단계 | 입력 → 출력 | 경계 |
|---|---|---|
| 임베딩 | [B,T] → [B,T,D] | |
| Q / K / V | [B,T,D] → [B,H,T,D/H] | 64 ÷ 4 = 16 |
| 어텐션 | [B,H,T,T] × [B,H,T,D/H] | j≤i |
| 출력 투영 | [B,T,D] → [B,T,V] | 파라미터 134,912개 |
| 손실 | [BT,V] + [BT] → scalar | nats / byte |
6. 손실, 기울기, 갱신 루프
teacher forcing에서는 실제 이전 바이트를 입력합니다. logits [B,T,V]를 [BT,V], 정답을 [BT]로 펴서 원시 logits를 cross_entropy에 넣습니다. 먼저 softmax를 적용하면 안 됩니다. 정답 확률 0.25의 손실은 −
각 단계에서 기존 기울기를 비우고 손실 계산, 역전파, 전체 기울기 노름을 1로 제한한 뒤 AdamW를 적용합니다. 일차·이차 모멘트가 갱신 크기를 조절하고 가중치 감쇠는 별도로 작동합니다. 여기서는 모든 파라미터를 감쇠하지만 편향과 정규화를 제외하는 방식도 실험 조건으로 명시할 수 있습니다.
명목상 최대 학습률은 0.002이며 20단계 워밍업과 마지막에 10%에 가까워지는 코사인 계수를 곱합니다. 가중치, 모멘트, 설정, 단계, 난수 상태를 저장합니다. 재로드는 확인하지만 resume 명령은 없으므로 완전한 재시작에는 스케줄과 데이터 순서 복원도 필요합니다.
logit에 대한 교차 엔트로피 미분은 pᵢ−1[
출력층만 보면 h는 정규화된 [D,1] 열벡터, 저장 가중치 W는 [V,D],
한 번의 갱신으로 학습 루프 구성
매 단계 새 배치를 얻고 학습률을 설정한 뒤 기울기를 지운다. loss()는 16×32 위치를 256클래스 분류 샘플 512개로 펼친다. backward()는 parameter.grad에 누적하고 opt.step()은 이를 이용해 갱신하므로 의도적 누적이 아니라면 이전 기울기를 지워야 한다. 300단계의 153,600개 표본 위치에는 중복이 있으며 고유 바이트 수나 epoch 수가 아니다.
구현 발췌 · 실행할 때 전체 프로젝트 사용
def loss(model, x, y):
logits=model(x)
return F.cross_entropy(logits.reshape(-1, CFG['vocab']), y.reshape(-1))opt=torch.optim.AdamW(model.parameters(),lr=.002,weight_decay=.01)
before=heldout_loss(model,val)
for step in range(args.steps):
model.train();x,y=batch(train,generator)
lr=.002*min((step+1)/20,1)*(.1+.9*.5*(1+math.cos(math.pi*step/args.steps)))
for group in opt.param_groups:group['lr']=lr
opt.zero_grad(set_to_none=True);value=loss(model,x,y)
if not torch.isfinite(value):raise RuntimeError('nonfinite loss')
value.backward();nn.utils.clip_grad_norm_(model.parameters(),1.0);opt.step()스케줄은 warmup과 cosine의 곱이며 warmup 중에도 cosine이 진행되어 실제 최댓값은 0.002보다 약간 작다. 가중치와 최적화기 상태는 따로 저장한다. 기울기 자체가 학습된 모델은 아니다. 저장 상태는 향후 재개에 쓰일 수 있지만 생성에서는 가중치만 읽으며 중단 없는 학습과의 완전한 동등성을 구현하지 않는다.
예측 오차에서 가중치 갱신까지
작은 화면에서는 가로로 스크롤하거나 원본 크기로 여세요. 원본 그림 보기
7. 체크포인트에서 텍스트 생성까지
비어 있지 않은 프롬프트의 마지막 32바이트를 사용하고 마지막 위치의 logits만 취합니다. 양의 온도로 나누고 top-k를 남겨 정규화한 뒤 바이트 하나를 샘플링하여 반복합니다. EOS 없이 고정 바이트 수에서 멈춥니다. 낮은 온도가 분포를 좁혀도 사실성을 보장하지는 않습니다.
창을 자를 때마다 학습 위치를 0…31로 재설정하고 오래된 문맥은 잊습니다. 전체 창 재계산은 단순하지만 비쌉니다. KV 캐시는 위치 일관성과 무효화를 처리해야 하므로 위치를 재설정하면서 캐시를 단순 추가하면 같은 결과가 나오지 않습니다.
불완전한 UTF-8은 대체 문자로 변환됩니다. ASCII 말뭉치는 문제를 줄입니다. 유용한 비서에는 더 넓은 적법 데이터, 용량, 지시 학습, 운영 기반, 안전 검증이 필요합니다. 이 작은 모델은 별도 Agent도 안정적으로 구동하지 못하므로 해당 프로젝트에는 다른 로컬 지시 모델용 어댑터가 있습니다.
별도 프로세스에서 체크포인트 로드
generate.py를 tiny_lm.py 옆에 두고 TinyLM을 import한다. main 보호 조건 덕분에 import 시 학습이 시작되지 않는다. CPU로 읽고 저장 config로 생성한 뒤 model 상태를 로드하고 eval로 전환한다. 초기화도 난수를 쓰므로 생성 후 샘플링 시드를 다시 설정한다. 학습 산출물과 추론 진입점을 분리해 같은 환경에서 비교할 수 있다.
구현 발췌 · 실행할 때 전체 프로젝트 사용
"""Generate from a trusted checkpoint without retraining."""
import argparse,torch
from tiny_lm import TinyLM
p=argparse.ArgumentParser();p.add_argument('checkpoint');p.add_argument('--prompt',default='node 10');p.add_argument('--seed',type=int,default=42)
a=p.parse_args();torch.set_num_threads(1);torch.manual_seed(a.seed)
s=torch.load(a.checkpoint,map_location='cpu',weights_only=True)
m=TinyLM(s['config']);m.load_state_dict(s['model']);m.eval()
torch.manual_seed(a.seed)
print(m.generate(a.prompt))
학습 후 python generate.py tiny.pt --prompt "node 10"을 실행한다. 입력과 새 80바이트를 반환하는 CLI이며 HTTP API, 지시 튜닝, Agent 프로토콜은 없다. 제한과 큐를 갖춘 서버는 향후 확장이다. weights_only가 출처를 보장하지 않으므로 신뢰하는 체크포인트만 사용한다.
자기회귀 생성: 한 번에 한 바이트
작은 화면에서는 가로로 스크롤하거나 원본 크기로 여세요. 원본 그림 보기
8. 실습, 검증, 면접 연습
형태, 미래 비간섭, 문맥 한계, 한 가중치의 유한 차분, 재로드 logits 일치를 확인합니다. 말뭉치, 분할, seed, 단계, 검증을 고정하고 bigram, 1/2 블록, 무작위/학습 모델을 비교하세요. 손실과 홀짝 규칙 정확도를 따로 보고하고 3개 이상 seed를 사용합니다. 마스크 제거는 누수 시연일 뿐 유효한 경쟁 모델이 아닙니다. 자체 데이터는 허가와 분할을 먼저 확인하세요.
전체 구현과 명령
python tiny_lm.py --steps 300 --output tiny.pt
python generate.py tiny.pt --prompt 'node 10'
# Optional: your own licensed UTF-8 text, after data preparation
# python tiny_lm.py --text corpus.txt --steps 300 --output own.pttiny_lm.py
"""Original Token Lab byte-level causal LM. Python 3.12 / torch 2.5.1 CPU.
Run: python tiny_lm.py --steps 300 --output tiny.pt
No pretrained weights, downloads, model API or third-party dataset.
"""
import argparse
import math
from pathlib import Path
import torch
from torch import nn
from torch.nn import functional as F
CFG = dict(vocab=256, context=32, width=64, heads=4, layers=2)
class Attention(nn.Module):
def __init__(self, width, heads, context):
super().__init__()
assert width % heads == 0
self.heads, self.dim = heads, width // heads
self.qkv = nn.Linear(width, 3 * width)
self.out = nn.Linear(width, width)
self.register_buffer('mask', torch.ones(context, context, dtype=torch.bool).tril())
def forward(self, x):
b, t, c = x.shape
q, k, v = self.qkv(x).chunk(3, dim=-1)
q, k, v = [a.view(b, t, self.heads, self.dim).transpose(1, 2) for a in (q, k, v)]
scores = q @ k.transpose(-2, -1) / math.sqrt(self.dim)
scores = scores.masked_fill(~self.mask[:t, :t], float('-inf'))
mixed = scores.softmax(dim=-1) @ v
return self.out(mixed.transpose(1, 2).contiguous().view(b, t, c))
class Block(nn.Module):
def __init__(self, c):
super().__init__()
d=c['width']
self.n1, self.n2 = nn.LayerNorm(d), nn.LayerNorm(d)
self.attn = Attention(d, c['heads'], c['context'])
self.ff = nn.Sequential(nn.Linear(d, 4*d), nn.GELU(), nn.Linear(4*d, d))
def forward(self, x):
x = x + self.attn(self.n1(x))
return x + self.ff(self.n2(x))
class TinyLM(nn.Module):
def __init__(self, cfg=CFG):
super().__init__()
self.cfg = cfg
self.tokens = nn.Embedding(cfg['vocab'], cfg['width'])
self.positions = nn.Embedding(cfg['context'], cfg['width'])
self.blocks = nn.Sequential(*[Block(cfg) for _ in range(cfg['layers'])])
self.norm = nn.LayerNorm(cfg['width'])
self.head = nn.Linear(cfg['width'], cfg['vocab'], bias=False)
self.apply(self.init)
@staticmethod
def init(m):
if isinstance(m, (nn.Linear, nn.Embedding)):
nn.init.normal_(m.weight, std=.02)
if getattr(m, 'bias', None) is not None: nn.init.zeros_(m.bias)
def forward(self, ids):
if ids.ndim != 2 or not 0 < ids.shape[1] <= self.cfg['context']:
raise ValueError('Expected [batch, time], 1 <= time <= context')
x = self.tokens(ids) + self.positions(torch.arange(ids.shape[1], device=ids.device))
return self.head(self.norm(self.blocks(x)))
@torch.no_grad()
def generate(self, prompt, count=80, temperature=.8, top_k=20):
if not prompt or temperature <= 0 or not 1 <= top_k <= self.cfg['vocab']:
raise ValueError('Nonempty prompt, positive temperature, valid top_k required')
self.eval()
ids = torch.tensor([list(prompt.encode('utf-8'))], dtype=torch.long)
for _ in range(count):
logits = self(ids[:, -self.cfg['context']:])[:, -1, :] / temperature
threshold = logits.topk(top_k).values[:, -1:]
logits = logits.masked_fill(logits < threshold, float('-inf'))
ids = torch.cat((ids, torch.multinomial(logits.softmax(-1), 1)), dim=1)
return bytes(ids[0].tolist()).decode('utf-8', errors='replace')
def corpus():
# Original synthetic sentences. Split document IDs BEFORE window extraction.
docs = [f'node {i:03d}: status is {"ready" if i % 2 == 0 else "busy"}.\n' for i in range(120)]
return ''.join(docs[:100]).encode(), ''.join(docs[100:]).encode()
def batch(raw, generator, size=16):
data=torch.tensor(list(raw), dtype=torch.long)
t=CFG['context']
starts=torch.randint(len(data)-t, (size,), generator=generator)
return torch.stack([data[i:i+t] for i in starts]), torch.stack([data[i+1:i+t+1] for i in starts])
def loss(model, x, y):
logits=model(x)
return F.cross_entropy(logits.reshape(-1, CFG['vocab']), y.reshape(-1))
@torch.no_grad()
def heldout_loss(model, raw):
model.eval()
data=torch.tensor(list(raw),dtype=torch.long)
total, count=0.,0
for i in range(0,len(data)-1,CFG['context']):
t=min(CFG['context'],len(data)-1-i)
x,y=data[i:i+t][None,:],data[i+1:i+t+1][None,:]
total += loss(model,x,y).item()*t
count += t
return total/count
def checks(model):
model.eval()
x=torch.arange(12)[None,:]
changed=x.clone();changed[:,7:]=200
with torch.no_grad():
a,b=model(x),model(changed)
assert a.shape == (1,12,256)
assert torch.allclose(a[:,:7],b[:,:7],atol=1e-6), 'future leak'
try:model(torch.zeros(1,33,dtype=torch.long))
except ValueError:pass
else:raise AssertionError('context overflow accepted')
# One coordinate of the readout gradient, central finite difference.
target=torch.arange(1,13)[None,:]
model.zero_grad(set_to_none=True)
loss(model,x,target).backward()
analytical=model.head.weight.grad[1,0].item()
original=model.head.weight[1,0].item();eps=.01
with torch.no_grad():
model.head.weight[1,0]=original+eps;plus=loss(model,x,target).item()
model.head.weight[1,0]=original-eps;minus=loss(model,x,target).item()
model.head.weight[1,0]=original
assert abs(analytical-(plus-minus)/(2*eps))<.002, 'gradient mismatch'
def main():
p=argparse.ArgumentParser();p.add_argument('--steps',type=int,default=300)
p.add_argument('--output',default='tiny.pt');p.add_argument('--text',help='Optional owned UTF-8 corpus; chronological 90/10 split')
args=p.parse_args()
if args.steps<1:raise ValueError('steps must be positive')
torch.set_num_threads(1);torch.manual_seed(42);torch.use_deterministic_algorithms(True)
generator=torch.Generator().manual_seed(123)
train,val=corpus()
if args.text:
raw=Path(args.text).read_text(encoding='utf-8').encode();cut=int(.9*len(raw));train,val=raw[:cut],raw[cut:]
if min(len(train),len(val))<=CFG['context']:raise ValueError('each split must exceed context')
model=TinyLM();checks(model)
opt=torch.optim.AdamW(model.parameters(),lr=.002,weight_decay=.01)
before=heldout_loss(model,val)
for step in range(args.steps):
model.train();x,y=batch(train,generator)
lr=.002*min((step+1)/20,1)*(.1+.9*.5*(1+math.cos(math.pi*step/args.steps)))
for group in opt.param_groups:group['lr']=lr
opt.zero_grad(set_to_none=True);value=loss(model,x,y)
if not torch.isfinite(value):raise RuntimeError('nonfinite loss')
value.backward();nn.utils.clip_grad_norm_(model.parameters(),1.0);opt.step()
after=heldout_loss(model,val)
torch.save({'config':CFG,'model':model.state_dict(),'optimizer':opt.state_dict(),
'step':args.steps,'rng':torch.get_rng_state(),'batch_rng':generator.get_state()},args.output)
saved=torch.load(args.output,weights_only=True);restored=TinyLM(saved['config']);restored.load_state_dict(saved['model']);restored.eval();model.eval()
probe=torch.tensor([[1,2,3]])
assert torch.equal(model(probe),restored(probe)), 'checkpoint mismatch'
checks(model)
print(f'parameters={sum(p.numel() for p in model.parameters())}')
print(f'validation_nats_per_byte: {before:.6f} -> {after:.6f}')
print(f'validation_perplexity_per_byte={math.exp(after):.6f}')
print('checks: shapes, causal mask, context bound, gradient, checkpoint passed')
if not args.text and args.steps>=300:assert after<before, 'synthetic learning failed'
torch.manual_seed(42);print('sample='+repr(model.generate('node 10')))
if __name__=='__main__':main()
generate.py
"""Generate from a trusted checkpoint without retraining."""
import argparse,torch
from tiny_lm import TinyLM
p=argparse.ArgumentParser();p.add_argument('checkpoint');p.add_argument('--prompt',default='node 10');p.add_argument('--seed',type=int,default=42)
a=p.parse_args();torch.set_num_threads(1);torch.manual_seed(a.seed)
s=torch.load(a.checkpoint,map_location='cpu',weights_only=True)
m=TinyLM(s['config']);m.load_state_dict(s['model']);m.eval()
torch.manual_seed(a.seed)
print(m.generate(a.prompt))
관측 결과와 검증 한계
Python 3.12, PyTorch 2.5.1+cpu, CPU 스레드 1개, 초기화 seed 42, 배치 seed 123으로 300단계 실행했습니다. 손실은 5.575623→0.546086 nats/byte, perplexity는 1.726483입니다. 합성 자료 실측이지 자연어 벤치마크가 아닙니다. 생성 node 046은 짝수인데 busy여서 낮은 손실이 규칙 학습을 증명하지 않음을 보여 줍니다. 32바이트마다 문맥을 초기화하고 토큰 수로 가중합니다. 플랫폼별 미세 차이는 가능합니다.
parameters=134912
validation_nats_per_byte: 5.575623 -> 0.546086
validation_perplexity_per_byte=1.726483
checks: shapes, causal mask, context bound, gradient, checkpoint passed
sample='node 107: status is busy.\nnode 046: status is busy.\nnode 096: status is ready.\nnode 081'
첫 실행 후 문제 해결
| 증상 | 의미 | 다음 조치 |
|---|---|---|
| ModuleNotFoundError: torch | 실행 Python이 의존성을 찾지 못한다. | .venv를 활성화하고 python -m pip --version과 sys.executable을 비교해 같은 Python으로 설치한다. |
| 체크포인트 없음·형태 불일치 | 학습 미완료·경로 오류·설정 변경. | --output 경로와 저장 config를 사용하고 형태 오류를 무시하지 않는다. 구조 변경 후 재학습한다. |
| 낮은 손실·잘못된 상태 | 바이트 예측과 규칙 정확도는 다르다. | 짝홀 규칙 정확도를 별도로 측정하고 학습 조건과 프롬프트를 고정한다. |
독창적 연습 문제이며 실제 기업 기출이 아닙니다
문항별 1–5점: 1 용어, 2 정확한 정의, 3 예제 추적, 4 실패와 대응 설명, 5 공정한 비교 및 증거 한계. 코드만으로는 만점이 아닙니다.
1. 인과 마스크를 없애면 왜 좋아 보이나요?
힌트
이동된 정답 위치를 찾으세요.
답과 분석
다음 바이트가 입력의 미래에 있어 학습 때 훔쳐볼 수 있습니다. 누수입니다. 미래를 바꿔도 과거 logits는 같아야 합니다.
2. perplexity 1.73이 유용한 비서를 증명하지 못하는 이유는?
힌트
말뭉치, 단위, 생성 오류를 보세요.
답과 분석
반복 문법의 바이트 perplexity이지 정확도가 아닙니다. node 046은 규칙을 어깁니다. 독립 작업과 분포를 평가하세요.
3. 폭 64와 128을 같은 단계 수로 공정하게 비교할 수 있나요?
힌트
데이터 노출량과 연산량을 구분하세요.
답과 분석
동일 단계는 데이터만 통제합니다. 투영 비용은 대략 D²입니다. 데이터 고정과 실측 연산 예산 고정을 구분하고 seed를 반복하세요.
4. 가중치만으로 정확한 학습 재개가 안 되는 이유는?
힌트
다음 갱신에 영향을 주는 상태를 추적하세요.
답과 분석
모멘트, 스케줄, 난수, 데이터 위치가 영향을 줍니다. 예제는 재로드까지만 구현합니다. resume 추가 시 연속 실행과 비교하세요.
선수 지식을 이해하기
방법을 뒷받침하는 공통 기초를 복습하고 예제와 확인 문제로 이해의 빈틈을 찾습니다.
신경망은 여러 함수의 합성입니다. 입력 X의 형상 [B,d]에서 B는 샘플 수, d는 샘플의 특징 수입니다. [d,h]인 가중치 W를 곱하면 샘플마다 h개의 가중합이 생기고 [h]인 편향이 각 행에 더해집니다.
출력 원소 하나를 손으로 계산하고 안쪽 차원이 같아야 하는 이유를 설명할 수 있어야 합니다. 활성화 함수가 비선형성을 더합니다. 아핀 층만 쌓으면 전체도 여전히 아핀 변환입니다.
여기서는 샘플을 행으로 둡니다. 뒤의 단일 샘플 열벡터 표기에서는 가중치가 [h,d]로 이 행렬의 전치이며 같은 변환을 뜻합니다.
답을 보기 전에 추론하기
미분은 작은 변화에 대한 국소적 민감도입니다. 연쇄 법칙은 예측에 대한 손실의 민감도와 가중치에 대한 예측의 민감도를 연결합니다.
단계별 해설
예측은 2이고 손실은 0.5입니다. 두 미분은 −1과 2이므로 곱하면 dL/
실제 응용과의 연결
XOR는 이 계산을 은닉 표현으로 확장합니다. (0,0)과 (1,1)은 라벨 0, 나머지 두 점은 라벨 1이며 직선 하나로 나눌 수 없습니다. 비선형 층으로 표현을 바꾸면 마지막 선형 분류기가 분리할 수 있습니다. 이는 특징 학습의 작은 예이며 대형 모델의 능력을 입증하는 실험은 아닙니다.
이해를 입증하는 방법
각 단계의 형상을 쓰고 매끄러운 지점에서 중심 차분과 해석적 기울기를 비교하세요. 차분 간격을 바꾸어 반올림 오차도 확인하세요. 같은 데이터와 예산에서 선형·비선형 모델을 비교하세요. XOR 네 행을 암기하는 것은 일반화 증거가 아니며 별도의 홀드아웃 과제나 분할이 필요합니다.
완전한 Python 예제 실행
Python 3.10+ · 표준 라이브러리만 · 결정적 계산으로 시드 불필요 · 통신 없음. 저장 후 아래 명령을 실행하세요. 교육용 확인이며 모델 벤치마크가 아닙니다.
Python 다운로드 · neural.pypython3 neural.py# Python 3.10+; standard library; deterministic; no network.
from math import isclose
def loss(w):
return (w * 2.0 - 3.0) ** 2 / 2
w, learning_rate = 1.0, 0.1
gradient = (w * 2.0 - 3.0) * 2.0
h = 1e-5
numeric = (loss(w + h) - loss(w - h)) / (2 * h)
assert isclose(gradient, numeric, abs_tol=1e-8)
w_new = w - learning_rate * gradient
assert isclose(w_new, 1.2)
assert isclose(loss(w_new), 0.18)
assert loss(w_new) < loss(w)
print("gradient=-2.0; weight=1.2; loss=0.18")
예상 출력
gradient=-2.0; weight=1.2; loss=0.18
기초 해설 수정:
추가 튜토리얼, 논문, 구현 참고 자료
자료 확인: 2026년 11월 10일. 구현, 예제, 그림은 독자 교육 자료입니다. 링크는 보완 학습 자료이며 보증이나 원 모델 재현 증거가 아닙니다. 논문 날짜와 게시 날짜는 구분합니다.
Nano AI · Build a language modelhttps://nano-ai.tech/articles/
추론에서 학습까지 모듈별로 배우는 중국어 자료.
Nano AI · GPT from scratchhttps://nano-ai.tech/articles/llm-from-scratch/
GPT-2 추론 재구성과 무작위 초기화 학습의 차이를 비교합니다.
Andrej Karpathy · Neural Networks: Zero to Herohttps://karpathy.ai/zero-to-hero.html
역전파와 점진적 언어 모델로 기초를 보완합니다.
Sebastian Raschka · LLMs from scratchhttps://github.com/rasbt/LLMs-from-scratch
구조, 학습, 적응을 심화하는 책의 구현 자료.
Andrej Karpathy · nanoGPThttps://github.com/karpathy/nanoGPT
작은 예제 뒤에 실용 학습 코드를 읽으세요. 자원 요구가 다릅니다.
Attention Is All You Needhttps://arxiv.org/abs/1706.03762
원 Transformer와 decoder-only 단순화를 비교합니다. 최초 2017-06-12, v7 2023-08-02.
OpenAI · Language Models are Unsupervised Multitask Learners (2019)https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf
GPT-2 역사적 보고서. 그 능력을 교육 모델의 능력으로 해석하지 마세요.
PyTorch · cross_entropyhttps://docs.pytorch.org/docs/main/generated/torch.nn.functional.cross_entropy.html
API 문서는 main이며 실행 코드는 PyTorch 2.5.1+cpu로 고정·검증했습니다.
PyTorch · AdamWhttps://docs.pytorch.org/docs/main/generated/torch.optim.AdamW.html
API 문서는 main이며 실행 코드는 PyTorch 2.5.1+cpu로 고정·검증했습니다.