🤖 AI/ML

Autoregressive

Autoregressive Model

A sequential generation method that uses the previous output as the next input. The core of the GPT family.

📖 Detailed Explanation

An autoregressive model is a sequential generation approach that uses previously generated elements as input when predicting the next element in a sequence. Mathematically, it decomposes the overall probability into a product of conditional probabilities, such as P(x) = P(x1) * P(x2|x1) * P(x3|x1,x2) * ... .

The concept originated from the ARIMA model for time series forecasting, and in deep learning it became the core principle of the GPT series by way of WaveNet (audio generation) in 2016 and the Transformer paper in 2017. Today, most generative AI, including ChatGPT and Claude, uses this approach.

The core principle is causal masking. By masking attention so that future tokens cannot be seen at the current position, the model is forced to generate sequentially from left to right. This allows parallel processing during training while generating one token at a time during inference.

In practice, the greatest advantage of AR models is generation consistency. Because they take all previous context into account, they maintain logical consistency even in long texts. The drawback is inference speed: generating N tokens requires N forward passes, which makes parallelization difficult. Research on improving this through methods such as speculative decoding is active.

💻 Code Example

# 간단한 Autoregressive 텍스트 생성 예제
import torch
from transformers import GPT2LMHeadModel, GPT2Tokenizer

# 모델과 토크나이저 로드
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
model = GPT2LMHeadModel.from_pretrained('gpt2')

def autoregressive_generate(prompt, max_new_tokens=50, temperature=0.8):
    """
    Autoregressive 방식으로 텍스트 생성
    - 한 토큰씩 순차적으로 생성
    - 이전 출력이 다음 입력이 됨
    """
    input_ids = tokenizer.encode(prompt, return_tensors='pt')

    generated = input_ids
    for _ in range(max_new_tokens):
        # 현재까지의 시퀀스로 다음 토큰 확률 예측
        with torch.no_grad():
            outputs = model(generated)
            next_token_logits = outputs.logits[:, -1, :]

        # Temperature 적용 후 샘플링
        probs = torch.softmax(next_token_logits / temperature, dim=-1)
        next_token = torch.multinomial(probs, num_samples=1)

        # 생성된 토큰을 시퀀스에 추가 (Autoregressive!)
        generated = torch.cat([generated, next_token], dim=-1)

        # EOS 토큰이면 종료
        if next_token.item() == tokenizer.eos_token_id:
            break

    return tokenizer.decode(generated[0], skip_special_tokens=True)

# 실행 예제
prompt = "The future of artificial intelligence"
result = autoregressive_generate(prompt, max_new_tokens=30)
print(result)

🗣️ Examples of Practical Conversations

In an LLM performance optimization meeting

"Because of the autoregressive nature, latency grows linearly for long responses. A 500-token response requires 500 forward passes. Using a KV-cache can reduce the computation at each step, but fundamentally we should consider adopting speculative decoding."

When explaining BERT vs GPT

"BERT looks at the entire context bidirectionally, whereas GPT is autoregressive, so it only sees the left context. That's why BERT is strong at classification and NLU, and GPT is strong at generation. Recently, there have also been attempts to combine the strengths of both with encoder-decoder or prefix LM approaches."

In a technical interview

"To explain the role of Teacher Forcing in training and inference of autoregressive models: during training, the ground-truth tokens are given as input, which enables parallel training, but during inference the model must use the tokens it generated itself, so generation becomes sequential. This gap is called exposure bias, and it can be mitigated with scheduled sampling."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Cautions

1
Exposure Bias

There is a mismatch: during training the model sees the ground-truth tokens, but during inference it sees its own output. Early generation errors can accumulate in subsequent tokens and quality can degrade sharply, so use beam search or nucleus sampling appropriately.

2
Inference speed bottleneck

Because one forward pass is required per token, this becomes a bottleneck in real-time services. Combine batch processing, KV-cache optimization, quantization, and so on, and consider streaming output when long responses are needed.

3
Repetitive generation problem

When the temperature is low or greedy decoding is used, the same pattern often repeats. Set the repetition penalty or no_repeat_ngram_size parameter.

🔗 Related Terms

📚 Learn More