본문 바로가기
C.W.K.
Stream
Lesson 03 of 06 · published

태스크, Auto 클래스, from_pretrained()

~30 min · transformers, auto

Level 0스카우트
0 XP0/50 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Auto* 클래스는 설정을 읽는 배차 담당이야

pipeline() 아래에는 AutoTokenizer, AutoModelForCausalLM, AutoModelForSequenceClassification, AutoProcessor처럼 작업별 Auto 클래스가 있어. 직접 구현 클래스의 이름을 외우는 대신 작업에 맞는 Auto 클래스를 고르면 돼.

Auto 클래스는 저장소의 config.json에서 model_type을 읽고 등록된 구체 클래스로 연결해. 예를 들어 llama라면 Llama 계열 tokenizer와 causal LM 클래스를 선택하지. 그래서 보통은 클래스를 직접 만들지 않고 AutoModelForXxx.from_pretrained(repo_id)를 호출해.

로더에서 자주 만지는 네 가지

  • torch_dtype='auto'는 설정에 기록된 자료형을 따르고, float16이나 bfloat16은 float32보다 메모리를 대략 절반만 써.
  • device_map='auto'는 보이는 GPU·MPS·CPU에 모델을 나눠 배치해. 위치를 직접 정하려면 dict를 넘겨.
  • load_in_8bitload_in_4bit는 bitsandbytes로 불러올 때 양자화해 메모리를 크게 줄여.
  • revision에는 재현성을 보장할 커밋 SHA를 넣어.

모델 카드가 library_name: transformers를 선언하고 아키텍처가 레지스트리에 등록돼 있으면 같은 로더 계약으로 불러올 수 있어.

Code

AutoTokenizer + AutoModelForCausalLM·python
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch

repo = "meta-llama/Llama-3.2-1B-Instruct"  # 1B 급 instruct 모델 아무거나

tok = AutoTokenizer.from_pretrained(repo)
model = AutoModelForCausalLM.from_pretrained(
    repo,
    torch_dtype=torch.bfloat16,
    device_map="auto",
)

prompt = tok.apply_chat_template(
    [{"role": "user", "content": "What is the Hugging Face Hub?"}],
    tokenize=False,
    add_generation_prompt=True,
)

inputs = tok(prompt, return_tensors="pt").to(model.device)
out = model.generate(**inputs, max_new_tokens=120, do_sample=False)
print(tok.decode(out[0], skip_special_tokens=True))
다른 head, 같은 레시피 (classification)·python
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch

repo = "distilbert-base-uncased-finetuned-sst-2-english"
tok = AutoTokenizer.from_pretrained(repo)
model = AutoModelForSequenceClassification.from_pretrained(repo)

inputs = tok("The movie was ok.", return_tensors="pt")
with torch.no_grad():
    logits = model(**inputs).logits
print("predicted label id:", logits.argmax().item())

External links

Exercise

Hub 의 텍스트 classifier 아무거나. AutoModelForSequenceClassification.from_pretrained(...) 로 로드. 셋팅 셋 비교: float32 디폴트, bfloat16, 8-bit (bitsandbytes). 각각 같은 100 입력 시간 측정 + nvidia-smi 또는 torch.cuda.max_memory_allocated() 로 peak GPU 메모리.

Progress

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

댓글 0

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

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