01편에서 vector를 만들고 곱했다. LLM은 마지막 hidden vector를 vocabulary logit으로 바꾼 뒤 다음 token의 조건부확률분포를 만든다. 이 글은 score가 distribution이 되고, 정답 token이 loss가 되고, 다시 sampling 결과가 되는 경로를 따라간다.
Probability의 기본 규칙
sample space 는 가능한 결과의 집합이고 event 는 그 부분집합이다. probability는 다음을 만족한다.
서로 겹치지 않는 event 에 대해
이다.
LLM의 다음 token 후보가 vocabulary 전체라면 각 token probability는 0 이상이고 합은 1이다. 하지만 model이 내놓은 0.9가 현실에서 90% 맞는다는 calibration까지 보장하지는 않는다.
조건부확률
가 일어났다는 조건에서 의 probability는
이다.
language model의 핵심은 다음 token 를 이전 token 에 조건화하는 것이다.
“서울의 수도는” 다음의 token distribution과 “프랑스의 수도는” 다음의 distribution이 다른 이유를 조건부확률로 표현한다.
Product rule와 chain rule of probability
두 event의 joint probability는
이다. 이를 sequence에 반복 적용하면
가 된다. 이 식을 probability chain rule이라고 한다. 미분의 chain rule과 이름은 같지만 다른 규칙이다.
예를 들어 세 token sequence의 probability는
다. decoder-only LLM의 autoregressive factorization이다.
Bayes rule
product rule을 두 방향으로 쓰면
를 얻는다.
- prior — 관측 전 믿음
- likelihood — 일 때 관측 가 나올 가능성
- evidence — 모든 가능한 원인 아래 관측의 probability
- posterior — 관측 뒤 갱신된 믿음
RAG를 단순화해 문서 가 질문 와 답 를 설명한다고 보면, 답을 본 뒤 어떤 문서가 중요했는지 를 생각할 수 있다. 다만 실제 production RAG가 항상 Bayes inference를 구현하는 것은 아니다.
Independence와 conditional independence
가 independent라면
이다. 문장 속 token은 일반적으로 independent하지 않다. bag-of-words model은 계산을 단순하게 만들기 위해 token occurrence에 강한 가정을 둘 수 있지만 Transformer는 문맥 의존성을 표현하려 한다.
conditional independence는 조건 가 주어졌을 때 independent하다는 뜻이다.
graphical model과 latent variable RAG 식을 읽을 때 어떤 conditional independence를 가정했는지 확인한다.
Random variable
random variable 는 random outcome을 숫자에 대응시킨다. token id, response length, retrieval rank, latency가 random variable이 될 수 있다.
Discrete와 continuous
- discrete — token category, tool 선택, 성공·실패
- continuous — latency, logit, embedding coordinate
continuous variable에서 한 점의 probability 는 보통 0이고 probability density를 구간에 적분한다. discrete probability mass와 continuous density의 값을 같은 방식으로 해석하지 않는다.
자주 보는 distribution
Bernoulli
성공 , 실패 인 variable이다.
binary classifier와 tool call 성공 여부에 사용한다.
Categorical
개 category 중 하나를 고른다.
다음 token 선택과 tool 선택은 categorical distribution으로 표현할 수 있다.
Gaussian
weight initialization, noise model, 통계적 추정에 자주 등장한다. 실제 activation이 완벽한 Gaussian이라는 보장은 없다. Gaussian 가정은 분석과 초기화를 가능하게 하는 model이다.
Expectation
discrete random variable의 expectation은 가능한 값의 probability-weighted average다.
함수 의 expectation은
다. machine learning loss는 데이터 distribution에 대한 expected loss로 쓴다.
현실의 를 전부 알 수 없으므로 dataset sample 평균으로 근사한다.
mini-batch gradient도 full-data expectation의 sample estimate다.
Linearity of expectation
independence가 없어도
가 성립한다. token별 loss를 합하거나 여러 평가 component를 가중합할 때 기본이 된다.
Variance와 covariance
variance는 mean 주변의 spread다.
standard deviation은 다.
batch마다 gradient가 달라지는 정도를 gradient variance로 분석한다. batch size가 커지면 estimate noise가 줄어드는 경향이 있지만 sample correlation과 data distribution에 따라 단순히 로만 줄지 않을 수 있다.
두 variable이 함께 움직이는 정도는 covariance다.
correlation은 scale을 제거한다.
correlation이 0이어도 nonlinear dependence가 있을 수 있고, correlation이 높아도 causation을 뜻하지 않는다.
Likelihood와 probability를 구분한다
를 의 함수로 보면 probability distribution이다. 관측 를 고정하고 의 함수로 보면 likelihood다.
같은 식이지만 무엇을 움직이는지 다르다. likelihood를 parameter에 대한 probability distribution이라고 부르려면 Bayesian prior와 normalization이 추가로 필요하다.
Maximum likelihood estimation
dataset 를 independent sample로 보면 likelihood는 곱이다.
log는 단조증가하므로 같은 optimum을 유지하면서 곱을 합으로 바꾼다.
optimization library가 loss를 minimize하므로 음수를 붙인다.
NLL은 negative log-likelihood다.
Autoregressive language modeling loss
sequence chain rule을 NLL에 넣는다.
padding token과 prompt 일부를 학습에서 제외할 때 mask 를 둔다.
분모를 token 수로 할지 sequence 수로 할지에 따라 긴 sample의 weight가 달라진다. “mean loss”라는 이름만 보지 말고 reduction 축을 확인해야 한다.
Logit
model의 마지막 linear layer 출력 는 logit이다.
logit은 normalized probability가 아니다. 두 class의 logit 차이는 softmax 뒤 odds ratio와 연결된다.
logit에 같은 상수를 더해도 probability는 바뀌지 않는다. 절대 logit보다 차이가 중요하다.
Sigmoid
binary logit 를 probability로 바꾼다.
두 독립 label을 각각 예측하는 multi-label 문제에는 class별 sigmoid를 쓸 수 있다. vocabulary 중 정확히 하나를 고르는 다음 token 문제에는 모든 class가 경쟁하는 softmax가 맞다.
Softmax
모든 는 양수이고 합이 1이다.
을 안정적으로 계산한다. 최대값 2를 뺀다.
합은 약 1.5032이므로
가장 큰 logit의 token이 약 66.5%를 받는다.
Stable softmax
을 직접 계산하면 overflow가 날 수 있지만 가장 큰 값을 빼면 최대 exponent가 이다.
Log-sum-exp
안정적인 형태는
이다. log-softmax는
로 계산한다. softmax 뒤 log를 따로 계산하는 것보다 fused log_softmax와 cross-entropy 구현이 안정적이다.
Information content
probability가 낮은 event는 발생했을 때 더 많은 정보를 준다고 정의한다.
이면 정보량은 0이다. 밑이 2면 단위는 bit, 자연로그면 nat다.
- — 1 bit
- — 3 bits
language model이 정답 token에 낮은 probability를 주면 surprisal 가 크고 loss도 크다.
Entropy
distribution 자체의 평균 surprisal이다.
개 결과가 균등하면 entropy가 최대다.
한 결과에 probability 1이 몰리면 entropy는 0이다. entropy가 높으면 distribution이 퍼져 있고, 낮으면 집중돼 있다. “entropy가 낮다 = 답이 사실이다”는 아니다. model은 틀린 답에 자신 있게 집중할 수 있다.
Cross-entropy
true distribution 의 sample을 model distribution 로 encoding할 때 평균 surprisal이다.
one-hot target이 class 에 1이라면
가 되어 categorical NLL과 같다.
정답 probability가 0.8이면 loss는
정답 probability가 0.01이면
이다. 틀린 데다 자신 있는 prediction에 큰 penalty를 준다.
Cross-entropy gradient
softmax 와 one-hot target 를 붙이면 logit 에 대한 gradient가 간단해진다.
정답 class 에는
이므로 gradient descent가 를 올린다. 다른 class에는 이므로 logit을 내린다.
앞의 에서 정답이 첫 번째 token이면
이다. 틀리게 높았던 두 번째 logit이 가장 크게 내려간다.
KL divergence
에서 나온 sample을 로 설명할 때 추가로 드는 정보량이다.
cross-entropy와 entropy 관계는
다. dataset의 가 고정이면 는 parameter와 무관하므로 cross-entropy 최소화는 최소화와 같은 optimum을 가진다.
KL은 distance가 아니다.
- 일반적으로
- triangle inequality를 만족하지 않는다.
- 인데 이면 무한대가 된다.
knowledge distillation, RLHF의 reference penalty, variational inference에서 어느 방향의 KL인지 반드시 확인한다.
Forward KL과 reverse KL의 직관
는 가 mass를 둔 곳을 가 놓치면 크게 벌한다. 여러 mode를 덮으려는 경향을 설명할 때 mode-covering이라고 부른다.
는 가 의 낮은-density 영역에 mass를 두는 것을 벌한다. 한 mode에 집중하는 mode-seeking 경향을 설명할 때 쓰인다.
이 표현은 직관이며 실제 neural optimization 결과를 단독으로 보장하는 정리는 아니다. distribution family와 objective 조건을 같이 봐야 한다.
Mutual information
두 random variable이 서로에 대해 주는 정보량이다.
independent하면 mutual information은 0이다. representation learning에서는 input과 representation, query와 relevant document 사이의 shared information을 논의할 때 등장한다. 고차원 continuous variable의 mutual information을 정확히 추정하는 일은 어렵다. 논문이 bound나 estimator를 쓰는지 확인한다.
Cross-entropy, NLL, KL의 관계
세 용어를 한 줄로 정리한다.
one-hot target의 categorical cross-entropy
= 정답 class의 negative log-likelihood
= target entropy가 고정일 때 target || model KL을 줄이는 objective
항상 같은 개념이라는 뜻은 아니다. target이 soft label인지, reduction이 무엇인지, KL 방향이 무엇인지에 따라 식이 달라진다.
Perplexity
token 평균 NLL의 exponent다.
평균 NLL이 이면 perplexity는 10이다. 직관적으로 매 token마다 균등한 10개 후보 사이에서 망설이는 정도의 surprisal과 같지만, 실제 distribution이 균등하다는 뜻은 아니다.
perplexity 비교에는 조건이 붙는다.
- tokenizer가 다르면 token 단위가 달라진다.
- evaluation corpus와 preprocessing이 같아야 한다.
- context window와 stride가 다르면 condition이 달라진다.
- 낮은 perplexity가 instruction following, factuality, 안전성 향상을 자동 보장하지 않는다.
Temperature
logit을 temperature 로 나눈 뒤 softmax한다.
- — logit 차이를 확대해 distribution을 뾰족하게 만든다.
- — logit 차이를 줄여 distribution을 평평하게 만든다.
- — unique maximum이 있으면 argmax에 가까워진다.
일 때 odds는 다.
- — 약 2.718 대 1
- — 대 1
- — 대 1
temperature는 model weight를 바꾸지 않고 decoding distribution만 변형한다.
Greedy, sampling, top-k, top-p
Greedy decoding
매 단계 가장 높은 token을 고른다. deterministic이지만 sequence 전체 probability를 최대화한다는 보장은 없다. 현재 최선 선택이 이후 선택을 제한할 수 있다.
Categorical sampling
같은 prompt에서도 다른 token을 뽑을 수 있다. random seed, hardware, sampling implementation까지 같아야 재현성이 높아진다.
Top-k
probability가 큰 개 token만 남기고 다시 normalize한다.
항상 후보 수가 다. distribution이 이미 매우 집중돼 있어도 같은 수를 남긴다.
Top-p 또는 nucleus sampling
정렬된 token probability의 누적합이 이상이 되는 최소 집합을 남긴다.
집중된 step에서는 후보가 적고, 평평한 step에서는 많아진다. top-와 top-를 함께 쓰면 어느 filter를 먼저 적용하는지 implementation을 확인한다.
Beam search
beam search는 매 step 상위 개의 partial sequence를 유지하는 heuristic search다. sequence score는 보통 log probability 합이다.
짧은 sequence는 합할 음의 log probability 항이 적어 유리할 수 있어 length penalty를 사용한다. beam width를 키운다고 인간 선호나 factuality가 단조롭게 좋아지는 것은 아니다.
Calibration
confidence가 0.8인 prediction 집합이 실제로 약 80% 맞는다면 calibrated됐다고 말한다. accuracy가 같아도 calibration은 다를 수 있다.
binary calibration의 Brier score는
다. Expected Calibration Error는 confidence bin별 accuracy 차이를 가중 평균하지만 bin 선택에 민감하다.
LLM token probability calibration과 답변 단위의 “이 답이 맞을 probability”는 같은 문제가 아니다. 답변은 여러 token과 reasoning step의 결과이며 self-reported confidence도 별도 검증이 필요하다.
Label smoothing
one-hot target의 일부 mass를 다른 class에 나눈다. 단순한 형태는
다. model이 정답 class에 probability 1을 몰도록 강제하지 않고 regularization 효과를 낸다. 정확한 분배 방식은 구현에 따라 K 또는 K-1을 쓸 수 있으므로 확인한다.
Contrastive learning으로 이어지는 softmax
query 와 positive document , negative 의 similarity 가 있을 때 InfoNCE 형태 loss는
다. vocabulary token 대신 candidate document가 class가 된 cross-entropy로 읽을 수 있다. temperature가 similarity 차이의 sharpness를 조절한다. negative sampling 방식이 바뀌면 denominator와 학습 난이도도 바뀐다.
RAG의 latent document probability
초기 RAG 논문은 retrieved document 를 latent variable로 두고 답 probability를 문서별로 합한다. sequence 단위 단순형은
다.
- — retriever distribution
- — generator distribution
- top- — 전체 corpus 합을 계산하지 않는 근사
production에서 문서를 prompt에 붙이고 API를 한 번 호출하는 방식은 이 식을 end-to-end로 학습한 original RAG와 다를 수 있다. “RAG”라는 이름만 보고 같은 objective를 쓴다고 가정하지 않는다.
확률에서 자주 하는 실수
0.8 similarity를 80% probability라고 부른다
score calibration이 없으면 불가능하다. cosine 0.8은 각도 기반 similarity다.
평균만 보고 variance를 버린다
평균 latency가 같아도 p95와 tail failure는 다를 수 있다. evaluation score도 seed와 sample에 따른 uncertainty를 같이 봐야 한다.
Dataset frequency를 진실의 probability로 본다
empirical frequency는 수집 과정과 sampling bias를 포함한다. model이 학습한 는 현실의 truth distribution과 동일하지 않다.
Conditional probability 방향을 뒤집는다
와 는 다르다. Bayes rule의 prior와 denominator가 필요하다.
KL을 대칭 distance로 본다
argument 순서가 objective의 행동을 바꾼다. 논문 식의 방향을 그대로 읽는다.
손계산
세 token의 logit이
이고 정답이 두 번째라고 하자.
최대값 2를 빼면 다.
합은 1.5032이므로
cross-entropy는
logit gradient는
이다. gradient descent는 첫 번째 logit을 내리고 정답인 두 번째를 올린다.
완료 체크
- joint, conditional, marginal probability를 구분한다.
- probability chain rule로 sequence likelihood를 쓴다.
- expectation과 sample mean의 관계를 설명한다.
- likelihood, log-likelihood, NLL의 관계를 설명한다.
- stable softmax와 log-sum-exp를 계산한다.
- one-hot cross-entropy gradient가 임을 설명한다.
- entropy, cross-entropy, KL divergence를 구분한다.
- perplexity 비교 조건을 말한다.
- temperature, top-, top-가 distribution을 다르게 바꾸는 이유를 설명한다.
- retrieval similarity와 relevance probability를 구분한다.
다음 글은 loss의 변화가 각 weight의 변화로 전달되는 경로를 다룬다. LLM 수학 03 — 미분과 최적화.
Reference
- Claude E. Shannon. A Mathematical Theory of Communication, 1948.
- Ian Goodfellow, Yoshua Bengio, Aaron Courville. Deep Learning, Probability and Information Theory, 2016.
- Patrick Lewis 외. Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks, 2020.
- Aaron van den Oord, Yazhe Li, Oriol Vinyals. Representation Learning with Contrastive Predictive Coding, 2018.
댓글