pipeline() 은 한 콜 뒤에 세 가지를 wire 하는 factory 함수: 토크나이저, 모델, 태스크별 pre/post-processing. 태스크 이름 ("text-generation", "sentiment-analysis", "automatic-speech-recognition" 등) 과 모델 id 를 넘기면, raw input (텍스트, 오디오 바이트, 이미지 PIL) 을 받아 task-shaped output 을 돌려주는 callable 을 받아.
태스크 이름이 곧 계약. pipeline("text-generation") 은 항상 [{"generated_text": str}] 돌려줘. pipeline("text-classification") 은 항상 [{"label": str, "score": float}]. 같은 pipeline 콜이 수천 모델에서 동작하는 이유 — 모델 카드의 pipeline_tag 필드가 routing key 야.
pipeline() 의 한계
pipeline() 이 맞는 도구: 프로토타이핑, 단일-입력 인퍼런스, 데모, Colab 노트북. 잘못된 도구: throughput 단위 batch 인퍼런스, 커스텀 디코딩 (beam variant, JSON 모드, 구조화 출력), raw logit 필요한 거. 컨트롤이 필요한 순간, AutoTokenizer + AutoModelForXxx 로 내려가 — 다음 레슨 주제.
pipeline() 에서 얻을 수 있는 거 하나: 디바이스 placement + batching. GPU 0 면 device=0, Apple Silicon 면 device="mps", multi-GPU sharding 면 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])
고객 리뷰 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.