본문 바로가기
C.W.K.
Stream
Lesson 03 of 07 · published

샘플링에서 미신 걷어내기 — temperature, top-p, repetition_penalty

~16 min · sampling, temperature, top-p

Level 0호기심
0 XP0/51 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

말 많은 조절값 셋

temperature, top_p, repetition_penalty는 거의 모든 채팅 API에 붙어 있어. 의견과 민담은 넘치는데 실제로 로짓에 무엇을 하는지는 흐릿하게 알려진 경우가 많아. 각각이 언제 돕고, 언제 해치고, 언제 그저 미신인지 직접 보자.

temperature — 확률 분포를 뾰족하거나 평평하게

샘플링 직전 모델은 어휘의 모든 토큰에 로짓이라는 실수 점수를 매겨. Softmax가 그 점수를 확률 분포로 바꾸고, temperature는 그 전에 로짓을 나눠. 값이 낮으면 가장 유력한 토큰이 더 강해지고, 높으면 분포가 평평해져 드문 토큰도 선택될 기회를 얻어.

  • temperature=0은 탐욕 디코딩이야. 언제나 argmax를 골라서 재현 가능하고, 때로 반복적이며, 거의 놀라게 하지 않아.
  • temperature=0.7–1.0은 자연스럽게 느껴지는 생성의 흔한 구간이야. 많은 채팅 API가 이 근처를 기본값으로 둬.
  • temperature ≥ 1.5부터 창의적으로 보일 수 있지만 곧 앞뒤가 무너지기 쉬워. 발상에는 쓸 만해도 지시를 정확히 따르는 일에는 나빠.

top_p — 긴 꼬리를 잘라내

top_p는 핵 샘플링이라고도 불러. 누적 확률이 최소 p가 되는 가장 작은 토큰 묶음만 남기고 그 안에서 골라. top_p=0.95라면 전체 확률의 95%를 덮는 상위 토큰만 보고 긴 꼬리는 버린다는 뜻이야. temperature가 분포의 모양을 바꾼다면 top_p는 끝을 잘라.

채팅 API에서 흔한 temperature=0.7, top_p=0.95 조합은 분포를 적당히 뾰족하게 만들고, 꼬리의 터무니없는 후보를 한 번 더 거르는 선택이야.

repetition_penalty — 최근 토큰의 메아리를 줄여

모델이 어떤 단어에 꽂혀 모든 줄에서 되풀이한다면 repetition_penalty가 최근에 낸 토큰의 로짓을 작은 계수로 나눠. 보통 1.05–1.15를 써. 반복에 빠지는 작은 지시 학습 모델에는 도움이 되지만 반복 자체가 표현인 창작 글에는 쓰지 마.

직접 보면 민담이 끝나

같은 프롬프트를 세 가지 설정으로 돌려봐. temperature=0은 늘 같은 답을 주고 조금 심심할 거야. 높은 temperature는 운에 따라 창의적이거나 완전히 풀려버려. 여기에 top_p를 더하면 높은 temperature의 최악을 줄이면서도 탐욕 디코딩처럼 평평하게 만들지는 않아. 눈으로 보면 과장된 설명은 금방 사라져.

Code

세 가지 샘플링 방식 — 같은 프롬프트의 차이 보기·python
from mlx_lm import load, generate
from mlx_lm.sample_utils import make_sampler

model, tok = load("mlx-community/Llama-3.2-1B-Instruct-4bit")
prompt = "Write one short imaginative sentence about clouds:"

print("--- temp=0 (greedy, reproducible) ---")
print(generate(model, tok, prompt=prompt, max_tokens=25,
               sampler=make_sampler(temp=0.0), verbose=False))

print()
print("--- temp=0.7, top_p=0.95 (the default zone) ---")
print(generate(model, tok, prompt=prompt, max_tokens=25,
               sampler=make_sampler(temp=0.7, top_p=0.95), verbose=False))

print()
print("--- temp=1.5, top_p=0.95 (creative-adjacent) ---")
print(generate(model, tok, prompt=prompt, max_tokens=25,
               sampler=make_sampler(temp=1.5, top_p=0.95), verbose=False))

# Verified outputs (2026-05-03, Llama-3.2-1B-Instruct-4bit):
#   temp=0    : "As the sun set over the rolling hills, a lone cloud drifted lazily..."  (cliche, but stable)
#   temp=0.7  : something natural-sounding, varies per run
#   temp=1.5  : "They danced on the sun-kissed rooftops in intricate waltz patterns."   (creative)
재현성 — 시드를 먼저 정하고 그다음 샘플링해·python
import mlx.core as mx
from mlx_lm import load, generate
from mlx_lm.sample_utils import make_sampler

model, tok = load("mlx-community/Llama-3.2-1B-Instruct-4bit")
sampler = make_sampler(temp=0.7, top_p=0.95)

mx.random.seed(123)
out1 = generate(model, tok, prompt="One sentence about Mars:", max_tokens=20, sampler=sampler, verbose=False)

mx.random.seed(123)
out2 = generate(model, tok, prompt="One sentence about Mars:", max_tokens=20, sampler=sampler, verbose=False)

assert out1 == out2, "Seeded sampling should be reproducible"
print("Seeded twice, identical output:")
print(out1)

External links

Exercise

세 가지 샘플링 코드 블록을 실행해. 이어서 temp=2.5, top_p=1.0으로 네 번째 호출을 추가해. temperature는 아주 높고 top-p 절단은 없는 설정이야. 출력이 창의적인지 그저 앞뒤가 없는지 봐. 다음에는 temp=2.5, top_p=0.9로 다섯 번째 호출을 추가해 비교해. top_p는 temperature와 따로 조정할 수 있는 안전장치이고, temperature가 매우 높을수록 읽을 만한 답을 지키려면 더 좁은 top_p가 필요하다는 감각을 잡아.

Progress

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

댓글 0

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

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