<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged fine-tuning</title>
<link>https://coderlegion.com/tag/fine-tuning</link>
<description>Powered by Question2Answer</description>
<item>
<title>Count your agent's narrow calls before you move any of them to a small model</title>
<link>https://coderlegion.com/32842/count-your-agents-narrow-calls-before-you-move-any-of-them-to-a-small-model</link>
<description>&lt;p&gt;A team decides its agent costs too much. Someone reads that small models are the future of agent work, picks a 3B model, and points the whole agent at it. Ticket classification holds up. The open-ended replies fall apart within a day, and the team rolls everything back.&lt;/p&gt;
&lt;p&gt;The reason is structural. The team swapped the whole agent, while the savings live in individual calls.&lt;/p&gt;
&lt;p&gt;Some calls repeat with little variation. Others need broad reasoning. Until you know which is which, you cannot know what a small model can take.&lt;/p&gt;
&lt;h3 id=&quot;many-agent-calls-are-narrow-and-repetitive&quot;&gt;Many agent calls are narrow and repetitive&lt;/h3&gt;
&lt;p&gt;NVIDIA Research and Georgia Tech made this case in a 2025 position paper, Small Language Models are the Future of Agentic AI (arXiv 2506.02153). Many agent calls are narrow, specialized tasks. For those calls, the paper argues, small models are sufficient, better suited and more economical. It counts most models under about 10B parameters as small.&lt;/p&gt;
&lt;p&gt;The cost gap is large. The paper states that serving a 7B model is 10 to 30 times cheaper in latency, energy and FLOPs than a 70B to 175B model. In a multi-step chain, that saving applies at every step.&lt;/p&gt;
&lt;p&gt;Large models keep a role. The authors argue for heterogeneous agents. Small models take calls by default. A large model is called when general reasoning or open-domain dialogue matters.&lt;/p&gt;
&lt;h3 id=&quot;the-published-percentages-are-estimates-not-your-numbers&quot;&gt;The published percentages are estimates, not your numbers&lt;/h3&gt;
&lt;p&gt;The authors studied three open-source agents. They estimate that about 60% of MetaGPT's LLM queries could move to specialized small models. For Open Operator the estimate is about 40%. For Cradle it is about 70%.&lt;/p&gt;
&lt;p&gt;Those numbers come from a position paper. They are not benchmark results. They also vary widely across three agents, and that spread is the useful part. Your agent's share depends on what your agent does.&lt;/p&gt;
&lt;p&gt;So treat them as a reason to measure. Log a week of calls and count how many are narrow tasks that repeat with little variation.&lt;/p&gt;
&lt;h3 id=&quot;log-every-call-that-is-not-talking-to-a-person&quot;&gt;Log every call that is not talking to a person&lt;/h3&gt;
&lt;p&gt;The paper's conversion recipe starts with logging. Capture the prompt, the output, the tool-call contents and the latency of every call that is not a direct exchange with a person.&lt;/p&gt;
&lt;p&gt;The exchange with the user is usually the open-ended part. The calls behind it are where the repetition lives: classify the ticket, pull the order ID, pick the tool.&lt;/p&gt;
&lt;p&gt;Record these as OpenTelemetry spans. Wrap the agent, each tool and the overall chain, so every call shows up under its parent. You need that structure later, when a bad answer has to be traced back to one step.&lt;/p&gt;
&lt;h3 id=&quot;cluster-the-calls-into-jobs&quot;&gt;Cluster the calls into jobs&lt;/h3&gt;
&lt;p&gt;Once the logs fill up, group the calls into recurring tasks. Typical clusters are intent recognition, data extraction and document summarization.&lt;/p&gt;
&lt;p&gt;Count each cluster. Its size tells you how much traffic a small model could take over.&lt;br&gt;
Read a sample from each one. A cluster that looks narrow can still hide long or unusual inputs.&lt;br&gt;
Strip sensitive data first. Remove PII, PHI and other sensitive fields before any call becomes a training example.&lt;/p&gt;
&lt;p&gt;The paper's rule of thumb for fine-tuning is 10K to 100K examples per task. Check how close each cluster gets to that range before you plan a fine-tune for it.&lt;/p&gt;
&lt;h3 id=&quot;pick-and-train-one-small-model-per-job&quot;&gt;Pick and train one small model per job&lt;/h3&gt;
&lt;p&gt;For each cluster, pick candidate models. Weigh capability, license and deployment footprint. Then test them on your own eval set, because a public benchmark measures general skill and your agent step is narrow.&lt;/p&gt;
&lt;p&gt;Several current small models document tool calling on their model cards. They include Qwen3.5 (0.8B to 9B), Gemma 4 E2B and E4B, Ministral 3, Phi-4-mini and SmolLM3-3B. In that set, Qwen3.5-0.8B is the smallest with documented tool calling.&lt;/p&gt;
&lt;p&gt;Fine-tune with LoRA or QLoRA on a single GPU. Another option is distillation: train the small model to mimic the large model's outputs on the task data. Either way, build each dataset to look like production traffic, with the same length, noise and label distributions.&lt;/p&gt;
&lt;h3 id=&quot;score-every-swap-against-the-model-it-replaces&quot;&gt;Score every swap against the model it replaces&lt;/h3&gt;
&lt;p&gt;Before any traffic moves, run the small model and the model it replaces through the same evals. Use a metric that fits the job:&lt;/p&gt;
&lt;p&gt;Router. Routing accuracy on a held-out set.&lt;br&gt;
Extractor. Exact-match or structured-field accuracy.&lt;br&gt;
Reasoning step. Faithfulness against the supplied context.&lt;/p&gt;
&lt;p&gt;Then run end-to-end scenarios across the whole chain. Per-agent evals miss handoff bugs. One agent emits a malformed handoff token, the next silently drops the request, and the workflow returns a wrong but plausible answer. A full-chain test is what catches it.&lt;/p&gt;
&lt;h3 id=&quot;keep-a-fallback-and-retrain-one-piece-at-a-time&quot;&gt;Keep a fallback and retrain one piece at a time&lt;/h3&gt;
&lt;p&gt;Route the easy calls to the small model, and keep a frontier model as a fallback behind the same endpoint. Small models are less reliable on adversarial or out-of-distribution inputs, so low-confidence cases go to the stronger model.&lt;/p&gt;
&lt;p&gt;The last step of the recipe is iteration. Retrain on fresh data as usage shifts. When one agent regresses, retrain or revert that one component and leave the others alone. Each change stays small and easy to roll back.&lt;/p&gt;
&lt;h3 id=&quot;pitfalls-that-keep-showing-up&quot;&gt;Pitfalls that keep showing up&lt;/h3&gt;
&lt;p&gt;Swapping the whole agent at once. The open-ended calls fail and take the narrow wins down with them.&lt;br&gt;
Quoting someone else's percentage. The 40% and the 70% came from different agents. Yours needs its own count.&lt;br&gt;
Training on raw logs. Logs carry PII and PHI. Strip them before a call becomes a training example.&lt;br&gt;
Picking by leaderboard. The paper lists generalist benchmarks as one of the barriers to adoption. Your own eval set decides.&lt;br&gt;
Skipping end-to-end tests. Each agent can pass its own suite while a handoff between them drops requests.&lt;/p&gt;
&lt;p&gt;The model lineup, a LoRA sketch and the tracing setup are in this &lt;a rel=&quot;nofollow&quot; href=&quot;https://futureagi.com/blog/small-language-models-agentic-ai-2025/?utm_source=fagiCoderlegion&amp;amp;utm_medium=organic&amp;amp;utm_campaign=blogdistribution&quot;&gt;guide to small language models for agentic AI&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Count the calls first. A small model earns its place only on a job you have measured, scored and can roll back.&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/32842/count-your-agents-narrow-calls-before-you-move-any-of-them-to-a-small-model</guid>
<pubDate>Wed, 28 Oct 2026 13:46:09 +0000</pubDate>
</item>
<item>
<title>Fine-Tuning vs Prompt Engineering vs RAG: When to Use Each (And the Fourth Option Nobody Mentions)</title>
<link>https://coderlegion.com/24338/fine-tuning-prompt-engineering-vs-rag-when-use-each-and-the-fourth-option-nobody-mentions</link>
<description>&lt;p&gt;You have an AI model that hallucinates with your company's data. You open a support ticket and ask the chatbot about your returns policy. The chatbot, powered by GPT-4 or Gemini 2.5, responds with a fabricated policy that sounds perfectly plausible but has nothing to do with your company's reality. Your boss stares at you. Your customer complains. You open Google and search &lt;strong&gt;&quot;how to connect LLM to my data&quot;&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The top 10 results offer three contradictory answers: &quot;use RAG,&quot; &quot;do fine-tuning,&quot; &quot;improve your prompt.&quot; All three are right. All three are wrong. Because the correct answer isn't any of the three in the abstract — it's &lt;strong&gt;the one that fits your specific use case&lt;/strong&gt;. And there's a fourth option that almost nobody mentions, and which, in my experience, is the right call in more cases than the industry admits.&lt;/p&gt;
&lt;p&gt;This article is the decision tree I wish I'd had when I started building the AI systems behind this blog. I've distilled it after implementing all four techniques in real production: Prompt Engineering across the entire &lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/ai_agents_part1/&quot;&gt;Autopilot series&lt;/a&gt;, RAG in the &lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/ai_agents_part8/&quot;&gt;Ops Copilot&lt;/a&gt; with Algolia, pure Tool Calling in the &lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/obs_part5_radar_agent/&quot;&gt;Obsolescence Radar&lt;/a&gt;, and experimental fine-tuning in industrial classification pipelines. It closes the trilogy that began with &lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/rag_antipatterns/&quot;&gt;RAG: 7 Anti-Patterns&lt;/a&gt; and continued with &lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/mcp_protocol/&quot;&gt;MCP Protocol&lt;/a&gt;.&lt;/p&gt;
&lt;h4 id=&quot;the-question-nobody-asks&quot;&gt;The Question Nobody Asks&lt;/h4&gt;
&lt;p&gt;Before choosing a technique, ask yourself this: &lt;strong&gt;Does the knowledge your LLM needs change, or is it static?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If the answer is &quot;it changes frequently&quot; (product documentation, inventory, prices, regulations), you need a technique that accesses data &lt;strong&gt;in real time&lt;/strong&gt; without retraining the model. If the answer is &quot;it's static or changes very slowly&quot; (brand tone, formatting rules, domain nomenclature), you can consider techniques that &lt;strong&gt;incorporate that knowledge into the model&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;This distinction is the first node of the decision tree. It seems obvious written this way. Yet most teams I've seen jump straight to whatever technique is trending (RAG in 2024, fine-tuning in 2023, prompt engineering always) without asking this fundamental question.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://datalaria.com/es/posts/finetuning_vs_rag/decision_tree.jpg&quot; alt=&quot;Decision tree: how to choose between the 4 techniques&quot;&gt;&lt;/p&gt;
&lt;h4 id=&quot;option-1-prompt-engineering-80-of-cases&quot;&gt;Option 1: Prompt Engineering — 80% of Cases&lt;/h4&gt;
&lt;p&gt;The uncomfortable truth the AI tooling industry doesn't want you to know: &lt;strong&gt;for 80% of use cases, a well-designed prompt is sufficient&lt;/strong&gt;. You don't need RAG. You don't need fine-tuning. You need a system prompt that clearly defines the role, context, constraints, and expected output format.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;When it's sufficient&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The required knowledge fits in the model's context window (Gemini 2.5 handles up to 1 million tokens; Claude up to 200K).&lt;/li&gt;
&lt;li&gt;The task is generic but needs structure (drafting emails, summarizing documents, classifying text, generating code).&lt;/li&gt;
&lt;li&gt;You don't need updated proprietary data — the model's general knowledge is enough.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Advanced techniques that make the difference&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Structured system prompts&lt;/strong&gt;: Define the role (&quot;You are a senior supply chain engineer&quot;), constraints (&quot;Always respond in technical English&quot;), and output format (&quot;Return a JSON with fields: analysis, recommendation, confidence&quot;).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Few-shot prompting&lt;/strong&gt;: Include 3-5 correct input-output examples in the prompt. In the &lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/ai_agents_part3/&quot;&gt;Autopilot series&lt;/a&gt;, CrewAI agents use few-shot to maintain style consistency across generated articles.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Chain-of-thought (CoT)&lt;/strong&gt;: Instruct the model to &quot;think step by step&quot; before giving the final answer. Dramatically improves accuracy in reasoning, calculation, and multi-step analysis tasks.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Prompt chaining&lt;/strong&gt;: Break complex tasks into sequential subtasks, each with its own optimized prompt. This is exactly what CrewAI does with its agent architecture: each agent has a specialized prompt for its role.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Cost&lt;/strong&gt;: Virtually zero (only API token cost). A well-designed prompt can take hours of iteration, but operational cost is minimal.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Fatal limitation&lt;/strong&gt;: The context window has a limit. If you need the model to &quot;know&quot; about 10,000 documents from your knowledge base, you can't inject them all into the prompt. This is where RAG enters.&lt;/p&gt;
&lt;h4 id=&quot;option-2-rag-updatable-proprietary-knowledge&quot;&gt;Option 2: RAG — Updatable Proprietary Knowledge&lt;/h4&gt;
&lt;p&gt;&lt;strong&gt;RAG (Retrieval-Augmented Generation)&lt;/strong&gt; is the right answer when you need the LLM to respond about &lt;strong&gt;your proprietary knowledge&lt;/strong&gt; and that knowledge &lt;strong&gt;updates frequently&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;When it's necessary&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Product documentation, technical manuals, internal knowledge bases that update weekly or monthly.&lt;/li&gt;
&lt;li&gt;The user can ask unpredictable questions about a broad document corpus (you don't know in advance which fragment the LLM will need).&lt;/li&gt;
&lt;li&gt;You need &lt;strong&gt;citability&lt;/strong&gt;: the answer must include the sources it draws from (critical for compliance, as we documented in the &lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/eu_ai_act/&quot;&gt;EU AI Act&lt;/a&gt;, Article 13 on transparency).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;When NOT to use it&lt;/strong&gt;: When data is structured (SQL tables, APIs with defined schemas) or when you need numerical precision. As I extensively documented in &lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/rag_antipatterns/&quot;&gt;Anti-Pattern 7 of the RAG article&lt;/a&gt;, RAG over structured data generates narrative hallucinations where you need exact figures.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Correct architecture (summarized)&lt;/strong&gt;:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Semantic chunking&lt;/strong&gt; (not fixed-length — Anti-Pattern 1)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Evaluated embeddings&lt;/strong&gt; with your domain benchmark (Anti-Pattern 2)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Reranking&lt;/strong&gt; between retriever and LLM (Anti-Pattern 3)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Generous context&lt;/strong&gt; (top-10/15, not top-3 — Anti-Pattern 4)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Evaluation with RAGAS/DeepEval&lt;/strong&gt; before production (Anti-Pattern 6)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Real cost&lt;/strong&gt;: Moderate. The vector store (Pinecone, Weaviate, Algolia) has a monthly cost (€0-100 depending on volume), plus embedding cost (low) and generation cost (API tokens). In the &lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/ai_agents_part8/&quot;&gt;Ops Copilot&lt;/a&gt;, the total RAG cost with Algolia was under &lt;strong&gt;€3/month&lt;/strong&gt; for the blog's ~70 posts.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Real case at Datalaria&lt;/strong&gt;: The Ops Engineering Copilot (&lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/ai_agents_part8/&quot;&gt;Autopilot Part 8&lt;/a&gt;) uses RAG with Algolia Agent Studio to answer questions about blog content. Posts are indexed as semantic records (one record per section), and the copilot retrieves relevant fragments before generating the response. Works well for semantic search over free text.&lt;/p&gt;
&lt;h4 id=&quot;option-3-fine-tuning-the-scalpel-not-the-hammer&quot;&gt;Option 3: Fine-Tuning — The Scalpel, Not the Hammer&lt;/h4&gt;
&lt;p&gt;&lt;strong&gt;Fine-tuning&lt;/strong&gt; is the most powerful technique and the most misused. It involves &lt;strong&gt;partially retraining&lt;/strong&gt; a base model (Gemini, Llama, Mistral) with your own data so the model internalizes specific knowledge, style, or behavior.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;When it's essential&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;You need the model to adopt a &lt;strong&gt;very specific tone or style&lt;/strong&gt; consistently (a brand with strict voice &amp;amp; tone, a domain with very particular technical jargon).&lt;/li&gt;
&lt;li&gt;The task is &lt;strong&gt;highly specialized&lt;/strong&gt; and generalist models don't solve it well even with advanced prompting (industrial defect classification, proprietary nomenclature entity extraction, specialized medical diagnosis).&lt;/li&gt;
&lt;li&gt;You need to &lt;strong&gt;reduce latency and cost&lt;/strong&gt; in production: a fine-tuned smaller model (7B-13B parameters) can match the quality of a large model (70B+) on your specific task, at a fraction of the cost and latency.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;When NOT to use it&lt;/strong&gt; (the most widespread myth):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Don't use fine-tuning to &quot;teach the model data.&quot;&lt;/strong&gt; Fine-tuning is not a database. If you need the model to know your product catalog, use RAG. Fine-tuning &quot;burns in&quot; behavioral patterns, not updatable facts.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Don't use fine-tuning if your knowledge changes frequently.&lt;/strong&gt; Each update requires retraining, which can cost hours and hundreds of euros. RAG is instant: update the document and the retriever finds it immediately.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Modern tools&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;LoRA (Low-Rank Adaptation)&lt;/strong&gt;: The standard technique. Instead of retraining the model's billions of parameters, LoRA trains only low-rank matrices &quot;attached&quot; to the model's layers. Reduces training cost by 90%+ and stores the fine-tuned model as a few MB of &quot;adapters.&quot;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;QLoRA&lt;/strong&gt;: LoRA applied to a 4-bit quantized model. Enables fine-tuning 70B-parameter models on a single consumer GPU (24GB VRAM). Democratized fine-tuning for startups and teams without GPU clusters.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Vertex AI Tuning / OpenAI Fine-Tuning API&lt;/strong&gt;: Managed services where you upload your training dataset (instruction-response pairs) and the platform runs the fine-tuning without you managing GPU infrastructure.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Real cost&lt;/strong&gt;: Variable. Fine-tuning with LoRA on a 7B-parameter model with 10,000 examples costs &lt;strong&gt;€5-20&lt;/strong&gt; on cloud (Google Cloud, AWS). A 70B model can cost &lt;strong&gt;€50-200&lt;/strong&gt; per training session. Plus the cost of preparing the dataset (hours of human work). As we analyzed in &lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/hidden_economics_ai/&quot;&gt;The Hidden Economics of AI&lt;/a&gt;, fine-tuning's hidden cost isn't compute — it's &lt;strong&gt;training dataset curation&lt;/strong&gt;.&lt;/p&gt;
&lt;h4 id=&quot;option-4-tool-calling-mcp-the-one-nobody-mentions&quot;&gt;Option 4: Tool Calling / MCP — The One Nobody Mentions&lt;/h4&gt;
&lt;p&gt;This is the option I discovered by elimination after RAG failed spectacularly on the &lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/obs_part5_radar_agent/&quot;&gt;Obsolescence Radar&lt;/a&gt;. &lt;strong&gt;Tool Calling&lt;/strong&gt; means the LLM doesn't try to &quot;know&quot; the answer; instead, it knows &lt;strong&gt;who to ask&lt;/strong&gt; — that is, which tool to execute to get the information with deterministic precision.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;When it's the right option&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Data is &lt;strong&gt;structured&lt;/strong&gt; (SQL databases, REST APIs, spreadsheets with schemas).&lt;/li&gt;
&lt;li&gt;You need &lt;strong&gt;absolute numerical precision&lt;/strong&gt; (financial calculations, inventory metrics, sensor data).&lt;/li&gt;
&lt;li&gt;The operation requires &lt;strong&gt;actions&lt;/strong&gt;, not just answers (create a ticket, send an email, run a query, call an external API).&lt;/li&gt;
&lt;li&gt;You want to &lt;strong&gt;standardize connections&lt;/strong&gt; between the LLM and tools to avoid vendor lock-in — exactly the problem solved by &lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/mcp_protocol/&quot;&gt;MCP (Model Context Protocol)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Architecture&lt;/strong&gt;: The LLM (Gemini 2.5, Claude) acts as a &lt;strong&gt;semantic orchestrator&lt;/strong&gt;: it understands the user's natural language intent, decides which tool(s) to execute, constructs the parameters, executes the tool(s), and interprets results for the user. Tools are deterministic Python functions (decorated with &lt;code&gt;@tool&lt;/code&gt; in CrewAI) that execute precision operations: SQL queries to Supabase, supplier API calls, linear programming calculations with PuLP.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Cost&lt;/strong&gt;: The lowest of all four options. You only pay for LLM tokens (typically few, since the prompt is short) and tool execution (SQL queries, API calls). In the Obsolescence Radar, the cost per complete execution (analyze a component, traverse the BOM graph, calculate financial impact, generate executive report) was under &lt;strong&gt;€0.02 per query&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Real case at Datalaria&lt;/strong&gt;: The &lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/obs_part5_radar_agent/&quot;&gt;Agentic Obsolescence Radar&lt;/a&gt; uses Tool Calling exclusively. The LLM (Gemini 2.5 via CrewAI) understands the obsolescence alert in natural language, but all data operations — SQL query to the component catalog, BOM graph traversal, P&amp;amp;L calculation, PDF generation — are executed by deterministic Python tools. Result: executive reports in 4 seconds with &lt;strong&gt;0% numerical hallucination&lt;/strong&gt;.&lt;/p&gt;
&lt;h4 id=&quot;the-decision-matrix&quot;&gt;The Decision Matrix&lt;/h4&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;&lt;th align=&quot;left&quot;&gt;Criterion &lt;/th&gt;&lt;th align=&quot;center&quot;&gt;Prompt Engineering &lt;/th&gt;&lt;th align=&quot;center&quot;&gt;RAG &lt;/th&gt;&lt;th align=&quot;center&quot;&gt;Fine-Tuning &lt;/th&gt;&lt;th align=&quot;center&quot;&gt;Tool Calling&lt;/th&gt;&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;&lt;td align=&quot;left&quot;&gt;&lt;strong&gt;Initial cost&lt;/strong&gt; &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐ Minimal &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐⭐ Low-medium &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐⭐⭐ High &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐⭐ Low&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td align=&quot;left&quot;&gt;&lt;strong&gt;Operational cost&lt;/strong&gt; &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐ Low &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐⭐ Medium &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐ Low (small model) &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐ Minimal&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td align=&quot;left&quot;&gt;&lt;strong&gt;Precision (free text)&lt;/strong&gt; &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐⭐ Medium &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐⭐⭐ High &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐⭐⭐ Very high &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐ N/A&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td align=&quot;left&quot;&gt;&lt;strong&gt;Precision (structured data)&lt;/strong&gt; &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐ Low &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐ Low &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐ Low &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐⭐⭐ Exact&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td align=&quot;left&quot;&gt;&lt;strong&gt;Data freshness&lt;/strong&gt; &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐⭐⭐ Instant &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐⭐⭐ Instant &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐ Requires retraining &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐⭐⭐ Real-time&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td align=&quot;left&quot;&gt;&lt;strong&gt;Implementation effort&lt;/strong&gt; &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐ Hours &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐⭐ Days-weeks &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐⭐⭐ Weeks-months &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐⭐ Days&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td align=&quot;left&quot;&gt;&lt;strong&gt;Maintenance&lt;/strong&gt; &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐ Minimal &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐⭐ Medium &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐⭐⭐ High (data drift) &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐⭐ Medium&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td align=&quot;left&quot;&gt;&lt;strong&gt;Traceability (EU AI Act)&lt;/strong&gt; &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐ Difficult &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐⭐⭐ High (citable sources) &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐ Opaque (black box) &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;⭐⭐⭐ Total (deterministic)&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td align=&quot;left&quot;&gt;&lt;strong&gt;Ideal use case&lt;/strong&gt; &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;Generic tasks with clear instructions &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;Updatable proprietary text knowledge &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;Specific style/tone, ultra-specialized tasks &lt;/td&gt;&lt;td align=&quot;center&quot;&gt;Structured data, numerical precision, actions&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h4 id=&quot;the-3-question-framework&quot;&gt;The 3-Question Framework&lt;/h4&gt;
&lt;p&gt;If the matrix seems dense, I've distilled a 3-question framework that resolves 90% of decisions:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Question 1: Does the data the LLM needs fit in the prompt?&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Yes → &lt;strong&gt;Prompt Engineering&lt;/strong&gt;. Inject context directly. Simpler, cheaper, faster.&lt;/li&gt;
&lt;li&gt;No → Next question.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Question 2: Is the data free text or structured?&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Free text (documentation, manuals, posts) → &lt;strong&gt;RAG&lt;/strong&gt;. Semantic retrieval is superior for searching unstructured text.&lt;/li&gt;
&lt;li&gt;Structured (SQL, APIs, tables, calculations) → &lt;strong&gt;Tool Calling&lt;/strong&gt;. Deterministic tools that execute exact queries.&lt;/li&gt;
&lt;li&gt;Both → &lt;strong&gt;Hybrid architecture&lt;/strong&gt; (RAG for textual context + Tool Calling for structured data, as we proposed in the &lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/rag_antipatterns/&quot;&gt;RAG article&lt;/a&gt;).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Question 3: Do you need a behavior or style the base model can't reproduce even with the best prompt?&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Yes (unique brand tone, ultra-specific domain jargon, task that generalist models consistently fail) → &lt;strong&gt;Fine-Tuning&lt;/strong&gt; on a base model.&lt;/li&gt;
&lt;li&gt;No → Go back to Prompt Engineering and refine your prompt before considering more complex techniques.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;what-i-learned-implementing-all-four&quot;&gt;What I Learned Implementing All Four&lt;/h4&gt;
&lt;p&gt;The most valuable lesson from operating these four techniques in production fits in a single sentence: &lt;strong&gt;always start with the simplest technique that could work&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The temptation is to jump straight to RAG or fine-tuning because they're more &quot;sophisticated.&quot; But sophistication doesn't correlate with effectiveness. In the &lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/ai_agents_part1/&quot;&gt;Autopilot&lt;/a&gt;, the majority of output quality comes from Prompt Engineering — carefully designed system prompts, few-shot examples, and Chain-of-thought. RAG added marginal value in the Ops Copilot for blog search. Fine-tuning wasn't necessary in any case. And Tool Calling was the transformative technique in the Obsolescence Radar, where RAG had failed.&lt;/p&gt;
&lt;p&gt;The evaluation order should always be:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Prompt Engineering&lt;/strong&gt; (hours, ~€0)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Tool Calling&lt;/strong&gt; if data is structured (days, ~€0)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;RAG&lt;/strong&gt; if you need access to proprietary text (days-weeks, ~€3-50/month)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Fine-Tuning&lt;/strong&gt; only if the previous three consistently fail (weeks, €50-500+)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;And in the era of the &lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/eu_ai_act/&quot;&gt;EU AI Act&lt;/a&gt;, there's a fifth consideration that isn't technical but legal: &lt;strong&gt;traceability&lt;/strong&gt;. Article 10 of the regulation requires that training data for high-risk systems be &quot;relevant, representative, and to the extent possible, free of errors and complete.&quot; This applies directly to fine-tuning: if you fine-tune a model with biased or incorrect data, and that model makes decisions in a regulated domain, you're exposed to sanctions. RAG and Tool Calling, being transparent in their sources, offer traceability that fine-tuning cannot match.&lt;/p&gt;
&lt;p&gt;As we wrote in &lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/hidden_economics_ai/&quot;&gt;The Hidden Economics of AI&lt;/a&gt;, the 10x Rule applies: if a more complex technique doesn't give you a result &lt;strong&gt;10 times better&lt;/strong&gt; than the previous one, it probably doesn't justify its added cost and complexity. Start simple. Measure. Scale only when the data demands it.&lt;/p&gt;
&lt;hr&gt;
&lt;h5 id=&quot;sources-of-interest-&quot;&gt;Sources of Interest:&lt;/h5&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://cloud.google.com/vertex-ai/docs/generative-ai/models/tune-models&quot;&gt;&lt;strong&gt;Google Cloud&lt;/strong&gt;: Tuning &amp;amp; Fine-tuning with Vertex AI&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://huggingface.co/docs/peft/conceptual_guides/lora&quot;&gt;&lt;strong&gt;Hugging Face&lt;/strong&gt;: LoRA — Low-Rank Adaptation of Large Language Models&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://www.pinecone.io/learn/rag-vs-fine-tuning/&quot;&gt;&lt;strong&gt;Pinecone&lt;/strong&gt;: RAG vs Fine-Tuning — How to Choose&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.anthropic.com/en/docs/build-with-claude/prompt-engineering&quot;&gt;&lt;strong&gt;Anthropic&lt;/strong&gt;: Prompt Engineering Guide&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/rag_antipatterns/&quot;&gt;&lt;strong&gt;Datalaria&lt;/strong&gt;: RAG in Production — 7 Anti-Patterns That Destroy Precision&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/mcp_protocol/&quot;&gt;&lt;strong&gt;Datalaria&lt;/strong&gt;: MCP Protocol — The USB of AI (Standardized Tool Calling)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/obs_part5_radar_agent/&quot;&gt;&lt;strong&gt;Datalaria&lt;/strong&gt;: The Agentic Radar — Tool Calling in Production&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/hidden_economics_ai/&quot;&gt;&lt;strong&gt;Datalaria&lt;/strong&gt;: The Hidden Economics of AI — Real Costs of Each Technique&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://datalaria.com/en/posts/eu_ai_act/&quot;&gt;&lt;strong&gt;Datalaria&lt;/strong&gt;: EU AI Act — Article 10 and Training Data&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description>
<category>Tutorials</category>
<guid isPermaLink="true">https://coderlegion.com/24338/fine-tuning-prompt-engineering-vs-rag-when-use-each-and-the-fourth-option-nobody-mentions</guid>
<pubDate>Sun, 09 Aug 2026 14:33:21 +0000</pubDate>
</item>
<item>
<title>Fine-Tune SLMs in Colab for Free : A 4-Bit Approach with Meta Llama 3.2</title>
<link>https://coderlegion.com/3080/fine-tune-slms-in-colab-for-free-a-4-bit-approach-with-meta-llama3-2</link>
<description>&lt;p&gt;&lt;img src=&quot;https://cdn-images-1.medium.com/max/2944/1*JZfV1Z94lDRuFaxZ0_BCQA.png&quot; alt=&quot;UnSloth Guides the Llama’s Fine-Tuning Ritual — a whimsical stylized llama illustration&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Fine-tuning large language models (LLMs) sounds complex — until you meet Unsloth.&lt;/strong&gt; Whether you’re a complete beginner or an experienced ML tinkerer, this guide walks you through the simplest and most efficient way to fine-tune LLaMA models on free GPUs using Google Colab. Best of all? No fancy hardware or deep ML theory required.&lt;/p&gt;
&lt;p&gt;This article breaks down every keyword, library, and function, defining each term precisely but in the simplest language possible.&lt;/p&gt;
&lt;p&gt;In this article, you’ll learn how to:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Install and configure &lt;a rel=&quot;nofollow&quot; href=&quot;https://unsloth.ai/&quot;&gt;Unsloth&lt;/a&gt; in Colab&lt;/li&gt;
&lt;li&gt;Load models in quantized (4-bit) mode to save memory&lt;/li&gt;
&lt;li&gt;Understand core concepts (parameters, weights, biases, quantization, etc.)&lt;/li&gt;
&lt;li&gt;Apply PEFT and LoRA adapters to fine-tune only a small part of the model&lt;/li&gt;
&lt;li&gt;Prepare Q\&amp;amp;A data for training with Hugging Face Datasets and chat templates&lt;/li&gt;
&lt;li&gt;Use SFTTrainer for supervised fine-tuning&lt;/li&gt;
&lt;li&gt;Switch to inference mode for faster generation&lt;/li&gt;
&lt;li&gt;Save and reload your fine-tuned model&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;getting-comfortable-with-some-core-concepts&quot;&gt;Getting Comfortable With some Core Concepts&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;https://cdn-images-1.medium.com/max/3072/0*kYVR3gVPzsXtHQOn&quot; alt=&quot;Llama’s Machine Learning Meditation — stylized llama in lotus pose&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Disclaimer:&lt;/strong&gt; I promise this will be the friendliest GenAI glossary — your cheat sheet, wittier than autocorrect and way less judgmental! &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Language Model —&lt;/strong&gt; &lt;em&gt;&lt;em&gt;Word-Predictor&lt;/em&gt; to put it simply! — like a smart autocomplete that predicts the next word based on what came before, much like your phone suggests “you” after “how are”. It learns these patterns by “reading” massive amounts of text, so it knows common word sequences and can fill in blanks. Behind the scenes, it models the probabilities of word sequences, assigning higher scores to more natural continuations.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Attention —&lt;/strong&gt; &lt;em&gt;Imagine you’re reading a sentence and want to know which earlier words matter most to understand each new word — that’s attention. Instead of reading a sentence strictly left-to-right, attention lets every word weigh how much it should consider all the others, like skimming a page and highlighting only key phrases. This selective focus makes predictions more accurate and efficient, ignoring irrelevant details.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Parameter —&lt;/strong&gt; &lt;em&gt;A number inside a model that can change during learning (like a dial that the model tweaks)&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Weight —&lt;/strong&gt; &lt;em&gt;Mostly synonymous with &lt;em&gt;parameters&lt;/em&gt; controlling how strongly one part of input affects the output&lt;/em&gt;&lt;/p&gt;
&lt;blockquote&gt;&lt;p&gt;&lt;strong&gt;Data vs Parameters vs Weights —&lt;/strong&gt; &lt;em&gt;“&lt;em&gt;Data&lt;/em&gt;” refers to the information used to train a model, while “&lt;em&gt;parameters&lt;/em&gt;” are the values the model learns from that data, and “&lt;em&gt;weights&lt;/em&gt;” are a specific type of parameter representing the strength of connections between model variables. To put it more simply, Data is the input, parameters are what the model adjusts to make predictions, and weights are a subset of those parameters.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;strong&gt;Bias —&lt;/strong&gt; &lt;em&gt;A small extra number added so the model can shift outputs up or down, like a baseline adjustment&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Transformer —&lt;/strong&gt; _A &lt;strong&gt;Transformer&lt;/strong&gt; is a special model built around attention, letting it “look” at every word in a sentence in parallel rather than one by one. It’s like a study group where everyone reads the entire essay at once and then discusses which sentences are most important to the main idea. Introduced in 2017 in Google’s “&lt;a rel=&quot;nofollow&quot; href=&quot;https://en.wikipedia.org/wiki/Attention_Is_All_You_Need&quot;&gt;Attention Is All You Need&lt;/a&gt;” paper, Transformers are the backbone of today’s LLMs and power everything from translation tools to chatbots._&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Quantization —&lt;/strong&gt; &lt;em&gt;Reducing precision of weights (e.g. 16-bit → 4-bit) to slash memory use, with minimal accuracy loss.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;PEFT —&lt;/strong&gt; &lt;em&gt;(&lt;a rel=&quot;nofollow&quot; href=&quot;https://arxiv.org/abs/2312.12148&quot;&gt;Parameter-Efficient Fine-Tuning&lt;/a&gt;) — updating only tiny adapter layers instead of the whole model.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;LoRA —&lt;/strong&gt; &lt;em&gt;(&lt;a rel=&quot;nofollow&quot; href=&quot;https://www.youtube.com/watch?v=DhRoTONcyZE&amp;amp;pp=0gcJCdgAo7VqN5tD&quot;&gt;Low-Rank Adaptation&lt;/a&gt;) — A smart shortcut for teaching a huge AI model new tricks by only tweaking a tiny part of it instead of retraining the entire thing. You “freeze” most of the model’s parameters and insert two small, trainable matrices into each layer. During fine-tuning, only these add-ons learn, drastically cutting down on time and compute cost.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;LoRA “r” —&lt;/strong&gt; &lt;em&gt;The adapter’s rank (size). Higher r gives more capacity but uses more memory.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;LoRA (alpha) —&lt;/strong&gt; &lt;em&gt;A scaling factor for adapter updates — like a “volume knob” for learning strength.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Dropout —&lt;/strong&gt; &lt;em&gt;Randomly turning off some adapter connections during training to prevent overfitting (can be set to 0).&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Gradient Checkpointing —&lt;/strong&gt; &lt;em&gt;Recomputes parts of the model during backpropagation to halve peak VRAM usage, at a slight speed cost.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;4-bit Mode —&lt;/strong&gt; &lt;em&gt;Quantized mode storing weights in 4 bits, cutting memory by \~4× compared to 16/32-bit.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Inference Mode —&lt;/strong&gt; &lt;em&gt;After training, use a special mode optimized for fast text generation (2× speed).&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Overfitting —&lt;/strong&gt; &lt;em&gt;When a model “memorizes” a tiny dataset and fails on new inputs — always test on unseen data.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Checkpoint —&lt;/strong&gt; &lt;em&gt;A saved snapshot of model weights you can reload later.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Token —&lt;/strong&gt; &lt;em&gt;A token is a small chunk of text (\~4–5 characters) — a word, part of a word, punctuation mark, or symbol — that serves as the basic unit a model processes.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Tokenizer —&lt;/strong&gt; &lt;em&gt;The tokenizer is the program that “cuts” raw text into those tokens and then converts each token into a unique number (ID) the model can work with (e.g., “unhappiness” → “un”, “happi”, “ness” → “un” = 137, “happi” = 428, etc).&lt;/em&gt;&lt;/p&gt;
&lt;h3 id=&quot;slms-vs-llms&quot;&gt;SLMs vs. LLMs&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;https://cdn-images-1.medium.com/max/3072/0*P3aTl3w0T8twLqCh&quot; alt=&quot;LMs Ultimate Showdown — stylized vs. large model illustration&quot;&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;SLMs (Small Language Models)&lt;/strong&gt; have fewer parameters and focus on specific tasks or domains — think of them as pocket calculators solving one type of math problem quickly and efficiently.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;LLMs (Large Language Models)&lt;/strong&gt; are like supercomputers trained on vast, diverse data; they can tackle many tasks — writing essays, summarizing articles, or coding — because they’ve “read” almost the entire internet.&lt;/li&gt;
&lt;li&gt;SLMs require less compute power and are ideal for on-device or specialized applications, whereas LLMs need massive cloud resources but offer broader versatility.&lt;/li&gt;
&lt;li&gt;In practice, you might use an SLM for customer-service chat on your phone, but call an LLM when you need deep research help or creative story generation.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;1-getting-started-colab-setup&quot;&gt;1. Getting Started: Colab Setup&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Why Google Colab &amp;amp; Tesla T4?&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Cost:&lt;/strong&gt; Free GPU access, that's all!&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Performance:&lt;/strong&gt; Tesla T4 handles mid-size LLMs effectively when paired with quantization and PEFT&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Accessibility:&lt;/strong&gt; No local GPU required — ideal for beginners&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Installing Unsloth&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;# Stable release from PyPI:
pip install unsloth

# OR

# Install the Nightly (latest GitHub) for cutting-edge features:
pip uninstall unsloth -y
pip install --upgrade --no-cache-dir --no-deps \
  git+https://github.com/unslothai/unsloth.git@nightly \
  git+https://github.com/unslothai/unsloth-zoo.git
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;pip install unsloth&lt;/code&gt;: grabs the vetted, stable version&lt;/li&gt;
&lt;li&gt;uninstall &amp;amp; install: fetches the newest commits from GitHub (may include experimental updates)&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;2-loading-a-model-efficiently&quot;&gt;2. Loading a Model Efficiently&lt;/h3&gt;
&lt;p&gt;We load the Llama 3.2 1B model using Unsloth in a memory-efficient &lt;strong&gt;4-bit quantization mode&lt;/strong&gt;, using roughly one-quarter the memory of full precision so it runs faster and fits on small GPUs. It also sets how long each input can be (up to 2048 tokens).&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;from unsloth import FastLanguageModel
import torch

# Configuration
max_seq_length = 2048      # How many tokens each input can have
dtype = None               # None for auto detection. Float16 for Tesla T4, V100; Bfloat16 for Ampere+
load_in_4bit = True        # Use 4-bit quantization to reduce memory usage
model_name = &quot;unsloth/Llama-3.2-1B-Instruct&quot;

# Load both model and tokenizer
model, tokenizer = FastLanguageModel.from_pretrained(
    model_name=model_name,
    max_seq_length=max_seq_length,
    dtype=dtype,
    load_in_4bit=load_in_4bit,
)
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;FastLanguageModel.from_pretrained&lt;/code&gt;: downloads and prepares the model + tokenizer&lt;/li&gt;
&lt;li&gt;&lt;code&gt;max_seq_length&lt;/code&gt;: sets the maximum context length&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src=&quot;https://cdn-images-1.medium.com/max/2302/1*riVpxab5gmWJpD-ONmEU6g.png&quot; alt=&quot;Diagram showing memory usage and model loading output&quot;&gt;&lt;/p&gt;
&lt;h3 id=&quot;3-introducing-peft-amp-lora&quot;&gt;3. Introducing PEFT &amp;amp; LoRA&lt;/h3&gt;
&lt;p&gt;Instead of updating all model weights (which can be billions), &lt;strong&gt;PEFT&lt;/strong&gt; adds small adapter layers you train. LoRA is one such method.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;model = FastLanguageModel.get_peft_model(
    model,
    r=16,          # Adapter rank (size). Suggested: 8, 16, 32, 64, 128
    target_modules=[
        &quot;q_proj&quot;, &quot;k_proj&quot;, &quot;v_proj&quot;, &quot;o_proj&quot;,
        &quot;up_proj&quot;, &quot;down_proj&quot;
    ],
    lora_alpha=16,                  # Scales adapter updates
    lora_dropout=0,                 # No dropout
    bias=&quot;none&quot;,                    # Skip bias updates
    use_gradient_checkpointing=&quot;unsloth&quot;,  # Unsloth-optimized checkpointing
    random_state=3407,              # For reproducibility
    use_rslora=False,               # Optional advanced LoRA variant
    loftq_config=None,              # Optional LoftQ config
)
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;r&lt;/strong&gt; controls the size of the LoRA layers; higher uses more memory.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;lora_alpha&lt;/strong&gt; is like a “volume knob” for learning strength.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;use_gradient_checkpointing=&quot;unsloth&quot;&lt;/strong&gt; trades compute for lower VRAM.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;4-preparing-your-dataset-for-training&quot;&gt;4. Preparing Your Dataset for Training&lt;/h3&gt;
&lt;p&gt;When preparing datasets for fine-tuning models like &lt;strong&gt;LLaMA 3.1&lt;/strong&gt; and &lt;strong&gt;Phi-4&lt;/strong&gt;, format multi-turn conversations per each model’s expected structure.&lt;/p&gt;
&lt;h4 id=&quot;llama-3-1-chat-template-format&quot;&gt;LLaMA 3.1: Chat Template Format&lt;/h4&gt;
&lt;p&gt;LLaMA 3.1 wraps each message with special tokens:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;&amp;lt;|begin_of_text|&amp;gt;&amp;lt;|start_header_id|&amp;gt;system&amp;lt;|end_header_id|&amp;gt;
You are a helpful AI assistant.&amp;lt;|eot_id|&amp;gt;&amp;lt;|start_header_id|&amp;gt;user&amp;lt;|end_header_id|&amp;gt;
Hello!&amp;lt;|eot_id|&amp;gt;&amp;lt;|start_header_id|&amp;gt;assistant&amp;lt;|end_header_id|&amp;gt;
Hi there! How can I assist you today?&amp;lt;|eot_id|&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;&amp;lt;|begin_of_text|&amp;gt;&lt;/code&gt; marks the start&lt;/li&gt;
&lt;li&gt;&lt;code&gt;&amp;lt;|start_header_id|&amp;gt;&lt;/code&gt;/&lt;code&gt;&amp;lt;|end_header_id|&amp;gt;&lt;/code&gt; mark roles&lt;/li&gt;
&lt;li&gt;&lt;code&gt;&amp;lt;|eot_id|&amp;gt;&lt;/code&gt; ends each message&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Use Unsloth’s &lt;code&gt;standardize_sharegpt&lt;/code&gt; to convert existing data into this format.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Phi-4&lt;/strong&gt; uses ChatML JSON:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-json&quot;&gt;{
  &quot;messages&quot;: [
    {&quot;role&quot;: &quot;system&quot;,    &quot;content&quot;: &quot;You are a helpful assistant.&quot;},
    {&quot;role&quot;: &quot;user&quot;,      &quot;content&quot;: &quot;Can you explain machine learning?&quot;},
    {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: &quot;Certainly! Machine learning is...&quot;}
  ]
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;converting-between-formats&quot;&gt;Converting Between Formats&lt;/h4&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Identify&lt;/strong&gt; current format (CSV, ShareGPT, ChatML).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Convert&lt;/strong&gt; to a ShareGPT-like structure (from/value).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Standardize&lt;/strong&gt; to role/content with &lt;code&gt;standardize_sharegpt&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Apply&lt;/strong&gt; chat template via &lt;code&gt;get_chat_template&lt;/code&gt; and &lt;code&gt;apply_chat_template&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Below, set &lt;code&gt;USE_CSV = True&lt;/code&gt; or &lt;code&gt;False&lt;/code&gt; to choose your data source.&lt;/p&gt;
&lt;h4 id=&quot;custom-dataset-csv-&quot;&gt;Custom Dataset (CSV)&lt;/h4&gt;
&lt;p&gt;We used a fictional 30-question dataset from “Eastern Caverns” to illustrate fine-tuning on domain-specific Q\&amp;amp;A.&lt;/p&gt;
&lt;p&gt;{% gist &lt;a rel=&quot;nofollow&quot; href=&quot;https://gist.github.com/kingrishabdugar/8f10fca3368c4e57db7266ef6a765007.js&quot;&gt;https://gist.github.com/kingrishabdugar/8f10fca3368c4e57db7266ef6a765007.js&lt;/a&gt; %}&lt;/p&gt;
&lt;h4 id=&quot;configuration-amp-imports&quot;&gt;Configuration &amp;amp; Imports&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# Configuration &amp;amp; Imports
USE_CSV     = True                 # False → load a ShareGPT dataset instead
CSV_PATH    = &quot;your_data.csv&quot;      # CSV must have 'question' &amp;amp; 'answer' columns
SHAREGPT_DS = &quot;mlabonne/FineTome-100k&quot;  # HF ShareGPT-style dataset

import pandas as pd
from datasets import Dataset, load_dataset
from unsloth.chat_templates import get_chat_template, standardize_sharegpt
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://cdn-images-1.medium.com/max/3812/1*Sx4LKbQXSjhKD1eauQ7gKg.png&quot; alt=&quot;Uploaded CSV file screenshot showing file path&quot;&gt;&lt;/p&gt;
&lt;h4 id=&quot;loading-amp-wrapping-data&quot;&gt;Loading &amp;amp; Wrapping Data&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;if USE_CSV:
    df = pd.read_csv(CSV_PATH)
    ds = Dataset.from_pandas(df)

    def to_sharegpt_format(ex):
        return {
            &quot;conversations&quot;: [
                {&quot;from&quot;: &quot;system&quot;, &quot;value&quot;: &quot;You are a Victorian-era assistant…&quot;},
                {&quot;from&quot;: &quot;human&quot;,  &quot;value&quot;: ex[&quot;question&quot;]},
                {&quot;from&quot;: &quot;gpt&quot;,    &quot;value&quot;: ex[&quot;answer&quot;]},
            ]
        }
    ds = ds.map(to_sharegpt_format, remove_columns=df.columns.tolist())
else:
    ds = load_dataset(SHAREGPT_DS, split=&quot;train&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;standardizing-amp-applying-the-chat-template&quot;&gt;Standardizing &amp;amp; Applying the Chat Template&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;ds = standardize_sharegpt(ds)

CHAT_TEMPLATE = &quot;llama-3.1&quot;
tokenizer = get_chat_template(tokenizer, chat_template=CHAT_TEMPLATE)

def format_prompts(examples):
    texts = [
        tokenizer.apply_chat_template(
            convo,
            tokenize=False,
            add_generation_prompt=False
        )
        for convo in examples[&quot;conversations&quot;]
    ]
    return {&quot;text&quot;: texts}

nds = ds.map(format_prompts, batched=True)

print(&quot;===== BEFORE =====&quot;)
print(nds[0][&quot;conversations&quot;])
print(&quot;===== AFTER =====&quot;)
print(nds[0][&quot;text&quot;])
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fejnvscexff13xl4x456.png&quot; alt=&quot;Console output showing before and after dataset conversation formatting&quot;&gt;&lt;/p&gt;
&lt;h3 id=&quot;5-supervised-fine-tuning-with-sfttrainer&quot;&gt;5. Supervised Fine Tuning with SFTTrainer&lt;/h3&gt;
&lt;p&gt;Too many things here  — lets explore one by one,&lt;/p&gt;
&lt;h4 id=&quot;-sfttrainer&quot;&gt;️ SFTTrainer&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Purpose:&lt;/strong&gt; Trainer for Supervised Fine-Tuning (SFT) of LLMs.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Why:&lt;/strong&gt; Streamlines fine-tuning with built-in utilities.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id=&quot;key-components&quot;&gt;Key Components&lt;/h4&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;model, tokenizer, train_dataset&lt;/strong&gt; — The model, tokenizer, and dataset (&lt;code&gt;nds&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;dataset_text_field=&quot;text&quot;&lt;/strong&gt; — Uses the &lt;code&gt;&quot;text&quot;&lt;/code&gt; field for input.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;DataCollatorForSeq2Seq&lt;/strong&gt; — Pads and batches seq2seq data.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;TrainingArguments&lt;/strong&gt; — Hyperparameters (batch size, learning rate, epochs, etc.).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;per_device_train_batch_size=2&lt;/strong&gt; — Examples per device.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;gradient_accumulation_steps=4&lt;/strong&gt; — Simulate larger batches.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;warmup_steps=5&lt;/strong&gt; — Smooth learning rate start.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;max_steps=100&lt;/strong&gt; — Total training steps.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;optim=&quot;adamw_8bit&quot;&lt;/strong&gt; — 8-bit AdamW optimizer for memory savings.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;output_dir=&quot;outputs&quot;&lt;/strong&gt; — Where checkpoints go.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;from trl import SFTTrainer
from transformers import TrainingArguments, DataCollatorForSeq2Seq
from unsloth import is_bfloat16_supported

trainer = SFTTrainer(
    model=model,
    tokenizer=tokenizer,
    train_dataset=nds,
    dataset_text_field=&quot;text&quot;,
    max_seq_length=max_seq_length,
    data_collator=DataCollatorForSeq2Seq(tokenizer=tokenizer),
    args=TrainingArguments(
        per_device_train_batch_size=2,
        gradient_accumulation_steps=4,
        warmup_steps=5,
        num_train_epochs=1,
        max_steps=100,
        learning_rate=2e-4,
        fp16=not is_bfloat16_supported(),
        bf16=is_bfloat16_supported(),
        logging_steps=1,
        optim=&quot;adamw_8bit&quot;,
        weight_decay=0.01,
        output_dir=&quot;outputs&quot;,
        report_to=&quot;none&quot;,
    ),
)
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;6-kicking-off-the-training&quot;&gt;6. Kicking-off the training&lt;/h3&gt;
&lt;p&gt;Use Unsloth’s &lt;code&gt;train_on_responses_only&lt;/code&gt; to compute loss only on the assistant’s output:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;from unsloth.chat_templates import train_on_responses_only

trainer = train_on_responses_only(
    trainer,
    instruction_part=&quot;&amp;lt;|start_header_id|&amp;gt;user&amp;lt;|end_header_id|&amp;gt;\n\n&quot;,
    response_part=&quot;&amp;lt;|start_header_id|&amp;gt;assistant&amp;lt;|end_header_id|&amp;gt;\n\n&quot;,
)

stats = trainer.train()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You’ll see the loss drop steadily—proof your 4-bit Llama 3.2 is learning efficiently.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://cdn-images-1.medium.com/max/2454/1*7LX5zkVfcrZRFYXPcs64fQ.png&quot; alt=&quot;Training loss curve showing decrease over steps&quot;&gt;&lt;/p&gt;
&lt;h3 id=&quot;7-inference-amp-saving-your-model&quot;&gt;7. Inference &amp;amp; Saving Your Model&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Fast Inference Mode&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;model = FastLanguageModel.for_inference(model)

inputs = tokenizer.apply_chat_template(
    [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;&amp;lt;Your Question Here&amp;gt;&quot;}],
    tokenize=True,
    add_generation_prompt=True,
    return_tensors=&quot;pt&quot;,
).to(&quot;cuda&quot;)

outputs = model.generate(input_ids=inputs, max_new_tokens=256)
print(tokenizer.batch_decode(outputs)[0])
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://cdn-images-1.medium.com/max/3704/1*4vmPEsEIN4wY3GZDpM1U4w.png&quot; alt=&quot;Example generated response in notebook output&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Save &amp;amp; Reload&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# Save
model.save_pretrained(&quot;/content/drive/MyDrive/my_llama3_model_eastern_caverns&quot;)
tokenizer.save_pretrained(&quot;/content/drive/MyDrive/my_llama3_model_eastern_caverns&quot;)

# Reload in 4-bit mode
from transformers import AutoTokenizer
from unsloth import FastLanguageModel

tokenizer = AutoTokenizer.from_pretrained(&quot;/content/drive/MyDrive/my_llama3_model_eastern_caverns&quot;)
model, tokenizer = FastLanguageModel.from_pretrained(
    model_name=&quot;/content/drive/MyDrive/my_llama3_model_eastern_caverns&quot;,
    load_in_4bit=True,
    max_seq_length=2048,
)

# Quick test
inputs = tokenizer(&quot;What backup options are available for the CavernDB cluster?&quot;, return_tensors=&quot;pt&quot;).to(&quot;cuda&quot;)
outputs = model.generate(**inputs, max_new_tokens=100)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://cdn-images-1.medium.com/max/2964/1*1MPLmoKI3PUvTQlXFfk1QA.png&quot; alt=&quot;Output showing saved model reload test&quot;&gt;&lt;/p&gt;
&lt;h3 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;https://cdn-images-1.medium.com/max/3072/0*_Z_jZ8xDebcmwHg_&quot; alt=&quot;The Pharaoh’s Workshop of Wisdom with UnSloth Guide — ornate workshop scene&quot;&gt;&lt;/p&gt;
&lt;p&gt;Fine-tuning a large language model is all about balancing precision, speed, and the right data.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Precision vs. Quantization&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Full precision (FP32) → \~4.3 billion weight values&lt;/li&gt;
&lt;li&gt;4-bit quantization → 16 levels (tiny rounding error for big memory savings)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Why 4-Bit Helps&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;7 B params in FP16 needs \~28 GB RAM; in 4-bit \~7 GB&lt;/li&gt;
&lt;li&gt;Avoids out-of-memory on free GPUs (Colab, Kaggle)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Unsloth’s Speed Boost&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Up to 2× faster fine-tuning, \~70% VRAM reduction&lt;/li&gt;
&lt;li&gt;Memory-efficient kernels without accuracy loss&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Picking the Right Dataset&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Too small → overfitting; too big/wild → underfitting&lt;/li&gt;
&lt;li&gt;Aim for focused, high-quality examples in proper order&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;That’s your bird’s-eye view: squeezing precision, saving resources, turbo-charging training with Unsloth, and choosing data wisely. Feedback and questions are always welcome!&lt;/p&gt;
&lt;p&gt;One last thing — if you’ve made it this far, I’ve dropped the Colab notebook link in the comments below. Feel free to dive in and give it a spin  !&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;further-reading-amp-resources&quot;&gt;Further Reading &amp;amp; Resources&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Unsloth GitHub&lt;/strong&gt; — &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/unslothai/unsloth&quot;&gt;https://github.com/unslothai/unsloth&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Hugging Face Datasets&lt;/strong&gt; — &lt;a rel=&quot;nofollow&quot; href=&quot;https://huggingface.co/docs/datasets&quot;&gt;https://huggingface.co/docs/datasets&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;PEFT Paper (LoRA)&lt;/strong&gt; — &lt;a rel=&quot;nofollow&quot; href=&quot;https://arxiv.org/abs/2106.09685&quot;&gt;https://arxiv.org/abs/2106.09685&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Google Colab&lt;/strong&gt; — &lt;a rel=&quot;nofollow&quot; href=&quot;https://colab.research.google.com/&quot;&gt;https://colab.research.google.com/&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;#LLM #fine-tuning #Unsloth #tutorial #PEFT #LoRA #4-bit #quantization #Colab #T4GPU #SFTTrainer #inference #optimization&lt;/p&gt;
</description>
<category>ML Basics</category>
<guid isPermaLink="true">https://coderlegion.com/3080/fine-tune-slms-in-colab-for-free-a-4-bit-approach-with-meta-llama3-2</guid>
<pubDate>Sun, 18 May 2025 05:29:07 +0000</pubDate>
</item>
</channel>
</rss>