Python / Python Modern Generative AI and Agents Interview Questions
What is the Hugging Face Transformers pipeline API and how do you use it for common NLP and vision tasks?
The pipeline() function in Hugging Face Transformers is the highest-level API — it wraps model loading, tokenisation, inference, and post-processing into a single callable. It is the fastest way to get results from a pre-trained model and is ideal for prototyping and evaluation before committing to a custom training loop.
Pipelines support dozens of tasks out of the box including text generation, classification, named entity recognition, translation, summarisation, question answering, image classification, and zero-shot classification. Specifying a task without a model name loads the current recommended default for that task; specifying a model name loads exactly that checkpoint from the Hugging Face Hub.
from transformers import pipeline # ââ Text generation gen = pipeline('text-generation', model='gpt2') print(gen('The capital of France is', max_new_tokens=20)) # ââ Sentiment / text classification clf = pipeline('sentiment-analysis') # loads recommended default print(clf('I absolutely loved this product!')) # [{'label': 'POSITIVE', 'score': 0.9998}] # ââ Named entity recognition ner = pipeline('ner', aggregation_strategy='simple') print(ner('Hugging Face is based in New York City.')) # ââ Summarisation summ = pipeline('summarization', model='facebook/bart-large-cnn') text = ('Scientists have discovered a new species of deep-sea fish ' 'near the Mariana Trench that can produce bioluminescent light...') * 3 print(summ(text, max_length=60, min_length=20)) # ââ Zero-shot classification (no fine-tuning needed) zsc = pipeline('zero-shot-classification', model='facebook/bart-large-mnli') print(zsc( 'The new iPhone has an impressive camera system.', candidate_labels=['technology', 'sports', 'politics'], )) # ââ Image classification from transformers import pipeline as vp img_clf = vp('image-classification', model='google/vit-base-patch16-224') print(img_clf('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg')) # ââ GPU acceleration gen_gpu = pipeline('text-generation', model='mistralai/Mistral-7B-v0.1', device=0, # GPU 0 torch_dtype='auto') # auto selects bfloat16 on ampere+
More Related questions...