Pipeline API — High-Level Inference
Interfaz unificada para tareas comunes
Pipeline es la forma más simple de usar modelos preentrenados: una función que toma texto y retorna predicciones. Bajo el capó, pipeline descarga automáticamente el tokenizer y modelo del hub de Hugging Face, los cachea localmente, y expone una interfaz unificada. No necesitas saber sobre tokenización, forward pass, post-processing: todo está encapsulado.
Ejemplos: pipeline('sentiment-analysis') clasifica sentimiento, retorna [{'label': 'POSITIVE', 'score': 0.999}]. pipeline('text-generation') genera continuación de texto. pipeline('question-answering', question='...', context='...') responde preguntas sobre contexto. pipeline('ner') etiqueta entidades nombradas. Para cada tarea, hay un modelo default que se descarga automáticamente.
El trade-off: pipeline es simple pero inflexible. No puedes personalizar post-processing, debuggear intermediate activations, o hacer cosas avanzadas. Para control total, usa AutoTokenizer + AutoModel directamente. Pero para 90% de los casos, pipeline es suficiente y recomendado para inferencia rápida.
# Pipeline examples for common NLP tasks
from transformers import pipeline
# Sentiment analysis
classifier = pipeline('sentiment-analysis', model='distilbert-base-uncased-finetuned-sst-2-english')
result = classifier('I love this movie!') # [{'label': 'POSITIVE', 'score': 0.9998}]
# Text generation
generator = pipeline('text-generation', model='gpt2')
output = generator('Once upon a time', max_length=50)
# output: [{'generated_text': 'Once upon a time...'}]
# Named Entity Recognition
ner = pipeline('ner', model='dbmdz/bert-base-german-cased-ner')
result = ner('My name is Sarah and I live in Paris')
# [{'entity': 'B-PER', 'word': 'Sarah', 'score': 0.995, 'index': 3}]
# Question Answering
qa = pipeline('question-answering', model='distilbert-base-cased-distilled-squad')
context = 'Machine learning is a subset of artificial intelligence'
question = 'What is machine learning?'
answer = qa(question=question, context=context)
# {'answer': 'a subset of artificial intelligence', 'score': 0.95}
# Translation (needs model like 't5-base' or mBART)
translator = pipeline('translation_en_to_es', model='t5-base')
result = translator('Hello, how are you?')Debugging lab
Detecta y corrige el error en el código.
- 01
# Pipeline with custom model from transformers import pipeline classifier = pipeline('sentiment-analysis') # What model is used?
- 02
# Pipeline batch inference classifier = pipeline('sentiment-analysis') # Single text result1 = classifier('I love this!') # Returns list # Multiple texts texts = ['I love this!', 'This is terrible', 'It is okay'] results = classifier(texts) # Returns list of lists?
- 03
# Pipeline overhead # First call: 5 seconds (download + load) # Subsequent calls: 100-500ms # If you need <50ms latency per query, what to do?