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

pipeline() 추상화

~28 min · transformers, pipeline

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

pipeline()이 묶어 주는 세 조각

pipeline()은 tokenizer, 모델, 작업별 전처리와 후처리를 한 호출 가능한 객체로 묶어 주는 factory야. text-generation, sentiment-analysis, automatic-speech-recognition 같은 작업 이름과 모델 ID를 주면 텍스트·오디오·이미지를 받아 그 작업에 맞는 결과를 돌려줘.

작업 이름은 출력 계약이기도 해. 텍스트 생성은 [{"generated_text": str}], 텍스트 분류는 [{"label": str, "score": float}] 형태를 유지해. 수천 개 모델에 같은 호출이 통하는 까닭은 모델 카드의 pipeline_tag가 작업을 연결해 주기 때문이야.

빠른 시작에는 좋지만 모든 제어를 주지는 않아

프로토타입, 단일 입력 추론, 데모와 노트북에는 pipeline()이 잘 맞아. 반면 처리량 중심의 배치 추론, 세밀한 디코딩, 구조화 출력, 원시 logit이 필요하면 AutoTokenizerAutoModelForXxx로 내려가야 해.

장치와 기본 배치는 여기서도 지정할 수 있어. 첫 GPU는 device=0, Apple Silicon은 device='mps', 여러 GPU에 모델을 나누려면 Accelerate와 device_map='auto'를 사용해.

Code

흔한 태스크 다섯 개, 같은 모양·python
from transformers import pipeline

# Text generation (causal LM)
gen = pipeline("text-generation", model="gpt2", device_map="auto")
print(gen("Hello", max_new_tokens=20)[0]["generated_text"])

# Text classification
cls = pipeline("sentiment-analysis")
print(cls("I love this library."))  # [{'label': 'POSITIVE', 'score': 0.99...}]

# Zero-shot classification
zs = pipeline("zero-shot-classification")
print(zs("This is a plot synopsis", candidate_labels=["sci-fi", "romance", "horror"]))

# Speech-to-text
asr = pipeline("automatic-speech-recognition", model="openai/whisper-tiny")
# print(asr("audio.wav"))

# Image-to-text
i2t = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base")
# print(i2t("photo.jpg"))
디바이스 컨트롤된 batch 인퍼런스·python
from transformers import pipeline

cls = pipeline("text-classification", model="distilbert-base-uncased-finetuned-sst-2-english", device=0)

# 리스트 넘기면 — pipeline 이 자동 batch
texts = [
    "I love this library.",
    "This is okay.",
    "What a nightmare.",
] * 100  # 300 inputs

results = cls(texts, batch_size=32)
print(len(results), results[0])

External links

Exercise

고객 리뷰 CSV 받아서 sentiment label + confidence score 두 컬럼 추가해 출력하는 작은 도구 만들어. pipeline('text-classification', batch_size=32, device=0 또는 'mps') 써. 1000 리뷰에 대해 시간 측정. device='cpu' 로 다시 돌려서 차이 확인.

Progress

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

댓글 0

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

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