🤖 AI/ML

Inference

Inference

The process of making predictions with a trained model. Contrasts with training.

📖 Detailed Explanation

Inference is the process of using a trained model to make predictions on new data. If training is the process of updating a model's weights, inference is the process of processing inputs with fixed weights to generate outputs.

In the early days of deep learning, training was the main challenge, but with the emergence of large-scale models such as GPT-4 and LLaMA, inference cost and speed became key issues. Most of the operating costs of OpenAI's GPT-4 service are spent on inference.

Inference optimization techniques include quantization, KV Cache, batch processing, and model distillation. Tools such as NVIDIA TensorRT, vLLM, and llama.cpp support inference acceleration.

In practice, LLM inference costs are around $0.01~0.03 per input token and $0.03~0.06 per output token. Increasing throughput with batch processing and reducing TTFT (Time to First Token) with KV Cache are the key optimization strategies.

💻 Code Example

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
import time

# 모델과 토크나이저 로드
model_name = "meta-llama/Llama-2-7b-chat-hf"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
    model_name,
    torch_dtype=torch.float16,  # FP16으로 메모리 절약
    device_map="auto"
)

# 추론 함수 (배치 처리 지원)
def batch_inference(prompts, max_new_tokens=100):
    # 토큰화 (패딩 포함)
    inputs = tokenizer(
        prompts,
        return_tensors="pt",
        padding=True,
        truncation=True
    ).to(model.device)

    start_time = time.time()

    # 추론 실행 (gradient 계산 비활성화로 메모리 절약)
    with torch.no_grad():
        outputs = model.generate(
            **inputs,
            max_new_tokens=max_new_tokens,
            do_sample=True,
            temperature=0.7,
            use_cache=True  # KV Cache 활성화
        )

    inference_time = time.time() - start_time

    # 결과 디코딩
    responses = tokenizer.batch_decode(outputs, skip_special_tokens=True)

    print(f"배치 크기: {len(prompts)}")
    print(f"총 추론 시간: {inference_time:.2f}초")
    print(f"프롬프트당 평균: {inference_time/len(prompts):.2f}초")

    return responses

# 테스트
prompts = [
    "Python의 장점을 설명해줘:",
    "머신러닝과 딥러닝의 차이는:",
    "좋은 코드를 작성하는 방법은:"
]
results = batch_inference(prompts)

🗣️ Say It Like This in Practice

💬 In a Meeting
"Our current inference latency averages 2 seconds, but applying KV Cache and batch processing can bring it down to 0.5 seconds. Switching to vLLM should also improve throughput by about 3x."
💬 In an Interview
"Training updates weights through backpropagation, while Inference only makes predictions with fixed weights. During inference, we turn off gradient computation with torch.no_grad() and enable the KV Cache with use_cache=True to increase speed."
💬 In a Technical Discussion
"Applying INT8 quantization cuts memory by 50% and doubles speed, but there is a 1~2% loss in accuracy. Depending on the characteristics of the service, you need to choose between FP16 and INT4."

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

⚠️ Common Mistakes & Cautions

❌
Running inference without torch.no_grad()

Gradient computation is enabled, so it consumes more than twice the memory and also runs slower. Always disable it during inference.

❌
Calling the API with single-item processing

Running inference separately for each request lowers GPU utilization. If possible, group requests into batches for processing.

✅
Make active use of KV Cache and quantization

Applying just use_cache=True and FP16/INT8 quantization can improve inference speed by 2~3x.

🔗 Related Terms

📚 Learn More