C.W.K.
Stream
Lesson 02 of 12 · published

Autoregressive 생성 — 한 번에 토큰 하나씩

~10 min · generation, decoding

Level 0Token
0 XP0/94 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

학습된 causal LM은 한 번에 토큰 하나씩 생산. 절차:

  1. prompt를 모델에 통과. 마지막 위치 logit 가져옴.
  2. 그 logit에서 토큰 샘플링(greedy, top-k, top-p, 또는 temperature 스케일).
  3. 새 토큰을 시퀀스에 append.
  4. EOS 토큰, stop sequence, 또는 최대 길이까지 1번부터 반복.

이 loop은 본질적으로 직렬. 토큰 5는 토큰 4가 선택되기 전엔 예측 불가. GPU 무한히 있어도 생성 중 시간 축 병렬화 불가능 — batch 축(독립 생성 여럿)이랑 depth 축(단일 forward pass 안)만 가능. 이 사실 하나가 KV-cache, speculative decoding, continuous batching을 다 굴리는 동력 — 모두 본질적 순차성의 영향을 누그러뜨리려는 시도.

Code

Bare-bones generate loop·python
def generate(model, prompt_ids, max_new_tokens=64,
             temperature=0.7, top_p=0.9, eos_id=None):
    ids = prompt_ids
    for _ in range(max_new_tokens):
        logits = model(ids)[:, -1, :]                  # last position
        if temperature > 0:
            logits = logits / temperature
            # nucleus sampling
            sorted_logits, sorted_idx = logits.sort(descending=True)
            probs = F.softmax(sorted_logits, dim=-1)
            cumulative = probs.cumsum(dim=-1)
            mask = cumulative > top_p
            mask[..., 1:] = mask[..., :-1].clone()
            mask[..., 0] = False
            sorted_logits = sorted_logits.masked_fill(mask, float('-inf'))
            next_id = sorted_idx.gather(
                -1,
                torch.multinomial(F.softmax(sorted_logits, dim=-1), 1)
            )
        else:
            next_id = logits.argmax(-1, keepdim=True)
        ids = torch.cat([ids, next_id], dim=1)
        if eos_id is not None and next_id.item() == eos_id:
            break
    return ids

External links

Exercise

위 generate loop을 어떤 최적화도 없이 구현. 작은 모델에서 temperature=0.7로 100토큰 생성. tokens-per-second 측정. 그 다음 model.config.use_cache와 KV caching 켜고 다시 측정. 적당한 시퀀스 길이에서 5-10배 속도 차이 나야.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.