콘텐츠로 이동
Search

Microgpt

lastmod 2026-11-16created 2026-02-1814 edits

microgpt는 Andrej Karpathy 가 2026년 2월 공개한, 의존성 없는 순수 Python 200줄 한 파일로 GPT 를 학습하고 추론하는 코드이다. 데이터셋·토크나이저·autograd·GPT-2 와 비슷한 Transformer·Adam 옵티마이저·학습과 추론 루프를 모두 담았고, 나머지는 전부 효율을 위한 것일 뿐이라는 것이 Karpathy 의 설명이다. 그는 이를 micrograd·makemore·nanoGPT 로 이어 온 LLM 단순화 작업의 결과물이자 "아트 프로젝트" 라고 부른다.

About

  • 영어 이름 32,033개를 한 줄에 하나씩 "문서" 로 삼아 학습하고 "kamon", "karai", "vialan" 같은 새 이름을 생성함
  • 모든 연산을 스칼라 하나를 감싼 Value 객체의 autograd 로 계산. 기본 설정(층 1개, 임베딩 16, 헤드 4)에서 파라미터는 4,192개
  • 1,000 스텝 학습에 MacBook 에서 약 1분, 손실은 약 3.3(27개 토큰 무작위 추측)에서 2.37 로 내려감
  • 소스는 GitHub Gist, karpathy.ai/microgpt.html, Google Colab 노트북으로 제공. 바이그램 표부터 Adam 까지 하나씩 쌓아 가는 train0~train5 단계도 별도 Gist 로 공개

microgpt 개요

데이터셋 구성

  • 실제 LLM 은 웹 페이지가 문서지만 여기서는 이름 하나가 문서 하나. 모델은 데이터의 통계적 패턴을 배워 비슷한 새 문서를 만들어 냄
  • ChatGPT 와의 대화도 모델 입장에서는 조금 특이하게 생긴 문서이고, 응답은 프롬프트로 시작한 문서를 통계적으로 이어 쓰는 것이라고 설명

토크나이저

  • tiktoken 같은 실제 토크나이저는 문자 묶음 단위지만, 여기서는 데이터에 나온 문자마다 정수 하나를 줌 (a~z 26개)
  • 문서의 시작과 끝을 알리는 BOS 토큰을 더해 어휘는 27개. "emma" 는 [BOS, e, m, m, a, BOS] 가 됨

자동 미분(Autograd)

  • Value 는 스칼라 값(.data)과 함께 자식 노드와 국소 도함수를 기억함. 지원 연산은 덧셈·곱셈·거듭제곱·log·exp·ReLU
  • backward() 는 손실 노드의 grad 를 1 로 두고 위상 정렬 역순으로 체인 룰을 적용함. 그래프가 갈라지면 기울기를 합해야 하므로 += 로 누적
  • PyTorch 의 .backward() 와 알고리즘은 같고, 텐서 대신 스칼라 단위라 단순하지만 훨씬 느림

파라미터 초기화

  • 가우시안 난수로 초기화한 행렬들을 state_dict 에 담음(임베딩 표, 어텐션 가중치, MLP 가중치, 출력 프로젝션)
  • n_embd = 16, n_head = 4, n_layer = 1, block_size = 16 으로 파라미터 4,192개. GPT-2 는 16억 개, 최근 LLM 은 수천억 개

아키텍처

  • 토큰·위치·파라미터·이전 위치의 키/값 캐시를 받아 다음 토큰의 로짓을 돌려주는 상태 없는 함수. GPT-2 를 따르되 LayerNorm 대신 RMSNorm, 바이어스 없음, GeLU 대신 ReLU
  • 토큰 임베딩과 위치 임베딩을 더한 뒤, 어텐션 블록(토큰끼리 정보를 주고받는 유일한 곳)과 MLP 블록(4배로 넓혔다 줄이는 위치별 계산)을 잔차 연결로 번갈아 쌓음
  • 토큰을 하나씩 처리하므로 학습 중에도 KV 캐시를 명시적으로 만들고, 캐시된 키·값도 역전파 대상이 됨

학습 루프

  • 스텝마다 문서 하나를 골라 BOS 로 감싸고, 위치마다 정답 다음 토큰의 음의 로그 확률(교차 엔트로피)을 구해 평균함. loss.backward() 한 번으로 모든 기울기를 얻음
  • 갱신은 Adam(모멘텀 m 과 제곱 평균 v, 바이어스 보정)과 선형 학습률 감소. 1,000 스텝 뒤 손실은 약 3.3 에서 2.37

추론

  • BOS 에서 시작해 로짓을 확률로 바꿔 토큰 하나를 뽑고, 그 토큰을 다시 입력으로 넣기를 BOS 가 나오거나 최대 길이에 이를 때까지 반복
  • softmax 전에 로짓을 온도로 나눔. 낮으면(코드 기본값 0.5) 보수적, 0 에 가까우면 탐욕적 디코딩, 높으면 다양하지만 덜 일관됨

실행 방법

  • 설치할 것 없이 python train.py. Colab 노트북에서 돌리며 Gemini 에게 코드에 대해 물어볼 수도 있음
  • 데이터셋을 바꾸거나 num_steps·모델 크기를 늘려 보라고 권함

코드 진행 단계

파일

추가 내용

train0.py

바이그램 카운트 테이블 — 신경망 없음, 그래디언트 없음

train1.py

MLP + 수동 그래디언트(수치적 & 해석적) + SGD

train2.py

Autograd(Value 클래스) — 수동 그래디언트 대체

train3.py

위치 임베딩 + 단일 헤드 어텐션 + rmsnorm + 잔차

train4.py

멀티헤드 어텐션 + 레이어 루프 — 전체 GPT 아키텍처

train5.py

Adam 옵티마이저 — 이것이 train.py

  • build_microgpt.py Gist의 Revisions에서 모든 버전과 각 스텝 간 diff 확인 가능

프로덕션 LLM과의 차이

  • 핵심 알고리즘과 전체 배치는 같고, 바뀌는 것은 규모에서 돌아가게 하는 요소들이라고 정리
  • 데이터·토크나이저: 이름 3만 2천 개 대신 중복 제거·품질 필터를 거친 수조 토큰, 글자 대신 약 10만 어휘의 BPE
  • 연산·구조: 스칼라 대신 GPU/TPU 위의 텐서와 FlashAttention 같은 CUDA 커널. 임베딩 1만 이상·100층 이상으로 넓고 깊으며 RoPE·GQA·게이트 활성화·MoE 같은 블록이 더해짐
  • 학습·최적화: 스텝당 수백만 토큰 배치, bfloat16·fp8 정밀도, 수천 GPU 로 몇 달. Chinchilla 같은 스케일링 법칙과 작은 실험으로 설정을 미리 잡음
  • 후학습·서빙: 사전학습 모델은 문서 완성기일 뿐이고 SFT(큐레이션한 대화로 계속 학습)와 RL 로 챗봇이 됨. 서빙에는 배칭, KV 캐시 페이징(vLLM 등), 추측 디코딩, int8/int4 양자화가 쓰임

FAQ

  • 모델이 "이해" 하는가: 기계적으로는 입력 토큰을 다음 토큰의 확률 분포로 바꾸는 큰 수학 함수일 뿐이고, 그 메커니즘은 200줄에 다 들어 있음
  • 왜 되는가: 옵티마이저가 매 스텝 파라미터를 조금씩 옮겨, 이름이 대개 자음으로 시작하고 "qu" 가 붙어 다니는 식의 통계적 규칙성을 확률 분포로 담게 됨
  • 환각: 모델에는 진실 개념이 없고 그럴듯한 시퀀스만 앎. microgpt 가 "karia" 를 지어내는 것과 ChatGPT 가 틀린 사실을 자신 있게 말하는 것은 같은 현상
  • 느린 이유와 개선: 순수 Python 으로 스칼라를 하나씩 처리하기 때문. 더 오래, 더 큰 모델로, 더 큰 데이터로 학습하면 좋아지고, 데이터를 도시·포켓몬 이름 등으로 바꾸면 코드 수정 없이 그것을 배움

Source code

"""
The most atomic way to train and run inference for a GPT in pure, dependency-free Python.
This file is the complete algorithm.
Everything else is just efficiency.

@karpathy
"""

import os       # os.path.exists
import math     # math.log, math.exp
import random   # random.seed, random.choices, random.gauss, random.shuffle
random.seed(42) # Let there be order among chaos

# Let there be a Dataset `docs`: list[str] of documents (e.g. a list of names)
if not os.path.exists('input.txt'):
    import urllib.request
    names_url = 'https://raw.githubusercontent.com/karpathy/makemore/988aa59/names.txt'
    urllib.request.urlretrieve(names_url, 'input.txt')
docs = [line.strip() for line in open('input.txt') if line.strip()]
random.shuffle(docs)
print(f"num docs: {len(docs)}")

# Let there be a Tokenizer to translate strings to sequences of integers ("tokens") and back
uchars = sorted(set(''.join(docs))) # unique characters in the dataset become token ids 0..n-1
BOS = len(uchars) # token id for a special Beginning of Sequence (BOS) token
vocab_size = len(uchars) + 1 # total number of unique tokens, +1 is for BOS
print(f"vocab size: {vocab_size}")

# Let there be Autograd to recursively apply the chain rule through a computation graph
class Value:
    __slots__ = ('data', 'grad', '_children', '_local_grads') # Python optimization for memory usage

    def __init__(self, data, children=(), local_grads=()):
        self.data = data                # scalar value of this node calculated during forward pass
        self.grad = 0                   # derivative of the loss w.r.t. this node, calculated in backward pass
        self._children = children       # children of this node in the computation graph
        self._local_grads = local_grads # local derivative of this node w.r.t. its children

    def __add__(self, other):
        other = other if isinstance(other, Value) else Value(other)
        return Value(self.data + other.data, (self, other), (1, 1))

    def __mul__(self, other):
        other = other if isinstance(other, Value) else Value(other)
        return Value(self.data * other.data, (self, other), (other.data, self.data))

    def __pow__(self, other): return Value(self.data**other, (self,), (other * self.data**(other-1),))
    def log(self): return Value(math.log(self.data), (self,), (1/self.data,))
    def exp(self): return Value(math.exp(self.data), (self,), (math.exp(self.data),))
    def relu(self): return Value(max(0, self.data), (self,), (float(self.data > 0),))
    def __neg__(self): return self * -1
    def __radd__(self, other): return self + other
    def __sub__(self, other): return self + (-other)
    def __rsub__(self, other): return other + (-self)
    def __rmul__(self, other): return self * other
    def __truediv__(self, other): return self * other**-1
    def __rtruediv__(self, other): return other * self**-1

    def backward(self):
        topo = []
        visited = set()
        def build_topo(v):
            if v not in visited:
                visited.add(v)
                for child in v._children:
                    build_topo(child)
                topo.append(v)
        build_topo(self)
        self.grad = 1
        for v in reversed(topo):
            for child, local_grad in zip(v._children, v._local_grads):
                child.grad += local_grad * v.grad

# Initialize the parameters, to store the knowledge of the model
n_layer = 1     # depth of the transformer neural network (number of layers)
n_embd = 16     # width of the network (embedding dimension)
block_size = 16 # maximum context length of the attention window (note: the longest name is 15 characters)
n_head = 4      # number of attention heads
head_dim = n_embd // n_head # derived dimension of each head
matrix = lambda nout, nin, std=0.08: [[Value(random.gauss(0, std)) for _ in range(nin)] for _ in range(nout)]
state_dict = {'wte': matrix(vocab_size, n_embd), 'wpe': matrix(block_size, n_embd), 'lm_head': matrix(vocab_size, n_embd)}
for i in range(n_layer):
    state_dict[f'layer{i}.attn_wq'] = matrix(n_embd, n_embd)
    state_dict[f'layer{i}.attn_wk'] = matrix(n_embd, n_embd)
    state_dict[f'layer{i}.attn_wv'] = matrix(n_embd, n_embd)
    state_dict[f'layer{i}.attn_wo'] = matrix(n_embd, n_embd)
    state_dict[f'layer{i}.mlp_fc1'] = matrix(4 * n_embd, n_embd)
    state_dict[f'layer{i}.mlp_fc2'] = matrix(n_embd, 4 * n_embd)
params = [p for mat in state_dict.values() for row in mat for p in row] # flatten params into a single list[Value]
print(f"num params: {len(params)}")

# Define the model architecture: a function mapping tokens and parameters to logits over what comes next
# Follow GPT-2, blessed among the GPTs, with minor differences: layernorm -> rmsnorm, no biases, GeLU -> ReLU
def linear(x, w):
    return [sum(wi * xi for wi, xi in zip(wo, x)) for wo in w]

def softmax(logits):
    max_val = max(val.data for val in logits)
    exps = [(val - max_val).exp() for val in logits]
    total = sum(exps)
    return [e / total for e in exps]

def rmsnorm(x):
    ms = sum(xi * xi for xi in x) / len(x)
    scale = (ms + 1e-5) ** -0.5
    return [xi * scale for xi in x]

def gpt(token_id, pos_id, keys, values):
    tok_emb = state_dict['wte'][token_id] # token embedding
    pos_emb = state_dict['wpe'][pos_id] # position embedding
    x = [t + p for t, p in zip(tok_emb, pos_emb)] # joint token and position embedding
    x = rmsnorm(x) # note: not redundant due to backward pass via the residual connection

    for li in range(n_layer):
        # 1) Multi-head Attention block
        x_residual = x
        x = rmsnorm(x)
        q = linear(x, state_dict[f'layer{li}.attn_wq'])
        k = linear(x, state_dict[f'layer{li}.attn_wk'])
        v = linear(x, state_dict[f'layer{li}.attn_wv'])
        keys[li].append(k)
        values[li].append(v)
        x_attn = []
        for h in range(n_head):
            hs = h * head_dim
            q_h = q[hs:hs+head_dim]
            k_h = [ki[hs:hs+head_dim] for ki in keys[li]]
            v_h = [vi[hs:hs+head_dim] for vi in values[li]]
            attn_logits = [sum(q_h[j] * k_h[t][j] for j in range(head_dim)) / head_dim**0.5 for t in range(len(k_h))]
            attn_weights = softmax(attn_logits)
            head_out = [sum(attn_weights[t] * v_h[t][j] for t in range(len(v_h))) for j in range(head_dim)]
            x_attn.extend(head_out)
        x = linear(x_attn, state_dict[f'layer{li}.attn_wo'])
        x = [a + b for a, b in zip(x, x_residual)]
        # 2) MLP block
        x_residual = x
        x = rmsnorm(x)
        x = linear(x, state_dict[f'layer{li}.mlp_fc1'])
        x = [xi.relu() for xi in x]
        x = linear(x, state_dict[f'layer{li}.mlp_fc2'])
        x = [a + b for a, b in zip(x, x_residual)]

    logits = linear(x, state_dict['lm_head'])
    return logits

# Let there be Adam, the blessed optimizer and its buffers
learning_rate, beta1, beta2, eps_adam = 0.01, 0.85, 0.99, 1e-8
m = [0.0] * len(params) # first moment buffer
v = [0.0] * len(params) # second moment buffer

# Repeat in sequence
num_steps = 1000 # number of training steps
for step in range(num_steps):

    # Take single document, tokenize it, surround it with BOS special token on both sides
    doc = docs[step % len(docs)]
    tokens = [BOS] + [uchars.index(ch) for ch in doc] + [BOS]
    n = min(block_size, len(tokens) - 1)

    # Forward the token sequence through the model, building up the computation graph all the way to the loss
    keys, values = [[] for _ in range(n_layer)], [[] for _ in range(n_layer)]
    losses = []
    for pos_id in range(n):
        token_id, target_id = tokens[pos_id], tokens[pos_id + 1]
        logits = gpt(token_id, pos_id, keys, values)
        probs = softmax(logits)
        loss_t = -probs[target_id].log()
        losses.append(loss_t)
    loss = (1 / n) * sum(losses) # final average loss over the document sequence. May yours be low.

    # Backward the loss, calculating the gradients with respect to all model parameters
    loss.backward()

    # Adam optimizer update: update the model parameters based on the corresponding gradients
    lr_t = learning_rate * (1 - step / num_steps) # linear learning rate decay
    for i, p in enumerate(params):
        m[i] = beta1 * m[i] + (1 - beta1) * p.grad
        v[i] = beta2 * v[i] + (1 - beta2) * p.grad ** 2
        m_hat = m[i] / (1 - beta1 ** (step + 1))
        v_hat = v[i] / (1 - beta2 ** (step + 1))
        p.data -= lr_t * m_hat / (v_hat ** 0.5 + eps_adam)
        p.grad = 0

    print(f"step {step+1:4d} / {num_steps:4d} | loss {loss.data:.4f}", end='\r')

# Inference: may the model babble back to us
temperature = 0.5 # in (0, 1], control the "creativity" of generated text, low to high
print("\n--- inference (new, hallucinated names) ---")
for sample_idx in range(20):
    keys, values = [[] for _ in range(n_layer)], [[] for _ in range(n_layer)]
    token_id = BOS
    sample = []
    for pos_id in range(block_size):
        logits = gpt(token_id, pos_id, keys, values)
        probs = softmax([l / temperature for l in logits])
        token_id = random.choices(range(vocab_size), weights=[p.data for p in probs])[0]
        if token_id == BOS:
            break
        sample.append(uchars[token_id])
    print(f"sample {sample_idx+1:2d}: {''.join(sample)}")

See also

Favorite site

author Zer0, MCPBot sitemap