Logits: Analysis
Summary
Logits are unprocessed numerical values that the model outputs before being transformed into probabilities; they are used for selecting the next token during generation. For more details: Logits.
Definition
Logits are a vector of real numbers that the neural network returns on the last layer before the activation function. In the context of language models, logits correspond to estimates for each token in the vocabulary.
For example, if the vocabulary contains 50,000 tokens, the model will output a vector of 50,000 logits. The higher the value of the logit, the higher the probability of the corresponding token.
Conversion to Probabilities
Logits themselves are not probabilities—they can be any numbers, including negative. To obtain probabilities, the softmax function is applied:
import numpy as np
def softmax(logits):
exp_logits = np.exp(logits - np.max(logits)) # for numerical stability
return exp_logits / np.sum(exp_logits)
logits = np.array([2.0, 1.0, 0.1])
probs = softmax(logits)
print(probs) # [0.659, 0.242, 0.099]
Role in Text Generation
During text generation, the model predicts the next token. Logits go through several stages:
- Temperature — divides logits by the temperature, changing the probability distribution (see Temperature).
- Top-k / Top-p — filters the set of tokens (see Top-p and Top-k sampling).
- Softmax — converts to probabilities.
- Token selection — greedy selection or sampling.
Example with a Real Model
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
tokenizer = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2")
inputs = tokenizer("The capital of France is", return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits[0, -1, :] # logits for the last token
probs = torch.softmax(logits, dim=-1)
top_token_id = torch.argmax(probs).item()
print(tokenizer.decode(top_token_id)) # " Paris"
Logits and Loss Functions
In classification tasks, logits are often used directly in the loss function, for example, in cross-entropy. This helps avoid numerical issues related to the logarithm of probability.
Relation to Other Concepts
- Softmax — function for converting logits to probabilities.
- Logprobs — logarithmic probabilities used for confidence estimation.
- Greedy Decoding — selection of the token with the highest probability.
Understanding logits is essential for tuning generation parameters and analyzing model behavior.