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

Hugging Face Transformers: AutoModel과 파이프라인

~14 min · transformers, huggingface, automodel, pipeline

Level 0텐서 탐구자
0 XP0/62 lessons0/13 achievements
0/120 XP to next level120 XP to go0% complete

하나의 패키지로 주요 Transformer 구조를 다뤄

Hugging Face의 transformers 라이브러리는 주요 NLP, 비전, 오디오, 멀티모달 Transformer를 같은 방식으로 다룰 수 있게 해. 추상화는 위에서 아래로 세 층으로 나뉘어:

  1. 파이프라인: pipeline("sentiment-analysis")pipeline("summarization")처럼 한 줄로 작업을 실행하는 API야. 시제품과 일회성 스크립트에 가장 좋아.
  2. Auto* 클래스: AutoTokenizer, AutoModel, AutoModelForSequenceClassification 등이 있어. 체크포인트 이름에서 구조를 알아내 알맞은 클래스를 만들어 줘. 모델과 학습 반복문을 직접 제어하고 싶을 때 적당한 수준이야.
  3. 특정 모델 클래스: BertModel, GPT2LMHeadModel 등이야. Auto 계층이 숨기는 구조별 기능이 꼭 필요할 때만 사용해.

토크나이저와 모델은 한 쌍이야

모든 Transformers 모델에는 짝이 맞는 토크나이저가 있어. 토크나이저는 텍스트를 토큰 ID와 어텐션 마스크로 바꾸고 모델은 이를 입력으로 받아. 둘은 반드시 일치해야 하므로 같은 체크포인트 이름으로 불러와.

작업별 '헤드' 선택

같은 기본 모델 구조도 작업에 따라 여러 헤드 변형을 제공해:

  • AutoModel: 기본 모델로, 은닉 상태를 반환해.
  • AutoModelForSequenceClassification: 분류 헤드를 붙여 로짓을 반환해.
  • AutoModelForTokenClassification: NER처럼 토큰마다 레이블을 예측해.
  • AutoModelForCausalLM: GPT 계열의 인과 언어 모델링에 사용해.
  • AutoModelForSeq2SeqLM: T5 같은 인코더-디코더 모델에 사용해.
  • AutoModelForQuestionAnswering: 추출형 질의응답에서 시작과 끝 위치를 예측해.

작업에 맞는 클래스를 고르면 라이브러리가 알맞은 출력 헤드를 자동으로 붙여 줘.

Code

pipeline: 가장 빠르게 실행해 보기·python
# pip install transformers
from transformers import pipeline

# Sentiment classification
clf = pipeline("sentiment-analysis")
print(clf("PyTorch makes deep learning feel native."))
# [{'label': 'POSITIVE', 'score': 0.9998}]

# Other tasks — same one-line idiom
summarizer = pipeline("summarization")
qa = pipeline("question-answering")
generator = pipeline("text-generation", model="gpt2")
ner = pipeline("ner", aggregation_strategy="simple")
Auto* 계열: 미세 조정에 알맞은 추상화·python
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification

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

# Tokenize — the inputs the model expects
inputs = tok(
    ["This tutorial is great!", "I'm bored."],
    padding=True, truncation=True, return_tensors='pt',
)
print(inputs.keys())   # dict_keys(['input_ids', 'attention_mask'])

# Forward
with torch.inference_mode():
    out = model(**inputs)
print(out.logits)
# tensor([[-1.9234, 2.0456], [1.7234, -1.8123]])

# Convert to labels
labels = ['NEGATIVE', 'POSITIVE']
preds = out.logits.argmax(-1)
for text, p in zip(["good", "bad"], preds):
    print(text, '→', labels[p])
기본 모델 + 직접 만든 헤드 추가·python
import torch
import torch.nn as nn
from transformers import AutoTokenizer, AutoModel

# Sometimes you want the encoder + a custom head (e.g. multi-task, custom loss)
tok = AutoTokenizer.from_pretrained("bert-base-uncased")
encoder = AutoModel.from_pretrained("bert-base-uncased")

class CustomBertClassifier(nn.Module):
    def __init__(self, encoder, num_classes, dropout=0.1):
        super().__init__()
        self.encoder = encoder
        self.dropout = nn.Dropout(dropout)
        hidden = encoder.config.hidden_size
        self.classifier = nn.Linear(hidden, num_classes)

    def forward(self, input_ids, attention_mask=None):
        out = self.encoder(input_ids=input_ids, attention_mask=attention_mask)
        cls_token = out.last_hidden_state[:, 0]      # [CLS] representation
        cls_token = self.dropout(cls_token)
        return self.classifier(cls_token)

model = CustomBertClassifier(encoder, num_classes=5)

External links

Exercise

distilbert-base-uncased와 AutoModelForSequenceClassification을 num_labels=2로 불러와. 'I love this'와 'I hate this'를 토큰화해 순전파를 실행하고 로짓을 출력해. 그다음 같은 모델을 pipeline('sentiment-analysis', model=...) 인터페이스로 불러와 예측이 일치하는지 검증해.

Progress

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

댓글 0

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

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