C.W.K.
Stream
Lesson 02 of 05 · published

모델 & 토크나이저 로딩

~22 min · model-loading, quantization, chat-template

Level 0관찰자
0 XP0/43 lessons0/11 achievements
0/120 XP to next level120 XP to go0% complete

베이스 모델 로딩

주 경로 두 가지 — full precision(fp16/bf16)으로 full 파인튜닝 또는 LoRA, 4-bit 양자화로 QLoRA.

토크나이저 셋업

토크나이저는 모델만큼 중요해. 네가 반드시 해야 할 명백하지 않은 두 가지 —

  1. Padding 토큰 설정: 많은 베이스 토크나이저가 padding 토큰 없어. 합리적 기본값 tokenizer.pad_token = tokenizer.eos_token 사용.
  2. apply_chat_template() 사용: 현대 모델은 다 자체 chat template(Jinja2) 가져. 프롬프트 손으로 만들지 말고 항상 apply_chat_template로 포맷 — 특수 토큰, 시스템 메시지, 모델별 포맷팅 올바르게 처리해줘.

Code

Standard fp16 / bf16 loading·python
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

model_name = "meta-llama/Llama-3.1-8B-Instruct"

model = AutoModelForCausalLM.from_pretrained(
    model_name,
    torch_dtype=torch.bfloat16,
    device_map="auto",
    attn_implementation="flash_attention_2",  # if available
)
4-bit QLoRA loading·python
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
import torch

bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16,
    bnb_4bit_use_double_quant=True,
)

model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-3.1-8B-Instruct",
    quantization_config=bnb_config,
    device_map="auto",
)
Tokenizer + chat template·python
tokenizer = AutoTokenizer.from_pretrained(model_name)

# Important: set padding token (many models don't ship one)
if tokenizer.pad_token is None:
    tokenizer.pad_token = tokenizer.eos_token

# Use the model's built-in chat template
messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Hello!"},
]
formatted = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True,
)
print(formatted)
# <|begin_of_text|><|start_header_id|>system<|end_header_id|>
# You are a helpful assistant.<|eot_id|>...

External links

Exercise

Llama 3.1 8B Instruct를 fp16이랑 4-bit로 로드. nvidia-smi로 VRAM 사용량 비교. Chat template 출력하고, 3메시지 대화를 apply_chat_template으로 포맷. 출력에 옳은 특수 토큰(<|begin_of_text|>, <|start_header_id|> 등) 있는지 검증.

Progress

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

댓글 0

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

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