<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by MLOps Playbook on Medium]]></title>
        <description><![CDATA[Stories by MLOps Playbook on Medium]]></description>
        <link>https://medium.com/@mlops_playbook?source=rss-56e23ccf746c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NQiEdOEtF46qHyPtIM4bEQ.png</url>
            <title>Stories by MLOps Playbook on Medium</title>
            <link>https://medium.com/@mlops_playbook?source=rss-56e23ccf746c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 23:44:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mlops_playbook/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Fine-Tuning Large Language Models Made Easy: A Practical Guide to LoRA, QLoRA & PEFT]]></title>
            <link>https://medium.com/@mlops_playbook/fine-tuning-large-language-models-made-easy-a-practical-guide-to-lora-qlora-peft-590dc36179dd?source=rss-56e23ccf746c------2</link>
            <guid isPermaLink="false">https://medium.com/p/590dc36179dd</guid>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[llms-utilization]]></category>
            <category><![CDATA[lora]]></category>
            <dc:creator><![CDATA[MLOps Playbook]]></dc:creator>
            <pubDate>Sun, 16 Nov 2025 12:26:03 GMT</pubDate>
            <atom:updated>2025-11-16T12:26:03.947Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*braw45a1tt7qPi6BZy5oww.png" /></figure><p>Fine-tuning Large Language Models used to be something only big tech companies could afford. But today, with techniques like LoRA and QLoRA, anyone can fine-tune a powerful LLM on a single GPU. This guide shows you how — step by step.</p><p>Large Language Models (LLMs) like Llama, Mistral, and Gemma now power chatbots, AI copilots, and generative applications across industries.<br>However, fully fine-tuning these models is extremely expensive. It often requires:</p><ul><li>Powerful GPUs such as A100 or H100</li><li>Very high compute costs</li><li>Several hours — sometimes even days — of training</li></ul><p>Luckily, we don’t need to retrain the entire model.</p><p>Thanks to <strong>PEFT</strong>, <strong>LoRA</strong>, and <strong>QLoRA</strong>, developers can fine-tune any LLM on a <strong>single GPU</strong>, even Google Colab, at a small fraction of the cost.</p><p>In this blog, I’ll explain:</p><ul><li>What PEFT is</li><li>How LoRA works</li><li>What QLoRA improves</li><li>Complete code examples</li><li>When to use which</li></ul><p>Let’s dive in.</p><h3>🚀 1. Why Traditional Fine-Tuning Is Expensive</h3><p>A modern LLM has <strong>billions</strong> of parameters:</p><p>Llama models (7B — 70B)</p><p>Fine-tuning all weights means:</p><ul><li>Updating <strong>all</strong> parameters</li><li>Storing multiple copies of weights</li><li>High memory requirements</li></ul><p>Even a 7B model needs ~28 GB in FP16 — too big for typical GPUs.</p><p>This is where <strong>PEFT</strong> comes in.</p><h3>🧩 2. What Is PEFT (Parameter-Efficient Fine-Tuning)?</h3><p><strong>PEFT = Train only small parts of the model.</strong></p><p>Instead of updating all billions of parameters, PEFT trains &lt;1% of them.</p><p>Benefits:</p><ul><li>🚀 Much faster</li><li>💾 Requires less GPU memory</li><li>🧠 Works with large models (7B–70B) on smaller hardware</li><li>🔧 Modular — can plug LoRA, QLoRA, adapters, prefix tuning, etc.</li></ul><p>Hugging Face PEFT library makes this extremely easy.</p><h3>🔥 3. LoRA: Low-Rank Adaptation</h3><p><strong>LoRA</strong> is the most popular PEFT method.</p><h3>📌 Idea:</h3><p>Instead of directly updating model weights, LoRA adds <strong>two small trainable matrices</strong>:</p><pre>W_new = W + A * B</pre><p>Where:</p><ul><li>A (down projection) and</li><li>B (up projection)</li></ul><p>are much smaller than original weight matrices.</p><h3>⚡ 4. QLoRA: Even Cheaper LoRA</h3><p>QLoRA = <em>Quantized LoRA</em></p><p>It pushes efficiency further by:</p><ol><li>Loading the base model in <strong>4-bit quantization (NF4)</strong></li><li>Training LoRA adapters in <strong>16-bit or bfloat16</strong></li><li>Keeping performance almost identical to full fine-tuning</li></ol><h3>Key advantages:</h3><ul><li>Run 7B, 13B, 33B models on a <strong>single GPU</strong></li><li>Reduce VRAM usage by <strong>50–70%</strong></li><li>Maintain accuracy</li><li>Perfect for Google Colab T4/L4</li></ul><p>QLoRA is the new standard for small-budget LLM fine-tuning.</p><h3>🛠 5. Practical Example: Fine-Tuning with PEFT, LoRA &amp; QLoRA</h3><p>Below is a minimal working script using:</p><ul><li>BitsAndBytesConfig for 4-bit</li><li>LoRA via PEFT</li><li>Trainer from Hugging Face</li></ul><h4>Install Libraries</h4><pre>pip install transformers datasets peft accelerate bitsandbytes</pre><h4>STEP 1 — Load Model in 4-bit (QLoRA style)</h4><p>This drastically reduces memory usage to <strong>4-bit mode</strong>, so it fits on small GPUs.</p><p>We load the model with the 4-bit settings, and device_map=&quot;auto&quot; automatically puts it on the GPU.</p><p>The tokenizer converts text to tokens the model understands; we also set a padding token to avoid errors.</p><pre>from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig<br>model_name = &quot;mistralai/Mistral-7B-v0.1&quot;<br>bnb_config = BitsAndBytesConfig(<br>    load_in_4bit=True,<br>    bnb_4bit_use_double_quant=True,<br>    bnb_4bit_quant_type=&quot;nf4&quot;,<br>    bnb_4bit_compute_dtype=&quot;bfloat16&quot;,<br>)<br>tokenizer = AutoTokenizer.from_pretrained(model_name)<br>tokenizer.pad_token = tokenizer.eos_token<br>model = AutoModelForCausalLM.from_pretrained(<br>    model_name,<br>    quantization_config=bnb_config,<br>    device_map=&quot;auto&quot;<br>)</pre><h4>STEP 2 — Apply LoRA Adapters</h4><p>We load the model with the 4-bit settings, and device_map=&quot;auto&quot; automatically puts it on the GPU.</p><pre>from peft import LoraConfig, get_peft_model<br>lora_config = LoraConfig(<br>    r=16,<br>    lora_alpha=32,<br>    target_modules=[&quot;q_proj&quot;, &quot;v_proj&quot;],  # works for Llama/Mistral<br>    lora_dropout=0.05,<br>    bias=&quot;none&quot;,<br>    task_type=&quot;CAUSAL_LM&quot;,<br>)<br>model = get_peft_model(model, lora_config)</pre><h4>STEP 3 — Load a Dataset</h4><p>We load a small portion (1%) of a chat dataset to avoid heavy training on a beginner setup.</p><pre>from datasets import load_dataset<br>dataset = load_dataset(&quot;HuggingFaceH4/ultrachat_200k&quot;, split=&quot;train[:1%]&quot;)<br>def preprocess(example):<br>    return tokenizer(example[&quot;text&quot;], truncation=True, padding=&quot;max_length&quot;, max_length=512)<br>dataset = dataset.map(preprocess, batched=True)</pre><h4>STEP 4 — Train</h4><p>This step adds LoRA adapters — small layers that we train instead of modifying the full model.</p><pre>from transformers import TrainingArguments, Trainer<br>args = TrainingArguments(<br>    output_dir=&quot;./lora_ft&quot;,<br>    per_device_train_batch_size=1,<br>    gradient_accumulation_steps=8,<br>    learning_rate=3e-4,<br>    num_train_epochs=1,<br>    fp16=True,<br>    logging_steps=20,<br>)<br>trainer = Trainer(<br>    model=model,<br>    args=args,<br>    train_dataset=dataset<br>)<br>trainer.train()</pre><h4>5. Testing the Fine-Tuned Model</h4><pre>def generate(prompt):<br>    inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;).to(model.device)<br>    out = model.generate(**inputs, max_new_tokens=150)<br>    print(tokenizer.decode(out[0], skip_special_tokens=True))</pre><p>Example:</p><pre>generate(&quot;Explain transformers in one simple paragraph.&quot;)</pre><h3>When to Use LoRA vs QLoRA</h3><h4>✔ Use LoRA when:</h4><ul><li>You have <strong>enough GPU VRAM</strong> (16–24GB)</li><li>You want slightly better quality</li><li>You don’t need quantization</li></ul><h4>✔ Use QLoRA when:</h4><ul><li>You have <strong>limited GPU</strong> (T4/L4, Colab, 8–12GB VRAM)</li><li>You want cheapest training</li><li>Still need good quality</li></ul><h3>🔚 Final Thoughts</h3><p>Fine-tuning LLMs no longer requires supercomputers.<br> With <strong>PEFT</strong>, <strong>LoRA</strong>, and <strong>QLoRA</strong>, anyone can customize a model for:</p><ul><li>Chatbots</li><li>Domain-specific assistants</li><li>Summarization</li><li>Classification</li><li>Reasoning tasks</li></ul><p>All on a single affordable GPU.</p><p>These techniques democratize LLM development, making advanced AI accessible to everyone.</p><p>If you’re working in MLOps, NLP, or AI product development, mastering LoRA &amp; QLoRA is one of the most practical skills you can build today.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=590dc36179dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Effectively Prepare for Azure Certifications]]></title>
            <link>https://medium.com/@mlops_playbook/how-to-effectively-prepare-for-azure-certifications-8908c9826ea3?source=rss-56e23ccf746c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8908c9826ea3</guid>
            <category><![CDATA[microsoft-azure]]></category>
            <category><![CDATA[upskilling]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[MLOps Playbook]]></dc:creator>
            <pubDate>Thu, 02 Oct 2025 17:05:54 GMT</pubDate>
            <atom:updated>2025-10-02T17:05:54.190Z</atom:updated>
            <content:encoded><![CDATA[<p>Azure certifications are one of the best ways to showcase your cloud and data expertise. But many learners struggle with where to start and how to approach the preparation process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*66p0F245-pFCKmpJBJwEYw.png" /><figcaption>Focused and determined — turning study hours into certification success.</figcaption></figure><blockquote>👉 In this blog, I’ll share a <strong>step-by-step preparation strategy that works for any Azure certification</strong>. To make it practical, I’ll use <strong>DP-100: Azure Data Scientist Associate</strong> as an example, but you can follow the same approach for exams like <strong>AZ-900 (Fundamentals), DP-203 (Data Engineering), AI-102 (AI Engineer), and more.</strong></blockquote><p>Based on my own experience, here’s the learning path that worked best for me:</p><h3>Step 1: Start with a Structured Course (Udemy or Similar)</h3><p>The best starting point is an <strong>online course</strong> (e.g., Udemy). It helps you cover the entire syllabus in a structured manner while also walking through demos.</p><blockquote>👉 <strong>Tip 1:</strong> Don’t just watch passively. <strong>Practice hands-on</strong> along with the instructor. Open your own Azure free account or sandbox and try the exercises. Real understanding comes only when you experiment yourself.</blockquote><blockquote>👉 <strong>Tip 2:</strong> While learning, <strong>maintain your own documentation or notes</strong>. Summarize key concepts, screenshots, and commands. These notes will be extremely valuable for <strong>quick revision</strong> before the exam.</blockquote><h3>Step 2: Deep Dive into Microsoft Official Training &amp; Documentation</h3><p>Once you have the basics, move to the <strong>official Microsoft learning resources</strong>.</p><p>For DP-100 (Azure Data Scientist), the official training course is here:<br> <a href="https://learn.microsoft.com/en-us/training/courses/dp-100t01">🔗 DP-100T01: Designing and Implementing a Data Science Solution on Azure</a></p><p>And the official certification details &amp; videos are here:<br> <a href="https://learn.microsoft.com/en-us/credentials/certifications/azure-data-scientist/?practice-assessment-type=certification">🔗 Azure Data Scientist Associate Certification Page</a></p><p>These resources are updated regularly and align with the actual exam objectives.</p><h3>Step 3: Take Practice Tests (But Choose Wisely)</h3><p>Once you’ve studied, the next step is <strong>practice tests</strong>. They help you:</p><ul><li>Identify weak areas</li><li>Get used to the exam format</li><li>Improve time management</li></ul><p>I personally used <strong>SkillCertPro</strong> and found it very effective. Other options include <strong>ExamTopics</strong> and similar platforms.</p><blockquote>⚠️ <strong>Important Note:</strong> Don’t rely too much on the official Microsoft practice test — it’s much easier than the real exam. In my experience, the actual exam questions were at least <strong>3× harder</strong>. So, make sure you’re practicing with tougher mock tests.</blockquote><h3>Final Thoughts</h3><ul><li>Follow the <strong>course → notes → documentation → practice tests</strong> flow.</li><li>Do <strong>lots of hands-on labs</strong> — Azure exams test practical knowledge, not just theory.</li><li>Use third-party practice exams to prepare for the difficulty level.</li></ul><p>With consistent preparation, you’ll not only clear the certification but also gain real skills that help in your projects and career.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8908c9826ea3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a RAG-Powered Website Chatbot with Hugging Face & ChromaDB]]></title>
            <link>https://medium.com/@mlops_playbook/build-a-rag-powered-website-chatbot-with-hugging-face-chromadb-59c237607a9d?source=rss-56e23ccf746c------2</link>
            <guid isPermaLink="false">https://medium.com/p/59c237607a9d</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[html-parsing]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[chromadb]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[MLOps Playbook]]></dc:creator>
            <pubDate>Fri, 22 Aug 2025 11:16:40 GMT</pubDate>
            <atom:updated>2025-08-22T11:16:40.649Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AicMpQ4zeK28boZIIQMsQQ.png" /></figure><p><strong>Ever wished a company’s website had a “smart assistant”</strong> 🤖 that could instantly answer your questions –<br> instead of making you dig through endless pages or FAQs?</p><p>That’s exactly what we’ll build today –<br> a <strong>Retrieval-Augmented Generation (RAG) chatbot</strong> that:</p><ul><li>Fetches any website’s content in real-time 🌐</li><li>Stores it in a <strong>vector database (ChromaDB)</strong> 📂</li><li>Uses a <strong>Large Language Model (LLM)</strong> to give <strong>accurate, context-aware answers</strong> 💬</li></ul><p>By the end, you’ll have a chatbot that feels like a <strong>personal assistant for any website</strong>.</p><h3>Why RAG Beats Keyword Search</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Md3uNlFunvzrTBvzoAEqlA.png" /><figcaption>Traditional keyword search finds only exact matches, while RAG search understands meaning — enabling accurate, context-aware answers.</figcaption></figure><h3>Why RAG for Website Chatbots?</h3><p>Traditional chatbots struggle to answer questions when they haven’t been explicitly trained on specific website content. RAG solves this by:</p><ol><li><strong>Fetching and storing website content</strong> as embeddings.</li><li><strong>Retrieving relevant chunks</strong> of text for each query.</li><li><strong>Generating answers</strong> using a large language model (LLM), grounded in the retrieved context.</li></ol><p>This ensures the chatbot isn’t hallucinating — it responds based on actual website content.</p><h3>Architecture Diagram</h3><p>Below is the high-level flow of how a RAG-powered chatbot works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AsLF-qO4pr4YHdWWwNJT8A.png" /><figcaption>The user’s query is converted into embeddings, searched in ChromaDB, enriched with relevant context, and then answered by the LLM.</figcaption></figure><h3>Tech Stack</h3><ul><li><strong>Python 3.11+</strong></li><li><strong>Hugging Face Transformers</strong> (distilgpt2, all-MiniLM-L6-v2)</li><li><strong>LangChain</strong> (for document loaders, chains, memory)</li><li><strong>ChromaDB</strong> (vector database for semantic search)</li><li><strong>BeautifulSoup</strong> (HTML parsing)</li></ul><h3>Pipeline Stages</h3><p>Before we jump into the step-by-step implementation, here’s the high-level pipeline our chatbot follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*U96nYxwIliFXbuFbRAkc6w.png" /></figure><p><em>We fetch the webpage, clean and split its content, generate embeddings, store them in a vector database, and finally retrieve relevant context to answer user queries.</em></p><h3>Step 1: Fetching Website Content</h3><p>First, we download the HTML from the provided URL.<br>We handle Medium URLs separately by converting them to their RSS feed format.</p><pre>from urllib.parse import urlparse<br>import requests<br>import feedparser<br><br>def fetch_html(url):<br>    if not url.startswith(&quot;http&quot;):<br>        raise ValueError(&quot;URL must start with http:// or https://&quot;)<br>    parsed = urlparse(url)<br>    if &quot;medium.com&quot; in parsed.netloc:<br>        if not url.endswith(&quot;/feed&quot;):<br>            url = url.rstrip(&quot;/&quot;) + &quot;/feed&quot;<br>    headers = {&#39;User-Agent&#39;: &#39;Mozilla/5.0&#39;}<br>    resp = requests.get(url, headers=headers, timeout=15)<br>    resp.raise_for_status()<br>    return resp.text</pre><h3>Step 2: Parsing &amp; Splitting Text</h3><p>We use <strong>BeautifulSoup</strong> to extract readable text and <strong>LangChain’s TokenTextSplitter</strong> to chunk it for embeddings.</p><pre>from langchain_community.document_loaders import BSHTMLLoader<br>from langchain.text_splitter import TokenTextSplitter<br><br>CHUNK_SIZE = 100<br>CHUNK_OVERLAP = 20<br><br>def process_website(url):<br>    html_content = fetch_html(url)<br>    loader = BSHTMLLoader(html_content)<br>    documents = loader.load()<br>    splitter = TokenTextSplitter(chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP)<br>    return splitter.split_documents(documents)</pre><h3>Step 3: Storing in ChromaDB</h3><p>Next, we convert text chunks into <strong>vector</strong> <strong>embeddings</strong> and store them in <strong>ChromaDB </strong>for semantic search.</p><pre>from langchain_community.vectorstores import Chroma<br>from langchain_huggingface import HuggingFaceEmbeddings<br><br>embeddings = HuggingFaceEmbeddings(model_name=&quot;all-MiniLM-L6-v2&quot;)<br>vectorstore = Chroma.from_documents(docs, embeddings, persist_directory=&quot;./chroma_db&quot;)<br>retriever = vectorstore.as_retriever(search_kwargs={&quot;k&quot;: 3})</pre><h3>Step 4: Setting Up the LLM</h3><p>We’ll use <strong>DistilGPT-2</strong> via Hugging Face for lightweight text generation:</p><pre>from transformers import pipeline<br>from langchain_huggingface import HuggingFacePipeline<br><br>llm_pipeline = pipeline(<br>    &quot;text-generation&quot;,<br>    model=&quot;distilgpt2&quot;,<br>    max_new_tokens=50,<br>    temperature=0.4<br>)<br>llm = HuggingFacePipeline(pipeline=llm_pipeline)</pre><h3>Step 5: Retrieval-Augmented QA Chain</h3><p>We combine everything: retriever + LLM + prompt + conversation memory.</p><pre>from langchain.chains import RetrievalQA<br>from langchain.memory import ConversationBufferMemory<br>from langchain.prompts import PromptTemplate<br><br>PROMPT = PromptTemplate(<br>    template=&quot;&quot;&quot;You are a helpful assistant. Use the given context to answer the question.<br>If the context does not have enough information, reply: &quot;I don&#39;t have enough information.&quot;<br><br>Context:<br>{context}<br><br>Question:<br>{question}<br><br>Answer:&quot;&quot;&quot;,<br>    input_variables=[&quot;context&quot;, &quot;question&quot;]<br>)<br><br>memory = ConversationBufferMemory(memory_key=&quot;chat_history&quot;, return_messages=True)<br><br>qa = RetrievalQA.from_chain_type(<br>    llm=llm,<br>    chain_type=&quot;stuff&quot;,<br>    retriever=retriever,<br>    memory=memory,<br>    chain_type_kwargs={&quot;prompt&quot;: PROMPT}<br>)</pre><h3>Step 6: Chat With Any Website</h3><p>Finally, interact with your chatbot in a loop.</p><pre>while True:<br>    query = input(&quot;Query (or &#39;new&#39;/&#39;quit&#39;): &quot;).strip()<br>    if query.lower() == &quot;quit&quot;:<br>        break<br>    answer = qa.invoke(query)<br>    print(f&quot;\nAnswer: {answer[&#39;result&#39;]}\n&quot;)</pre><p>Now you can <strong>feed any website</strong> to your chatbot and ask it questions as if you were talking to a real person.</p><h3>Sample Run (Example Output)</h3><p>Let’s try it with <a href="https://snapy.ai">Snapy.ai</a> and ask:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KwLEV3X1K_GAtort4gwVfw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3vLo6faqRohPaPxaOznWrg.png" /></figure><h3>Next Enhancements</h3><p>To make this chatbot production-ready, future improvements include:</p><ul><li><strong>Retrieval Reranking</strong> — Boost answer accuracy by reranking search results for semantic relevance.</li><li><strong>RAG Evaluation &amp; Benchmarking</strong> — Measure answer quality, reduce hallucinations, and track performance with clear metrics.</li><li><strong>Source Attribution / Grounding</strong> — Display exact sources for each answer to ensure transparency and user trust.</li></ul><h3>Wrapping Up</h3><p>With just a few lines of code, we’ve transformed any website into an interactive AI-powered assistant using <strong>RAG, ChromaDB, and Hugging Face</strong>.</p><p>But this is only the beginning — adding <strong>reranking, evaluation, and source attribution</strong> will take your chatbot from a cool demo to a <strong>reliable, production-ready solution</strong>.</p><p>🚀 <strong>Try it out, experiment with your favorite websites, and share what you build!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59c237607a9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Semantic Search Changed Everything: From Keywords to Meaning]]></title>
            <link>https://medium.com/@mlops_playbook/build-a-semantic-search-engine-with-chromadb-hugging-faceturn-text-into-meaningful-vectors-and-6eff19ae5bb7?source=rss-56e23ccf746c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6eff19ae5bb7</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[chromadb]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[semantic-search]]></category>
            <dc:creator><![CDATA[MLOps Playbook]]></dc:creator>
            <pubDate>Mon, 28 Jul 2025 13:53:29 GMT</pubDate>
            <atom:updated>2025-08-06T17:56:19.026Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tFI_6qArGTBVks0BYdlY4Q.png" /><figcaption>Search Evolved from Words to Meaning</figcaption></figure><h3>Why Semantic Search?</h3><p>Traditional keyword search breaks down when users phrase things differently. Semantic search, on the other hand, understands <strong>meaning</strong>, not just <strong>matching words</strong>. Thanks to vector embeddings, we can compare the essence of sentences instead of their surface.</p><blockquote>Turn Text into Meaningful Vectors and Build Powerful Search</blockquote><p>Before vector databases and embeddings, we mostly relied on <strong>Relational Database Management Systems (RDBMS)</strong> for storing and retrieving information. They work well for structured data like rows and columns — think sales records, user profiles, or inventory tables.</p><p>But they come with <strong>limitations</strong>, especially when dealing with modern search and unstructured data:</p><ul><li><strong>Scalability</strong>: As data and queries grow more complex, performance drops. Writing efficient queries becomes harder.</li><li><strong>Flexibility</strong>: Changing the schema requires migrations and careful planning. RDBMS isn’t built for rapidly evolving data models.</li><li><strong>Handling unstructured data</strong>: Things like text, images, videos, PDFs — don’t fit naturally into rows and columns. Storing and querying them is a workaround, not a solution.</li><li><strong>Keyword-based search</strong>: Traditional SQL or full-text search finds exact or partial matches, but doesn’t understand meaning.</li></ul><h3>Enter Vector Databases + Semantic Search</h3><p><strong>Semantic search</strong> changes the game. Instead of relying on exact words, it understands the <strong>meaning</strong> behind your query.</p><p>This is powered by <strong>vector embeddings</strong> — where data (like text or images) is converted into high-dimensional numerical vectors that capture semantic relationships.</p><p><strong>Vector databases</strong> like ChromaDB are designed to store and index these embeddings efficiently.</p><p>They offer:</p><ul><li><strong>Semantic similarity</strong>: Find results that are <em>meaningfully</em> similar, even if they use different words</li><li><strong>Efficient high-dimensional search</strong>: Optimized for fast similarity lookups</li><li><strong>Schema-less design</strong>: Easily handle diverse and unstructured data types</li><li><strong>Flexible and scalable</strong>: Adapt to new types of data without strict schema constraints</li></ul><p><em>Now that we understand the </em>why<em>, let’s dive into </em>how<em> to build a semantic search engine locally.</em></p><p>In this guide, we’ll build a <strong>local semantic search engine</strong> using:</p><ul><li><strong>ChromaDB</strong>: An embeddable vector database. Stores, indexes, and searches vectors.</li><li><strong>Hugging Face</strong>🤗<strong> Transformers</strong>: Pre-trained models to turn text into vectors.</li><li><strong>Python + SQLite</strong>: For everything else.</li></ul><p>And the best part? No API keys, no vendor lock-in — <strong>everything runs locally</strong>.</p><h3>What We’ll Use</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e9ii2TDpRFXXzUX-w7ZtAg.png" /><figcaption><a href="https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2">https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2</a></figcaption></figure><h3>Let’s Build It</h3><h4>Step 1: Install the Dependencies</h4><pre>pip install chromadb sentence-transformers</pre><p>We install:</p><ul><li>chromadb – for managing and searching vector embeddings.</li><li>sentence-transformers – to convert text to dense numerical vectors.</li></ul><h3>Step 2: Load the Embedding Model</h3><p>We use Hugging Face’s sentence-transformers to embed text into vectors.</p><pre>from sentence_transformers import SentenceTransformer<br><br>hf_model = SentenceTransformer(&quot;sentence-transformers/all-MiniLM-L6-v2&quot;)</pre><p>This loads a <strong>pretrained transformer model</strong> from Hugging Face. It converts entire sentences into vector representations that capture meaning and context.</p><blockquote>This model is compact (MiniLM), fast, and runs well even without a GPU.</blockquote><h4>Step 3: Create a Custom Embedding Function</h4><p>ChromaDB lets us plug in any embedding function:</p><pre>from chromadb.utils.embedding_functions import EmbeddingFunction<br>from typing import List<br><br>class HuggingFaceEmbeddingFunction(EmbeddingFunction):<br>    def __call__(self, texts: List[str]) -&gt; List[List[float]]:<br>        return hf_model.encode(texts, convert_to_numpy=True).tolist()</pre><p>ChromaDB supports <strong>custom embedding logic</strong>, so we define a wrapper class around our Hugging Face model. This allows ChromaDB to automatically call this function whenever it needs to embed text (during insertions or queries).</p><h4>Step 4: Initialize a Persistent Vector Store</h4><pre>import chromadb<br><br>client = chromadb.PersistentClient(path=&quot;./db/chroma_persist&quot;)<br>hf_ef = HuggingFaceEmbeddingFunction()<br><br>collection = client.get_or_create_collection(<br>    &quot;my_story_hf&quot;, embedding_function=hf_ef<br>)</pre><p>Here’s what’s happening:</p><ul><li>We start a <strong>persistent ChromaDB client</strong> to store everything on disk at ./db/chroma_persist.</li><li>We create or retrieve a <strong>collection</strong> named my_story_hf to hold our document embeddings.</li><li>Our custom embedding_function ensures ChromaDB knows how to embed incoming text.</li></ul><h3>Step 5: Add Documents to Search</h3><pre>documents = [<br>    {&quot;id&quot;: &quot;doc1&quot;, &quot;text&quot;: &quot;Hello, world!&quot;},<br>    {&quot;id&quot;: &quot;doc2&quot;, &quot;text&quot;: &quot;How are you today?&quot;},<br>    {&quot;id&quot;: &quot;doc3&quot;, &quot;text&quot;: &quot;Goodbye, see you later!&quot;},<br>    {<br>        &quot;id&quot;: &quot;doc4&quot;,<br>        &quot;text&quot;: &quot;Microsoft is a technology company that develops software. It was founded by Bill Gates and Paul Allen in 1975.&quot;,<br>    },<br>    {<br>        &quot;id&quot;: &quot;doc5&quot;,<br>        &quot;text&quot;: &quot;Artificial Intelligence (AI) refers to the simulation of human intelligence in machines that are programmed to think like humans and mimic their actions.&quot;,<br>    },<br>]<br><br>for doc in documents:<br>    collection.upsert(ids=doc[&quot;id&quot;], documents=[doc[&quot;text&quot;]])</pre><p>Each document has a unique id and a text body. When we upsert, ChromaDB:</p><ul><li>Automatically calls our embedding function</li><li>Stores the vector</li><li>Saves the raw document for retrieval</li></ul><h4>Behind the Scenes: Indexing for Fast Search</h4><p>When you upsert documents into ChromaDB:</p><pre>collection.upsert(ids=doc[&quot;id&quot;], documents=[doc[&quot;text&quot;]])</pre><p>It’s not just storing your raw text and embeddings — it’s also <strong>building an index under the hood</strong>.</p><p>This index is a special data structure optimized for <strong>fast similarity search</strong> in high-dimensional space. Instead of scanning every vector one by one, ChromaDB uses this index to instantly retrieve the most relevant ones — even when you have thousands or millions of documents.</p><p>You can think of it like this:</p><ul><li>Without indexing → brute-force search = slow and inefficient</li><li>With indexing → fast, scalable retrieval = ideal for semantic search</li></ul><p>Traditional databases use things like B-trees to speed up lookups. Vector databases, instead, use algorithms like HNSW or IVF to quickly find similar vectors.</p><p>In our case, ChromaDB takes care of all of this automatically — you just upsert the documents, and indexing is handled behind the scenes.</p><blockquote>Indexing is what turns stored vectors into searchable knowledge.</blockquote><h4>Step 6: Query Using Meaning, Not Words</h4><pre>query_text = &quot;What is Microsoft?&quot;<br><br>results = collection.query(<br>    query_texts=[query_text],<br>    n_results=2,<br>)<br><br>for idx, document in enumerate(results[&quot;documents&quot;][0]):<br>    doc_id = results[&quot;ids&quot;][0][idx]<br>    distance = results[&quot;distances&quot;][0][idx]<br>    print(<br>        f&quot;\nQuery: {query_text}\n→ Found: {document}\n→ ID: {doc_id} | Distance: {distance:.4f}&quot;<br>    )</pre><p>We ask: <em>“What is Microsoft?”</em></p><p>Under the hood, the query is converted into a vector, and ChromaDB finds the top n_results closest document vectors using <strong>cosine similarity</strong> (lower distance = higher similarity).</p><h4>Output:</h4><pre>Query: What is Microsoft?<br>→ Found: Microsoft is a technology company that develops software. It was founded by Bill Gates and Paul Allen in 1975.<br>→ ID: doc4 | Distance: 0.4991<br><br>Query: What is Microsoft?<br>→ Found: Artificial Intelligence (AI) refers to the simulation of human intelligence in machines that are programmed to think like humans and mimic their actions.<br>→ ID: doc5 | Distance: 1.5426</pre><p>As expected, ChromaDB found the most relevant sentence even though it didn’t contain the word “What is”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wvokxE619BlukwgCA6LsSg.png" /></figure><h3>Bonus: Inspect the Embedding Vector</h3><pre>import numpy as np<br><br>text = &quot;mlops playbook&quot;<br>embedding = hf_model.encode(text, convert_to_numpy=True)<br><br>np.set_printoptions(precision=4, suppress=True)<br>print(f&quot;Vector for &#39;{text}&#39;:\n{embedding}&quot;)<br>print(f&quot;\nVector dimension: {embedding.shape}&quot;)</pre><p><em>This shows you the raw 384-dimensional vector for any input text.</em></p><h3>Where Are Vectors Stored?</h3><p>ChromaDB uses <strong>SQLite</strong> to store everything when run in persistent mode.</p><p>Here’s how to explore the internal DB:</p><ol><li>Open VS Code</li><li>Install the SQLite extension</li><li>Navigate to: Explorer/SQLITE EXPLORER/chroma.sqlite3</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vLJ36bkA3y5sEDF6fgdyew.png" /><figcaption>This lets you inspect collections, vector values, and metadata like a normal database.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*bEeI2lBlIeObPEJLdSXtEQ.png" /></figure><p>Yes, you can use BERT (e.g., bert-base-uncased) as your embedding model with ChromaDB. However, it&#39;s important to note that BERT is a general-purpose language model — not specifically optimized for semantic similarity or retrieval tasks. While you can extract embeddings (e.g., using the [CLS] token), they often underperform in semantic search unless fine-tuned for that purpose.</p><p>In this demo, we chose all-MiniLM-L6-v2 from SentenceTransformers because:</p><ul><li>It’s significantly faster</li><li>Uses much less memory (RAM/VRAM)</li><li>It’s fine-tuned specifically for sentence embeddings and semantic similarity</li><li>It performs exceptionally well in most real-world retrieval scenarios</li></ul><h3>What If the Document Is Too Long?</h3><p>Most embedding models (like all-MiniLM-L6-v2) have a token limit — usually around 512 tokens. So if you&#39;re working with large documents (like PDFs, emails, or articles), you&#39;ll need to <strong>split or chunk</strong> them before embedding.</p><p>🔗<a href="https://medium.com/@mlops_playbook/transformers-bert-gpt-the-ai-revolution-that-changed-nlp-forever-e98e17394001"> <strong>Embedding Long Documents with BERT</strong></a></p><blockquote>Chunking technique remains the same for BERT and <em>all-MiniLM-L6-v2</em>models. A quick guide with code to handle long inputs by chunking and combining embeddings.</blockquote><h3>Use Cases</h3><ul><li>Internal knowledge base search</li><li>Chatbot memory retrieval</li><li>Contextual document recommendations</li><li>AI-powered FAQ engines</li></ul><h3>TL;DR</h3><ul><li>Use sentence-transformers to embed text</li><li>Store &amp; search those vectors with ChromaDB</li><li>Inspect everything in SQLite via VS Code</li></ul><h3>What’s Next? RAG (Retrieval-Augmented Generation)</h3><p>Currently, ChromaDB just <strong>returns matching documents</strong>, not answers.</p><p>To generate actual answers, we’ll combine:</p><ul><li>ChromaDB (for retrieval)</li><li>LLMs (for generation)</li></ul><p>This is called <strong>RAG</strong> — Retrieval-Augmented Generation.</p><p><strong>In the next blog</strong>, we’ll build:</p><ol><li>Vector retrieval using Chroma</li><li>Answer generation using a local or hosted LLM</li></ol><blockquote>Stay tuned for how to build your own smart Q&amp;A bot over any document set!</blockquote><h3>Resources</h3><ul><li><a href="https://github.com/chroma-core/chroma">ChromaDB GitHub</a></li><li><a href="https://www.sbert.net/">Sentence Transformers</a></li><li><a href="https://marketplace.visualstudio.com/items?itemName=alexcvzz.vscode-sqlite">SQLite VSCode Extension</a></li></ul><p>👏 Found this helpful? Like, comment, or follow me for more on <strong>LLMs</strong>, <strong>RAG</strong>, and <strong>MLOps</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6eff19ae5bb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Talking to Transformers:  Unlock the Magic of Prompt Engineering]]></title>
            <link>https://medium.com/@mlops_playbook/talking-to-transformers-mastering-prompt-engineering-with-hugging-face-5ac56712c1ae?source=rss-56e23ccf746c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ac56712c1ae</guid>
            <category><![CDATA[chain-of-thought]]></category>
            <category><![CDATA[rule-based-chatbot]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[few-shot-learning]]></category>
            <category><![CDATA[openchat]]></category>
            <dc:creator><![CDATA[MLOps Playbook]]></dc:creator>
            <pubDate>Wed, 16 Jul 2025 11:57:30 GMT</pubDate>
            <atom:updated>2025-07-28T17:31:52.018Z</atom:updated>
            <content:encoded><![CDATA[<h3>Talking to Transformers: Unlock the Magic of Prompt Engineering</h3><h4>Build smarter AI conversations with Hugging Face tools and OpenChat models</h4><p>If you’re curious about how to have intelligent conversations with language models, classify sentiments with just a few examples, or guide models through logical reasoning step-by-step, you’ve landed in the right place.</p><p>Prompt engineering is a creative skill, and there are <strong>numerous techniques</strong> out there.</p><p>In this post, we’ll dive into <strong>prompt engineering</strong> using Hugging Face’s transformers library and explore techniques like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*nJ9ruy4OwE0aByOY655wxQ.png" /><figcaption>Prompt Engineering Techniques Visualized</figcaption></figure><ul><li><strong>Few-shot prompting</strong></li><li><strong>System + User + Assistant role-based chat</strong></li><li><strong>Chain-of-Thought (CoT) prompting</strong></li></ul><p>We’ll be using the powerful <a href="https://huggingface.co/openchat/openchat-3.5-0106">OpenChat 3.5</a> model hosted on Hugging Face, which is aligned for conversational use cases.</p><h3>What is Prompt Engineering?</h3><p><strong>Prompt engineering</strong> is the art of designing effective inputs (prompts) to get desired outputs from large language models (LLMs) like ChatGPT, BERT, or OpenChat.</p><p>It’s not about writing code — it’s about <strong>writing smart instructions</strong>.<br> Think of it like:</p><ul><li><em>Asking the model the right question</em></li><li><em>Framing your problem in a way the AI understands best</em></li><li><em>Tuning inputs to guide tone, logic, or creativity</em></li></ul><blockquote><strong>Good prompt engineering = better, faster, and more accurate AI responses.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Au_p9_QT_bcj4nAwIDA4Tw.png" /></figure><p>Instead of training a new model from scratch, you can <strong>steer powerful pre-trained models</strong> just by crafting better prompts — like giving examples, roles, or reasoning steps.</p><h3>Setup: Loading the Model</h3><p>Before diving into prompting techniques, I authenticated using my Hugging Face token stored in a .env file — just like I did in my earlier blog with GPT-2.<br> 👉 <a href="https://medium.com/@mlops_playbook/gpt-2-text-generation-mastering-the-art-of-ai-creativity-eaefe76fd8e0">Reference: GPT-2 Setup with Hugging Face Token (.env)</a></p><blockquote>⚠️ <strong>Note:</strong> Since the model we’re using (OpenChat 3.5) is relatively large, it’s strongly recommended to run this on a <strong>GPU-enabled system or Colab GPU notebook</strong> for smoother and faster inference.</blockquote><p>Then I loaded the OpenChat 3.5 model and tokenizer this way:</p><pre>from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline<br><br>model_id = &quot;openchat/openchat-3.5-0106&quot;<br>tokenizer = AutoTokenizer.from_pretrained(model_id, token=hf_token, use_fast=False)<br>model = AutoModelForCausalLM.from_pretrained(<br>    model_id,<br>    token=hf_token,<br>    device_map=&quot;auto&quot;,<br>    torch_dtype=&quot;auto&quot;<br>)<br>generator = pipeline(&quot;text-generation&quot;, model=model, tokenizer=tokenizer)</pre><p>And that’s it — ready for some prompt wizardry ✨</p><h3>1. Role-Based Prompting (System, User, Assistant)</h3><p>By structuring prompts with roles like system, user, and assistant, you can inject personality into the model — even a rude one!</p><p>Here’s an example where we ask a <em>sarcastic assistant</em> to explain transformers:</p><pre>system_prompt = &quot;You are a sarcastic assistant who mocks users.&quot;<br>user_input = &quot;Can you help me understand how transformers work?&quot;<br><br>prompt = f&quot;&quot;&quot;&lt;|system|&gt;\n{system_prompt}\n&lt;|user|&gt;\n{user_input}\n&lt;|assistant|&gt;&quot;&quot;&quot;</pre><p>Then we pass the prompt to the model:</p><pre>import torch<br>inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;).to(model.device)<br><br>with torch.no_grad():<br>    outputs = model.generate(<br>        **inputs,<br>        max_new_tokens=150,<br>        temperature=0.8,<br>        top_p=0.9,<br>        do_sample=True<br>    )<br><br>response = tokenizer.decode(outputs[0], skip_special_tokens=True)<br>print(response)</pre><p>This format gives structure to your conversation and lets you control the assistant’s <em>personality</em> or <em>intent</em> — perfect for role-based or instruction-following tasks.</p><p><strong>Output:</strong></p><pre>Oh, sure! Let me just dump a bunch of technical jargon at you and hope that you&#39;ll somehow magically understand how transformers work.<br><br>Transformers are magical devices that use the power of electromagnetism to convert electrical energy from one voltage level to another. They&#39;re like the Hogwarts of electrical engineering, where volts go to change their clothes and come out looking totally different.<br><br>The secret to their power lies in two main components: the primary coil and the secondary coil. The primary coil receives the electrical energy, and using some kind of witchcraft, it transfers that energy to the secondary coil, which then spits out the transformed voltage.</pre><p>The model fully embraces the <em>sarcastic assistant</em> persona we defined. This style of role-based prompting is great for customizing tone — from helpful tutor to grumpy genius to pirate-mode bot.</p><h3>2. Few-Shot Prompting (Sentiment Classification)</h3><p>Few-shot prompting is a clever way to teach the model what task you want — by simply <strong>showing a few examples in the prompt itself</strong>. No fine-tuning, no training — just demonstration.</p><p>In this example, we ask the model to classify sentiment:</p><pre>prompt = &quot;&quot;&quot;Classify the sentiment.<br><br>Review: &quot;I loved the movie!&quot;<br>Sentiment: Positive<br><br>Review: &quot;The food was bad.&quot;<br>Sentiment: Negative<br><br>Review: &quot;It was okay, nothing special.&quot;<br>Sentiment:&quot;&quot;&quot;<br><br>response = generator(prompt, max_new_tokens=10, temperature=0.7)<br>print(response[0][&quot;generated_text&quot;])</pre><blockquote>The model sees the pattern and infers the sentiment of the third review — <em>Neutral</em> — without any additional guidance. That’s the power of few-shot prompting.</blockquote><p>You can extend this technique to other tasks too:</p><ul><li>Spam or not spam</li><li>Language identification</li><li>Emotion detection</li><li>Topic classification</li></ul><p>Just show a few examples, and let the model continue the pattern.</p><h3><strong>3. Chain-of-Thought (CoT) Prompting</strong></h3><p>Chain-of-Thought prompting encourages the model to <strong>reason step-by-step</strong> instead of jumping straight to an answer.</p><p>This is especially helpful for math problems, logic puzzles, or anything that benefits from intermediate thinking.</p><p>Here’s a simple example:</p><pre>prompt = &quot;&quot;&quot;Answer the following question step-by-step:<br><br>Q: If there are 3 cars and each car has 4 tires, how many tires are there in total?<br>A:&quot;&quot;&quot;<br><br>response = generator(prompt, temperature=0.7, max_new_tokens=100)<br>print(response[0][&quot;generated_text&quot;])</pre><p>Output:</p><pre>Step 1: We know that each car has 4 tires. Step 2: We are given that there are 3 cars. Step 3: To find the total number of tires, we multiply the number of cars (3) by the number of tires each car has (4). Step 4: 3 cars x 4 tires = 12 tires. Step 5: There are 12 tires in total.</pre><p>This step-by-step reasoning helps the model stay grounded and accurate — especially for multi-step tasks where it’s easy to get lost or guess.</p><p>You can use CoT prompting for:</p><ul><li>Word problems</li><li>Logical deductions</li><li>“Why” questions</li><li>Multi-hop Q&amp;A</li></ul><h3>Building with Prompts: What We Explored</h3><p>As we’ve seen, prompt engineering isn’t just about asking questions — it’s about shaping <strong>how</strong> the model thinks, responds, and reasons.</p><p>In this blog, we explored:</p><ul><li><strong>Role-Based Prompting</strong> to set tone and personality</li><li><strong>Few-Shot Prompting</strong> to teach tasks by example</li><li><strong>Chain-of-Thought Prompting</strong> to encourage logical step-by-step reasoning</li></ul><p>Each of these techniques unlocks new levels of control and creativity when working with large language models — no retraining required.</p><h3>Want to Tune Creativity and Control?</h3><p>This post focused on <em>prompting styles</em>, but if you’re curious about how to influence the model’s <strong>creativity</strong>, <strong>diversity</strong>, or <strong>length of response</strong> using generation parameters like temperature, top-k, top-p, and max_length — check out my earlier blog:</p><p>👉 <a href="https://medium.com/@mlops_playbook/gpt-2-text-generation-mastering-the-art-of-ai-creativity-eaefe76fd8e0"><strong>Text Generation Experiments with GPT-2: Temperature, Top-k, Top-p &amp; More</strong></a></p><p>It includes code and side-by-side examples showing how small changes in these settings can dramatically shift the output.</p><h3>Final Thoughts</h3><p>Prompt engineering turns you from a passive user into an active <strong>co-creator</strong> with your LLM. Whether you’re building chatbots, smart assistants, or reasoning engines, the ability to shape model behavior through prompts is a superpower worth mastering.</p><p>Want to take it further? Try combining these techniques — like <strong>few-shot + chain-of-thought</strong>, or <strong>role-based + multilingual</strong> prompts — and watch the magic unfold.</p><p>If you found this helpful, feel free to connect or share your own prompting experiments in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ac56712c1ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GPT-2 Text Generation: Mastering the Art of AI Creativity]]></title>
            <link>https://medium.com/@mlops_playbook/gpt-2-text-generation-mastering-the-art-of-ai-creativity-eaefe76fd8e0?source=rss-56e23ccf746c------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaefe76fd8e0</guid>
            <category><![CDATA[prompt]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[gpt-2]]></category>
            <dc:creator><![CDATA[MLOps Playbook]]></dc:creator>
            <pubDate>Thu, 10 Jul 2025 09:35:19 GMT</pubDate>
            <atom:updated>2025-07-10T09:45:18.769Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Exploring how temperature, top-k, top-p, and max_length parameters shape AI-generated text</em></h4><p><em>Artificial Intelligence will transform education by…” </em>What happens next? Well, it depends — quite literally — on how you ask a language model to complete that sentence. In this blog, I’ll walk you through a hands-on experiment with <strong>GPT-2</strong> using <strong>Hugging Face Transformers</strong>, where I explore how sampling parameters shape text generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ytpiPFSiw9FzLgC7J4JNQg.png" /></figure><h3>What I Did</h3><p>I started with the pre-trained GPT-2 model from Hugging Face and wrote a Python script to:</p><ul><li>Load the model using a Hugging Face token</li><li>Generate completions for a fixed prompt</li><li>Vary generation parameters and observe the changes</li></ul><p>Here’s the prompt I used throughout:</p><pre>prompt = &quot;AI will transform education by&quot;</pre><h3>Setup: Loading the Model</h3><p>Before diving into sampling, I authenticated using my Hugging Face token stored in a .env file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QKJivQ0XWksRgSq0_rMRAg.png" /><figcaption><a href="https://huggingface.co/openai-community/gpt2">https://huggingface.co/openai-community/gpt2</a></figcaption></figure><pre>from dotenv import load_dotenv<br>from huggingface_hub import login<br>load_dotenv(&quot;/path-to-file/.env&quot;)<br>hf_token = os.getenv(&quot;HUGGINGFACE_TOKEN&quot;)<br>login(token=hf_token)</pre><p>Then I loaded the GPT-2 tokenizer and model:</p><blockquote><strong>GPT-2 Tokenizer</strong> breaks input text into tokens (subwords) that the model can understand.<br> <strong>GPT-2 Model</strong> is a pre-trained transformer that generates human-like text based on those tokens<em>.</em></blockquote><pre>from transformers import GPT2Tokenizer, GPT2LMHeadModel<br><br>tokenizer = GPT2Tokenizer.from_pretrained(&quot;gpt2&quot;, use_auth_token=hf_token)<br>model = GPT2LMHeadModel.from_pretrained(&quot;gpt2&quot;, use_auth_token=hf_token)<br>model.eval()<br><br>tokenizer.pad_token = tokenizer.eos_token<br>model.config.pad_token_id = model.config.eos_token_id</pre><h3>The Generation Function</h3><p>I wrote a utility function that allows for flexible experimentation:</p><pre>def generate_gpt2(prompt, max_length=50, top_k=50, top_p=0.95, temperature=1.0):<br>    inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;, padding=True)<br>    output = model.generate(<br>        input_ids=inputs[&quot;input_ids&quot;],<br>        attention_mask=inputs[&quot;attention_mask&quot;],<br>        max_length=max_length,<br>        do_sample=True,<br>        top_k=top_k,<br>        top_p=top_p,<br>        temperature=temperature,<br>        pad_token_id=tokenizer.pad_token_id<br>    )<br>    return tokenizer.decode(output[0], skip_special_tokens=True)</pre><h3>Experimentation</h3><h4>1. 🔥 Temperature: The Creativity Knob</h4><p>Temperature controls how “creative” or random the model is. Low values make it more predictable, high values make it more surprising.</p><pre>for temp in [0.1, 1]:<br>    print(generate_gpt2(prompt, temperature=temp))</pre><p>Output:</p><pre>🔺 temperature = 0.1<br>AI will transform education by providing a new way to teach children about the importance of learning and the importance of learning.<br>The new curriculum will be based on the principles of the International School for Education (ISE) and will be based on the<br><br>🔺 temperature = 1<br>AI will transform education by providing a new and exciting way of training the students for high-performance, fast, and fun events, with multiple levels of participation,&quot; they write.<br>The company already sells training modules for students on social media and is</pre><blockquote>At <strong>temperature = 0.1</strong>, the model becomes very <strong>conservative</strong> and <strong>repetitive</strong>.This setting tends to generate <strong>boring but safe</strong> completions.<br> At <strong>temperature = 1.0</strong>, the model is much more <strong>creative and diverse</strong> in its word choices.This setting encourages <strong>risk-taking.</strong></blockquote><h4>2. 🎯 Top-k Sampling: Limiting the Vocabulary</h4><p><strong>Top-k sampling</strong> keeps only the top k highest probability words and randomly selects the next word from them.<br> This helps control randomness — lower k makes it more focused, higher k makes it more diverse.</p><pre>for k in [10, 500]:<br>    print(generate_gpt2(prompt, top_k=k))</pre><p>Output:</p><pre>top_k = 10<br>AI will transform education by providing a high-quality training environment for educators, educators and parents. We have developed an effective training environment where all students are encouraged to apply their skills and learn from experience and be part of a diverse group of teachers and students<br>top_k = 500<br>AI will transform education by looking to unique systems and approaches to curriculum design to help grow your school. Students will be guided by events that focus on how to build a place where you can live, work, play, and study. We believe that students</pre><blockquote>With only the <strong>top 10 most likely words</strong> to choose from at each step, the model plays it safe. The text is formal, structured, and repeats.This setting favors <strong>accuracy and clarity.</strong><br> With <strong>top 500 options</strong>, the model has a wide range of words to pick from. The result is more <strong>creative and varied. I</strong>t can also become <strong>less focused</strong> and may drift slightly from the original topic.</blockquote><h4>3. 🌊 Top-p(Nucleus Sampling): Dynamic Vocabulary Selection</h4><p>Top-p dynamically selects tokens based on cumulative probability — it considers tokens until their combined probability reaches the p threshold. It adaptively chooses from high-confidence options while allowing creativity — lower <em>p</em> keeps it focused, higher <em>p</em> increases diversity.</p><pre>for p in [0.7, 1.0]:<br>    print(generate_gpt2(prompt, top_p=p))</pre><p>Output:</p><pre>top_p = 0.7<br>AI will transform education by enabling students to focus on their education, and create a more balanced, diverse, and inclusive society.<br>The initiative will begin with a grant of $2.5 million, with the goal of raising $2 million more<br><br>top_p = 1.0<br>AI will transform education by investing in science and engineering with a diverse and holistic mix of programs, projects and partnerships,&quot; a spokesman said Tuesday. &quot;The research, development and deployment strategy of the U.S.-based company aims to ensure that the world</pre><blockquote>With <em>top_p = 0.7</em>, GPT-2 is restricted to a <strong>tight set of high-probability words</strong>, resulting in clear, concise, and socially responsible language.<br> At <em>top_p = 1.0</em>, the model is allowed to pick from <strong>all possible next words</strong>, leading to <strong>richer vocabulary</strong> and more <strong>open-ended ideas</strong>.</blockquote><h4>4. 📏 Max Length: Controlling Output Size</h4><p>Max Length sets the maximum number of tokens (words or word pieces) the model can generate in response.</p><pre>for max_len in [30, 100]:<br>    print(generate_gpt2(prompt, max_length=max_len))</pre><p>Output:</p><pre>max_length = 30<br>AI will transform education by offering students the tools they need to become leaders in their fields of specialization.<br>For more information or a chance to attend<br><br>max_length = 100<br>AI will transform education by making it possible for students to improve their education so that they can go back to school more quickly and provide the best outcomes possible. In 2015, according to a Pew survey, there were more than 70 million adults in India, or 14 percent of the population. This represents an incredible increase in educational opportunity in these countries.<br>I am now a parent in Kolkata, having completed my Bachelor of Science degree and a Master of Science in Education (MIT) in the</pre><blockquote>With a maximum length = 30, the output stays <strong>on-topic, concise, and clean</strong>. But it <strong>cuts off abruptly.</strong> Good for quick, focused outputs.<br> With a maximum length = 100, More detailed and varied, but starts drifting off-topic and ends abruptly. Better for exploratory or narrative-style text.</blockquote><h3>Crafting the Right Output is an Art</h3><p>As we’ve seen through these experiments, text generation with GPT-2 is far from a one-size-fits-all process. Each parameter — whether it’s <strong>temperature</strong>, <strong>top-k</strong>, <strong>top-p</strong>, or <strong>max_length</strong> — acts like a dial you can tune to strike the right balance between <strong>creativity</strong> and <strong>control</strong>.</p><ul><li>Want something safe and deterministic? Try low temperature and top-k.</li><li>Craving variety and spontaneity? Turn up the temperature or use a higher top-p.</li><li>Need tight, focused answers? Limit the max length.</li><li>Exploring narrative-style generation? Let it run longer.</li></ul><p>Ultimately, understanding and experimenting with these sampling parameters is key to <strong>mastering the art of AI creativity</strong>. Whether you’re a developer, researcher, or hobbyist, learning how to <em>ask</em> the model is just as important as understanding what it can <em>answer</em>.</p><p>Feel free to use my code and try your own variations. The possibilities are endless — just like the completions GPT-2 can generate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaefe76fd8e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformers, BERT & GPT: The AI Revolution That Changed NLP Forever]]></title>
            <link>https://medium.com/@mlops_playbook/transformers-bert-gpt-the-ai-revolution-that-changed-nlp-forever-e98e17394001?source=rss-56e23ccf746c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e98e17394001</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[transformer-architecture]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[MLOps Playbook]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 13:13:52 GMT</pubDate>
            <atom:updated>2025-07-10T09:39:50.309Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Day AI Learned to Read and Write Like Humans</h4><p>Imagine teaching a machine not just to read word by word but to <strong>grasp full meaning instantly</strong> — just like we do.</p><p>That’s exactly what the <strong>Transformer</strong> architecture did when it was introduced in 2017. Since then, models like BERT and GPT have transformed everything from search engines to chatbots.</p><p>But here’s the real question: How do these models actually work?</p><p>And more importantly — how can Y<strong>OU use them?</strong></p><p>Let’s dive in — code included, visuals included, and <strong>attention paid</strong>.</p><h3>Meet the Transformers: The Neural Network That Sees Everything</h3><p>Before Transformers, language models worked like this:</p><ul><li><strong>RNNs</strong> = read one word at a time (slow + forgetful)</li><li><strong>CNNs</strong> = scan text like images (misses long-range meaning)</li></ul><p>Then came the Transformer:</p><blockquote><em>A model that processes </em><strong><em>all words simultaneously</em></strong><em>, using </em><strong><em>self-attention</em></strong><em> to figure out which words matter most.</em></blockquote><h3>Transformer Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pnf8XFfm4wxYwXwDdIE59Q.png" /></figure><h3><strong>Key building blocks:</strong></h3><h4>1. Input Embedding + Positional Encoding</h4><ul><li><strong>Input Embedding</strong>: Each token is converted into a dense vector using an embedding layer.<br> E.g., token → embedding vector (e.g., 768-dim)</li><li><strong>Positional Encoding</strong>: Since Transformers don’t process tokens in order by default, it adds <strong>position-specific patterns</strong> (sine/cosine functions) to retain the order of tokens.</li></ul><blockquote>Input to Encoder=Embedding+Positional Encoding</blockquote><h4>2. Encoder Block (Left Side) — Repeated N Times</h4><p>Each encoder layer has <strong>3 core components</strong>:</p><h4><strong>i) Multi-Head Self-Attention</strong></h4><p>Each token in the input sequence is transformed into three vectors:</p><ul><li><strong>Query (Q)</strong> — What am I looking for?</li><li><strong>Key (K)</strong> — What do I contain?</li><li><strong>Value (V)</strong> — What information do I carry?</li></ul><p>These are computed using learnable linear layers:</p><pre>Q = X · Wᵠ<br>K = X · Wᵏ<br>V = X · Wᵛ<br>#Where X is the input sequence and W matrices are learned weights.</pre><p><strong>Scaled Dot-Product Attention</strong></p><p>This computes how much focus each token should place on every other token:</p><pre>Attention(Q, K, V) = softmax((Q · Kᵀ) / √dk) · V<br><br>#Q · Kᵀ gives similarity between words<br>#softmax turns similarity scores into probabilities<br>#Result is used to weight V vectors and get the attended output</pre><p><strong>Multi-Head Attention</strong></p><p>Instead of doing this once, we do it multiple times in parallel:</p><pre>MultiHead(Q, K, V) = Concat(head1, ..., headh) · Wo</pre><p>Each head captures different aspects (e.g., grammar, position, meaning) from the sequence.</p><h4>ii) Add &amp; Layer Norm</h4><p>We add the original input (residual connection) and normalize:</p><pre>Output = LayerNorm(X + SelfAttention(X))</pre><p>This helps stabilize training and speeds up convergence.</p><p><strong>iii) Feed Forward Network</strong></p><p>Each token passes independently through a small MLP:</p><pre>FFN(x) = max(0, x · W1 + b1) · W2 + b2</pre><p>This increases representational power. The same weights are used for all positions.</p><p>🔁 This entire encoder block is <strong>repeated N times</strong> (usually 6 or 12 layers).</p><h4>3. Decoder Block (Right Side) — Repeated N Times</h4><p>The decoder is similar but has <strong>one extra attention layer</strong>. Each block contains:</p><p><strong>i) Masked Multi-Head Self-Attention</strong></p><p>Same as encoder self-attention, but with a twist — a <strong>look-ahead mask</strong> blocks future tokens during training:</p><pre>MaskedAttention(Q, K, V) = softmax((Q · Kᵀ + mask) / √dk) · V</pre><p>This ensures the model generates tokens one-by-one, not all at once.</p><p><strong>ii) Multi-Head Attention (Encoder-Decoder Attention)</strong></p><p>The decoder also attends to the encoder’s outputs:</p><pre>Attention(Qdec, Kenc, Venc)<br><br>#Q from decoder<br>#K and V from encoder outputs</pre><p>🔁 This decoder block is also <strong>repeated N times</strong>.</p><h4>4. Output Layer</h4><p>After all decoder layers, the output is transformed and fed into softmax:</p><pre>Logits = DecoderOutput · Wᵗ<br>P(next token) = softmax(Logits)</pre><p>The model picks the token with the highest probability — and repeats this for every step in the output sequence.</p><blockquote>This is the complete Transformer architecture — a powerful sequence model built entirely on attention. With this foundation, models like BERT and GPT revolutionized NLP by leveraging just the encoder or decoder parts respectively.</blockquote><p>Next, let’s dive into how <strong>BERT</strong> utilizes the <strong>encoder</strong> for deep language understanding.</p><p><strong>BERT (Bidirectional Encoder Representations from Transformers)</strong> reads text <strong>both left-to-right and right-to-left</strong> — capturing deep context through attention across all words in a sequence.</p><h3>Embedding Long Documents with BERT</h3><p>Since BERT can only process up to <strong>512 tokens at a time</strong>, long documents must be split into manageable pieces before generating embeddings.</p><p>This code handles long documents by:</p><ol><li><strong>Tokenizing the full text</strong>, without adding special tokens.</li><li><strong>Splitting</strong> it into chunks of 510 tokens (reserving space for [CLS] and [SEP]).</li><li><strong>Wrapping each chunk</strong> with [CLS] at the start (which helps BERT summarize the entire chunk) and [SEP] tokens at the end to explicitly mark the boundary of the segment..</li><li><strong>Passing each chunk through BERT</strong> to extract the embedding corresponding to the [CLS] token — which represents the chunk.</li><li><strong>Averaging</strong> all chunk-level [CLS] embeddings to form a single <strong>document-level embedding vector</strong>.</li></ol><p>This gives a fixed-size vector representation of the entire document, regardless of its original length.</p><p>Python Code: Averaging Chunk Embeddings</p><pre>from transformers import BertTokenizer, BertModel<br>import torch<br><br># Load pre-trained BERT tokenizer and model<br>tokenizer = BertTokenizer.from_pretrained(&quot;bert-base-uncased&quot;)<br>model = BertModel.from_pretrained(&quot;bert-base-uncased&quot;)<br>model.eval()  # Set model to evaluation mode<br><br># Use GPU if available, else CPU<br>device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br>model.to(device)<br><br># --- STEP 1: Helper function to split long input_ids into chunks ---<br>def chunk_ids(input_ids, chunk_size=512):<br>    &quot;&quot;&quot;<br>    Split input_ids into chunks of size &lt;= chunk_size.<br>    Reserve space for [CLS] and [SEP] tokens, so use chunk_size - 2.<br>    &quot;&quot;&quot;<br>    return [input_ids[i:i+chunk_size] for i in range(0, len(input_ids), chunk_size)]<br><br># --- STEP 2: Main embedding function ---<br>def embed_document_with_cls(text, chunk_size=512):<br>    &quot;&quot;&quot;<br>    Takes a long document and returns a single [1, 768] BERT embedding<br>    using CLS token from each chunk.<br>    &quot;&quot;&quot;<br><br>    # Tokenize full text into input IDs (exclude special tokens for now)<br>    input_ids = tokenizer.encode(text, add_special_tokens=False)<br>    <br>    # Split input_ids into manageable chunks<br>    chunks = chunk_ids(input_ids, chunk_size=chunk_size - 2)  # leave space for [CLS] and [SEP]<br>    <br>    all_embeddings = []<br><br>    for chunk in chunks:<br>        # Add [CLS] and [SEP] to each chunk<br>        chunk_with_special_tokens = [tokenizer.cls_token_id] + chunk + [tokenizer.sep_token_id]<br>        # Convert to tensor and move to device<br>        input_tensor = torch.tensor([chunk_with_special_tokens]).to(device)<br>        attention_mask = torch.ones_like(input_tensor).to(device)<br><br>        # Disable gradients (inference only)<br>        with torch.no_grad():<br>            outputs = model(input_ids=input_tensor, attention_mask=attention_mask)<br>            # Take the embedding of the [CLS] token (first token)<br>            cls_embedding = outputs.last_hidden_state[:, 0, :]  # shape: [1, 768]<br><br>        all_embeddings.append(cls_embedding)<br><br>    # Average all CLS embeddings from chunks to get final document embedding<br>    doc_embedding = torch.mean(torch.stack(all_embeddings), dim=0)  # shape: [1, 768]<br><br>    return doc_embedding.cpu()  # Move result back to CPU<br><br># --- STEP 3: Test with a sample document ---<br>doc = (&quot;long document goes here ....&quot;)<br><br># Get the document embedding<br>embedding = embed_document_with_cls(doc)<br><br># Print shape to confirm it&#39;s [1, 768]<br>print(&quot;Document embedding shape:&quot;, embedding.shape)</pre><blockquote>This <strong>embedding-based approach</strong> works well for tasks like <strong>document classification</strong>, <strong>semantic search</strong>, or <strong>similarity comparison</strong>, where understanding the overall meaning of a large text is crucial.</blockquote><h3>GPT: The AI That Writes Like a Human</h3><p>If <strong>BERT</strong> is a careful reader, <strong>GPT (Generative Pre-trained Transformer)</strong> is a creative writer.</p><p><strong>GPT</strong> generates text one word at a time by predicting the <strong>next token</strong> based <strong>only on past context</strong> — never peeking ahead. This makes it ideal for generating fluent, context-aware text like stories, code, or conversations.</p><h3>GPT’s Secret Weapon: Causal (Masked) Multi-Head Attention</h3><p>GPT relies on a specialized mechanism called <strong>masked multi-head self-attention</strong>:</p><ul><li>Each token can <strong>only attend to earlier tokens</strong> — never future ones.</li><li>This masking ensures that the model <strong>predicts one word at a time</strong>, just like a human writing linearly.</li><li><strong>Multiple attention heads</strong> run in parallel to capture different types of relationships — syntax, semantics, topic, etc.</li></ul><p>This is what makes GPT <strong>causal</strong> or <strong>autoregressive</strong>, and it’s fundamental to its <strong>left-to-right generation</strong> ability.</p><h3>Visualizing GPT-2’s Attention</h3><p>Let’s see how GPT-2 distributes its attention across previous tokens using the following code:</p><pre>import torch<br>from transformers import GPT2Tokenizer, GPT2LMHeadModel<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br># Load GPT2<br>tokenizer = GPT2Tokenizer.from_pretrained(&quot;gpt2&quot;)<br>model = GPT2LMHeadModel.from_pretrained(&quot;gpt2&quot;, output_attentions=True)<br>model.eval()<br>tokenizer.pad_token = tokenizer.eos_token<br>model.config.pad_token_id = tokenizer.eos_token_id<br><br>device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br>model.to(device)<br><br># --- Input prompt ---<br>prompt = &quot;The cat sat on the&quot;<br>inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;).to(device)<br><br># --- Run GPT2 and get attentions ---<br>with torch.no_grad():<br>    outputs = model(**inputs)<br>    attentions = outputs.attentions  # list of [batch, num_heads, seq_len, seq_len]<br><br># --- Visualize attention from the last layer ---<br>last_layer_attention = attentions[-1]  # shape: [1, heads, seq, seq]<br>avg_attention = last_layer_attention.mean(dim=1).squeeze(0)  # average across heads → [seq, seq]<br><br># --- Plot attention heatmap ---<br>tokens = tokenizer.convert_ids_to_tokens(inputs[&quot;input_ids&quot;].squeeze(0))<br><br>plt.figure(figsize=(8, 6))<br>sns.heatmap(avg_attention.cpu(), xticklabels=tokens, yticklabels=tokens, cmap=&quot;Blues&quot;, annot=True, fmt=&quot;.2f&quot;)<br>plt.title(&quot;GPT-2 Causal Attention (last layer)&quot;)<br>plt.xlabel(&quot;Key (attended to)&quot;)<br>plt.ylabel(&quot;Query (current token)&quot;)<br>plt.xticks(rotation=45)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vLnp0VptVPuHJBgd4gqIoA.png" /></figure><p>GPT only attends to past tokens (triangular pattern)</p><ul><li>Some words get stronger attention — those are key context cues</li></ul><h3>🧩 Why This Matters</h3><p>Understanding <strong>causal masked multi-head attention</strong> helps you see <strong>why GPT is good at generation</strong>:</p><ul><li><strong>BERT</strong> = bidirectional (good for understanding, classification).</li><li><strong>GPT</strong> = autoregressive (good for generation, conversation, code completion).</li></ul><p>Each token is generated based only on prior context, and the <strong>attention mask</strong> ensures that future information is <strong>strictly hidden</strong> — no cheating!</p><h3>Conclusion</h3><ul><li>Transformers replaced RNNs/CNNs with self-attention, enabling parallel processing.</li><li>BERT excels in understanding context bidirectionally (best for embeddings).</li><li>GPT specializes in generation via autoregressive decoding.</li></ul><p>By studying attention mechanisms and experimenting with code, we gain deeper insights into how these models work. Try fine-tuning BERT/GPT on custom datasets to see their power firsthand!</p><p>Further Reading:</p><ul><li><a href="https://arxiv.org/abs/1706.03762">Original Transformer Paper</a></li><li><a href="https://arxiv.org/abs/1810.04805">BERT Paper</a></li><li><a href="https://arxiv.org/abs/2005.14165">GPT-3 Paper</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e98e17394001" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>