Zero Labs
Industry News / AI

HuggingFace Pipeline & Open-Source LLMs

Source Β· Towards AI By Ishwar Ambare

From the publisher’s feed, collected in the ZeroLabs newsroom.

Part 3GenAI Practical Session β€” Detailed NotesSource: Lecture Transcript + HuggingFace Pipeline Docs + HuggingFace ModelsπŸ“‹ Table of ContentsRecap β€” What We’ve Covered So FarOpen-Source AI MarketWhy NOT Train Your Own Model?Language Model vs Large Language ModelBenefits of Open-Source LLMsReal-World Companies Using Open-Source LLMsHugging Face PlatformSetup β€” InstallationHuggingFace Pipeline β€” Core ConceptPipeline Tasks with Code Examples- Sentiment Analysis- Summarization- Zero-Shot Classification- Text Generation- Named Entity Recognition (NER)- Automatic Speech Recognition (ASR)- Image Classification (Multimodal)Advanced Pipeline ParametersHow to Find & Use Models from HuggingFace HubTransformer Architecture β€” RecapRAG β€” Retrieval Augmented Generation (Preview)Data Sources for AI/ML ProjectsHomework AssignmentQuick Reference Cheatsheet1. Recap β€” What We’ve Covered So FarIn previous sessions we covered the fundamentals of NLP:How computers interpret languageHow words in a sentence are relatedHow machines understand sarcasmTokenization, embeddings, attention mechanismTransformer architecture (Encoder–Decoder)Today’s goal: Move from theory β†’ practical application using pre-existing open-source models.2. Open-Source AI MarketWhat is Open Source?Open source software makes its source code freely available for anyone to use, modify, and distribute β€” no licensing fees for commercial use.https://medium.com/media/254890d8bde0897be650783d02eafdf4/hrefKey Insight: ChatGPT cannot be used commercially without an API key and billing. Open-source models like Llama can be used in your products for free.3. Why NOT Train Your Own Model?Three major barriers make training from scratch impractical for individuals and small teams:https://medium.com/media/0bf55bd12bb650b137712ccae381990c/hrefβœ… Solution: Use pre-trained models (LLMs) that have already invested in all three. We fine-tune or use them via API.4. Language Model vs Large Language Modelhttps://medium.com/media/c82f5d5e75318158750b5041a67db4a3/href5. Benefits of Open-Source LLMs1. πŸ’° Cost EffectiveBuild production-grade AI products with zero licensing costsNo per-API-call charges2. πŸ”’ Data Ownership & ControlData stays on your infrastructure β€” no third-party data exposureYou can set compliance rules, GDPR policies, access controlsContrast: When you send data to ChatGPT API, it leaves your control3. πŸ”“ No Vendor Lock-inNot dependent on a single provider (e.g., if NVIDIA drops you, pivot to HuggingFace)Freedom to modify and integrate with any system4. πŸ›‘οΈ Security & Privacy via Community ScrutinyOpen-source code is publicly visible (like pandas on GitHub)Community patches vulnerabilities quicklyCompanies like OpenAI hire ethical hackers to find vulnerabilities in closed models5. πŸ› οΈ Customization & SpecializationBuild domain-specific tools (e.g., Tableau voice extension, Excel formula generator)Fine-tune models on your own data for specialized tasksExample: Integrate Voice-to-Text β†’ LLM β†’ actions in one pipeline6. Real-World Companies Using Open-Source LLMshttps://medium.com/media/3b03381a4f6674e18bf02ae3157b73dd/href7. Hugging Face PlatformURL: huggingface.coβ€œThe platform where the ML community collaborates on models, datasets, and applications.”What’s Availablehttps://medium.com/media/0f6951f6370cdf322fa648b1a4f90a32/hrefKey FactsUse models without even logging in (for most models)Models hosted for free β€” no charges like NVIDIADirect access to Meta’s Llama 3.1, Stability AI’s Stable Diffusion 3, OpenAI’s Whisper, and more8. Setup β€” Installation# Install in Google Colab or local environment!pip install datasets transformers[sentencepiece]Note: PyTorch is a dependency of transformers but gets installed automatically β€” you don’t need to install it separately in Colab.9. HuggingFace Pipeline β€” Core ConceptWhat is a Pipeline?The pipeline object is the simplest and most powerful inference API in HuggingFace Transformers.Pipeline = Model Download + Preprocessing + Forward Pass + Post-processingThink of it like:Streamlit hides the complexity of web servers, sockets, HTML/CSSKeras hides the complexity of TensorFlow operationsPipeline hides all the complex ML code β€” tokenization, attention, decodingBasic Usagefrom transformers import pipeline# Create a pipeline for a specific taskmy_pipeline = pipeline("task-name")# Run inferenceresult = my_pipeline("your input text")What Happens Under the HoodRaw Text Input ↓Convert to Embeddings (Numbers) ↓Attention Mechanism (find important relationships) ↓Logits (raw scores per class) ↓Softmax β†’ Prediction (label + confidence score)Default Model SelectionWhen you don’t specify a model, pipeline selects a default pre-trained model:"sentiment-analysis" β†’ defaults to distilbert-base-uncased-finetuned-sst-2-english"summarization" β†’ defaults to facebook/bart-large-cnn (~1.22 GB)"zero-shot-classification" β†’ defaults to facebook/bart-large-mnliModels are downloaded once and cached locally β€” subsequent calls are fast.10. Pipeline Tasks with Code ExamplesπŸ“Š Sentiment AnalysisTask: Determine if text is positive or negative.from transformers import pipeline# Initializeclassifier = pipeline("sentiment-analysis")# Single sentenceresult = classifier("Food is delicious!")# Output: [{'label': 'POSITIVE', 'score': 0.9998}]# Tricky sentencesclassifier("I wish food was good")# Output: [{'label': 'NEGATIVE', 'score': 0.7762}]# Note: "I wish" implies something is currently NOT the case β†’ NEGATIVE βœ…classifier("I wish food was good!") # With exclamation mark# Output: [{'label': 'POSITIVE', ...}]# Note: Exclamation marks often appear in positive/excited sentences β†’ model flips# Mixed sentimentclassifier("I'm amazed by the speed of the processor but disappointed that it heats up quickly.")# Output: [{'label': 'NEGATIVE', 'score': 0.9983}]# Note: "disappointed" has more weight here# Multiple sentences at once (pass a list)classifier([ "I've been waiting for a HuggingFace course my whole life.", "I hate this so much!"])# Output: [{'label': 'POSITIVE', 'score': 0.9598}, {'label': 'NEGATIVE', 'score': 0.9994}]Key Insight: Default models are NOT perfect β€” they need fine-tuning for production use. Exclamation marks influenced the model’s sentiment because training data has exclamation marks more commonly in positive contexts.πŸ“ SummarizationTask: Condense long text into a shorter summary.from transformers import pipelinesummary = pipeline("summarization")text = """America has changed dramatically during recent years. Not only has the number of graduatesin traditional engineering disciplines declined, but in most of the premier American universities,engineering curricula now concentrate on theoretical and analytical skills rather than thedesign-and-build skills that industrial employers actually need. The result is a severe supply-demandmismatch for engineering graduates. China and India, while continuing to invest in basic andtheoretical knowledge, are graduating six and eight times as many traditional engineersas does the United States."""result = summary(text)# Output: [{'summary_text': 'America has changed dramatically during recent years. The number of# graduates in traditional engineering disciplines has declined. China and India graduate six and# eight times as many traditional engineers as the U.S.'}]How it works (Encoder-Decoder flow):Long Text Input ↓ENCODER β”œβ”€β”€ Tokenizes text into words/subwords β”œβ”€β”€ Converts tokens to embeddings (numbers + positional encoding) └── Attention mechanism β†’ builds rich contextual understanding ↓State Representation (rich understanding of text) ↓DECODER β”œβ”€β”€ Selects the most important information β”œβ”€β”€ Organizes it logically └── Generates concise output ↓Summary Text Output🏷️ Zero-Shot ClassificationTask: Classify text into user-defined labels without any training data.The Problem: In real projects, you rarely have labeled training data. Labeling is:- Time-consuming- Expensive (needs smart annotators)- Resource-intensiveZero-shot classification solves this β€” you define your own labels at runtime.from transformers import pipelinezero_shot = pipeline("zero-shot-classification")# Example: News classification for a media apptext = "India won 2 bronze medals in Pistol shooting"candidate_labels = ["sports", "business", "education"]result = zero_shot(text, candidate_labels=candidate_labels)# Output: {'labels': ['sports', 'education', 'business'],# 'scores': [0.9849, 0.0096, 0.0054]}# β†’ Correctly classified as "sports" with 98.5% confidence!Use Case: News tagging for apps like InShorts β€” automatically categorize incoming news into Politics, Business, Sports, Education, etc. without a labeled training set.Model Used: facebook/bart-large-mnli (Multi-Genre Natural Language Inference)✍️ Text GenerationTask: Auto-complete or extend given text.from transformers import pipeline# Default modelgenerator = pipeline("text-generation")result = generator("In this course, we're gonna learn how to")# Output: [{'generated_text': 'In this course, we\'re gonna learn how to create a simple# user-friendly interface...'}]# Specifying a model with parametersgenerator = pipeline("text-generation", model="distilgpt2")result = generator( "I am designing a course in data science, its curriculum should include", max_length=100, # Limit output length num_return_sequences=2 # Get 2 different responses)# Returns 2 different completions of 100 words eachParameters Explained:https://medium.com/media/6f4683c716af24d1a5ef9afb3074d159/href🏷️ Named Entity Recognition (NER)Task: Identify and classify named entities (persons, organizations, locations) in text.from transformers import pipelinener = pipeline("ner", grouped_entities=True)# grouped_entities=True: groups multi-token entities (e.g., "Scaler Pvt Ltd" as one ORG)text = "My name is Suraaj, I work with Scaler Pvt Ltd as a senior manager in Data Science located in Bangalore"result = ner(text)# Output:# [{'entity_group': 'PER', 'word': 'Suraaj', 'score': 0.99},# {'entity_group': 'ORG', 'word': 'Scaler Pvt Ltd', 'score': 0.98},# {'entity_group': 'LOC', 'word': 'Bangalore', 'score': 0.99}]Entity Types:https://medium.com/media/0fb5a3f755772f767ef49ef6ab4b628c/hrefLimitation: Default models aren’t perfect β€” capitalization of words significantly affects detection. Fine-tuning improves results.πŸŽ™οΈ Automatic Speech Recognition (ASR)Task: Convert audio/speech into text.from transformers import pipeline# Using OpenAI's Whisper model (one of the best ASR models)transcriber = pipeline( task="automatic-speech-recognition", model="openai/whisper-large-v3")# From a URL (audio file)result = transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")# Output: {'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'}# With word-level timestampsresult = transcriber( audio="path/to/audio.flac", return_timestamp="word")# Output includes: {'text': '...', 'chunks': [{'text': ' I', 'timestamp': (0.0, 1.1)}, ...]}Live Voice β†’ Text Workflow:Live Microphone Input ↓Voice capture library (e.g., pyaudio, streamlit audio) ↓Save audio to temp file (WAV/MP3 format) ↓Pass to Whisper Pipeline ↓Transcribed Text Output ↓Delete temp fileWhisper by OpenAI is open-source and one of the most accurate speech recognition models available on HuggingFace.πŸ–ΌοΈ Image Classification (Multimodal)Task: Classify images or extract information from images using text queries.from transformers import pipeline# Visual Question Answering β€” multimodal (image + text β†’ text)vqa_pipeline = pipeline( "document-question-answering", model="impira/layoutlm-document-qa")result = vqa_pipeline( image="path/to/invoice.jpg", question="What is the invoice number?")# Model reads the invoice image and returns the invoice numberWhat β€œMultimodal” Means:Image Input β†’ Computer Vision Model β†’ Extract text/features ↓ Text Query β†’ NLP Understanding β†’ Answer ↓ Final Text OutputGradio Integration: HuggingFace pipelines work directly with Gradio β€” you can build a UI without writing any frontend code:import gradio as grgr.Interface.from_pipeline(pipeline).launch()11. Advanced Pipeline ParametersSpecifying a Different Model# Override default modelpipeline = pipeline("text-classification", model="roberta-base")Hardware Configuration# CPU (default)pipeline = pipeline("text-generation", model="gpt2", device=-1)# GPU (CUDA device 0)pipeline = pipeline("text-generation", model="gpt2", device=0)# Auto distribute across devices (with Accelerate)from accelerate import Acceleratorpipeline = pipeline("text-generation", model="google/gemma-2-2b", device_map="auto")Batch Inference# Process multiple inputs at once (useful for large datasets)pipeline = pipeline("text-generation", model="gpt2", device=0, batch_size=8)# Pass all inputs as a listpipeline(["text1", "text2", "text3", "text4"])Batch Inference Rules of Thumb:https://medium.com/media/5f16b6aa337222a3a735cf5d2f88d9c3/hrefLarge Datasets β€” Streamingfrom transformers.pipelines.pt_utils import KeyDatasetfrom datasets import load_datasetdataset = load_dataset("imdb", split="test")pipeline = pipeline("text-classification", model="distilbert-base-uncased-finetuned-sst-2-english")# Stream results without loading entire dataset into memoryfor out in pipeline(KeyDataset(dataset, "text"), batch_size=8): print(out)Memory Optimization β€” Half Precisionimport torch# Use bfloat16 for faster inference with less memorypipeline = pipeline("text-generation", model="google/gemma-2-2b", dtype=torch.bfloat16, device_map="auto")Memory Optimization β€” Quantizationfrom transformers import BitsAndBytesConfigimport torchpipeline = pipeline( model="google/gemma-7b", dtype=torch.bfloat16, device_map="auto", model_kwargs={"quantization_config": BitsAndBytesConfig(load_in_8bit=True)})12. How to Find & Use Models from HuggingFace HubStep-by-Step ProcessGo to huggingface.co/modelsFilter by task β€” select the task (e.g., Text Classification, Text-to-Image)Sort by: Downloads (most stable, community-supported) or TrendingClick on a model β€” read the model card (what it can do, training data, benchmarks)Click β€œUse this model” β†’ Select TransformersCopy the code snippet β†’ paste into your notebook/scriptFinding Models for Specific Taskshttps://medium.com/media/6d73dade24e182b77533185fe941029c/hrefBest Model for English β†’ SQLβ†’ Meta Llama 3.1 (recommended)# Direct code from HuggingFace model cardfrom transformers import pipelinesql_gen = pipeline("text-generation", model="meta-llama/Meta-Llama-3.1-8B-Instruct")prompt = """Convert the following to SQL:Give me the department with the maximum number of employees.The table 'employees' has columns: id, name, department, salary."""result = sql_gen(prompt, max_new_tokens=200)print(result[0]['generated_text'])Pro Tip: When prompting for SQL, include the table schema in your prompt so the model knows the structure.13. Transformer Architecture β€” RecapHow summarization (and most LLMs) work internally:INPUT TEXT β”‚ β–Όβ”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”‚ ENCODER β”‚β”‚ β”‚β”‚ 1. Tokenize text into words β”‚β”‚ 2. Convert words β†’ embeddings β”‚β”‚ 3. Add positional encodings β”‚β”‚ 4. Self-Attention mechanism: β”‚β”‚ - Find important word pairs β”‚β”‚ - Build contextual meaning β”‚β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β–Ό[Rich Contextual Representation of All Text] β”‚ β–Όβ”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”‚ DECODER β”‚β”‚ β”‚β”‚ 1. Select most important info β”‚β”‚ 2. Organize logically β”‚β”‚ 3. Generate token-by-token β”‚β”‚ 4. Apply beam search / sampling β”‚β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β–ΌOUTPUT (Summary / Translation / Generation)14. RAG β€” Retrieval Augmented Generation (Preview)Q: How do I train a model on my own data and ask it questions?Answer: That’s RAG β€” Retrieval Augmented Generation.Store your custom documents in a vector databaseWhen a user asks a question, retrieve relevant chunks from your documentsAugment the LLM prompt with retrieved contextLLM generates an accurate, grounded answerThis is covered in a dedicated upcoming module. Stay tuned!15. Data Sources for AI/ML ProjectsWhen people ask β€œwhere do companies get training data?”https://medium.com/media/18d194e9454c63ee3f510389abc96a4a/hrefFor Production: Always use APIs or licensed data. Web scraping violates terms of service and copyright law.16. Homework AssignmentTask: Find and use a HuggingFace model that converts English to SQL.Hints:What type of model is this? β†’ Text-to-TextWhat task does it perform? β†’ Question Answering or Text GenerationSearch huggingface.co/models with filter: text-generationRecommended model: Meta-Llama 3.1Provide schema in the prompt: "Table employees has columns: id, name, dept. Write SQL to find the department with maximum employees."17. Quick Reference Cheatsheetfrom transformers import pipeline# ── SENTIMENT ANALYSIS ──────────────────────────────────────────clf = pipeline("sentiment-analysis")clf("I love this product!") # POSITIVEclf(["text1", "text2"]) # Batch# ── SUMMARIZATION ───────────────────────────────────────────────summarizer = pipeline("summarization")summarizer(long_text)# ── ZERO-SHOT CLASSIFICATION ────────────────────────────────────zsc = pipeline("zero-shot-classification")zsc("some news text", candidate_labels=["sports", "politics", "business"])# ── TEXT GENERATION ──────────────────────────────────────────────gen = pipeline("text-generation", model="distilgpt2")gen("Once upon a time", max_length=100, num_return_sequences=2)# ── NAMED ENTITY RECOGNITION ─────────────────────────────────────ner = pipeline("ner", grouped_entities=True)ner("My name is Elon Musk, CEO of Tesla based in Austin")# ── SPEECH RECOGNITION ───────────────────────────────────────────asr = pipeline("automatic-speech-recognition", model="openai/whisper-large-v3")asr("path/to/audio.flac")# ── QUESTION ANSWERING ───────────────────────────────────────────qa = pipeline("question-answering")qa(question="Who won the match?", context="India won the cricket match against Australia.")# ── IMAGE CLASSIFICATION ─────────────────────────────────────────img_clf = pipeline("image-classification")img_clf("path/to/image.jpg")# ── ADVANCED: GPU + BATCH + QUANTIZATION ─────────────────────────import torchfrom transformers import BitsAndBytesConfigfast_pipeline = pipeline( "text-generation", model="google/gemma-7b", device_map="auto", dtype=torch.bfloat16, batch_size=8, model_kwargs={"quantization_config": BitsAndBytesConfig(load_in_8bit=True)})πŸ“š Resourceshttps://medium.com/media/cc8cb1ca29da295701a1c03c5caed30d/hrefNotes created from lecture transcript Β· Practical class on GenAI Β· April 2026πŸ€— HuggingFace Pipeline & Open-Source LLMs was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.