Hugging Face 파이프라인
Hugging Face 파이프라인 (Pipelines)
Hugging Face Transformers의 Pipeline은 모델을 추론(inference)에 사용하기 가장 쉽고 좋은 방법이에요. 복잡한 라이브러리 코드 대부분을 추상화해서, Named Entity Recognition, Masked Language Modeling, Sentiment Analysis, Feature Extraction, Question Answering 같은 여러 작업에 쓸 수 있는 간단한 API를 제공해요.
파이프라인에는 두 종류의 추상화가 있는데, 하나는 모든 파이프라인을 감싸는 가장 강력한 pipeline() 객체이고, 다른 하나는 오디오·컴퓨터 비전·NLP·멀티모달 작업별로 만들어진 태스크 특화 파이프라인이에요.
파이프라인 추상화
pipeline 추상화는 다른 모든 파이프라인의 래퍼예요. 다른 파이프라인처럼 인스턴스화하되 추가적인 편의 기능을 제공해요.
단일 항목 호출
>>> pipe = pipeline("text-classification")
>>> pipe("This restaurant is awesome")
[{'label': 'POSITIVE', 'score': 0.9998743534088135}]
허브에서 특정 모델을 쓰고 싶다면, 허브의 모델이 이미 작업을 정의하고 있다면 task를 생략하고 모델만 지정할 수 있어요.
>>> pipe = pipeline(model="FacebookAI/roberta-large-mnli")
>>> pipe("This restaurant is awesome")
[{'label': 'NEUTRAL', 'score': 0.7313136458396912}]
여러 항목 호출과 제너레이터
리스트를 넘기면 여러 항목을 한 번에 처리할 수 있어요.
>>> pipe = pipeline("text-classification")
>>> pipe(["This restaurant is awesome", "This restaurant is awful"])
[{'label': 'POSITIVE', 'score': 0.9998743534088135},
{'label': 'NEGATIVE', 'score': 0.9996669292449951}]
전체 데이터셋을 반복할 때는 dataset을 직접 넘기는 걸 권장해요. 전체 데이터셋을 한 번에 할당할 필요도, 직접 배칭할 필요도 없고 GPU에서 커스텀 루프만큼 빠르게 동작해요.
트랜스포머 pipeline() 함수
( task: str | None = None, model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None,
tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None,
feature_extractor: str | FeatureExtractionMixin | None = None,
image_processor: str | BaseImageProcessor | None = None,
video_processor: str | BaseVideoProcessor | None = None,
processor: str | ProcessorMixin | None = None,
revision: str | None = None, use_fast: bool = True, token: str | bool | None = None,
device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None,
dtype: str | torch.dtype | None = 'auto', trust_remote_code: bool | None = None,
model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any ) → Pipeline
주요 파라미터를 몇 가지 살펴볼게요.
- task (
str) — 반환할 파이프라인을 정의하는 작업. 예를 들어"text-classification"(별칭"sentiment-analysis")은TextClassificationPipeline을,"text-generation"은TextGenerationPipeline을,"token-classification"(별칭"ner")은TokenClassificationPipeline을 반환해요. 그 외에"audio-classification","automatic-speech-recognition","image-classification","object-detection","zero-shot-classification"등 다양한 작업이 있어요. - model (
str또는PreTrainedModel, 선택) — 예측에 사용할 모델. 모델 식별자이거나 사전학습 모델 인스턴스일 수 있어요. 제공하지 않으면 해당task의 기본 모델이 로드돼요. - tokenizer (선택) — 모델 데이터 인코딩용 토크나이저. 주어진 모델/설정의 기본 토크나이저가 사용돼요.
- device (
int, 기본-1) — CPU/GPU 장치 서수.-1은 CPU, 양수는 해당 CUDA 장치 ID에서 실행.torch.device나str도 전달 가능. - dtype (
str또는torch.dtype, 선택) — 모델 정밀도.torch.float16,torch.bfloat16등 또는"auto". - batch_size (
int, 기본 1) —DataLoader사용 시 배치 크기.
더 알아보기
- Hugging Face Quicktour: 사전학습 모델 로드·추론·파인튜닝
- Hugging Face Llama 문서: 텍스트 생성 예제
- Hugging Face 성능 가이드: GPU 추론 최적화