<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged llama</title>
<link>https://coderlegion.com/tag/llama</link>
<description>Powered by Question2Answer</description>
<item>
<title>Power Up Java with AI: Integrate LLaMA 3 Using Spring Boot</title>
<link>https://coderlegion.com/4333/power-up-java-with-ai-integrate-llama-3-using-spring-boot</link>
<description>&lt;p&gt;In today’s world of artificial intelligence, creating a personal AI assistant has become surprisingly accessible thanks to various LLM models. With Spring Boot and open-source AI models, we can build a conversational AI within Java applications. Let’s explore how this works.&lt;/p&gt;
&lt;p&gt;In this example, we’ll install and use Ollama locally, and create an endpoint that accepts a user’s prompt and returns a response using AI.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Step 1: Install Ollama&lt;/strong&gt;&lt;br&gt;
To get started, install Ollama using this link.&lt;br&gt;
Once the installation is complete, download one of the available models. For this example, we’ll use the LLaMA 3 model:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;ollama run llama3 // or any other model
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After the model is downloaded, you can also interact with it directly through the terminal:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; hello
Hello! It's nice to meet you. Is there something I can help you with, or would you like to chat?
&amp;gt;&amp;gt;&amp;gt; 
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Step 2: Connect to Ollama from a Spring Boot Application&lt;/strong&gt;&lt;br&gt;
Now it’s time to connect Ollama with a Spring Boot application.&lt;br&gt;
Let’s quickly generate a Spring Boot project using start.spring.io.&lt;br&gt;
Here’s an example of the build.gradle file with the necessary dependencies:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;plugins {
 id 'java'
 id 'org.springframework.boot' version '3.5.0'
 id 'io.spring.dependency-management' version '1.1.7'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'

java {
 toolchain {
  languageVersion = JavaLanguageVersion.of(21)
 }
}

repositories {
 mavenCentral()
}

ext {
 set('springAiVersion', &quot;1.0.0&quot;)
}

dependencies {
 implementation 'org.springframework.ai:spring-ai-starter-model-ollama'
}

dependencyManagement {
 imports {
  mavenBom &quot;org.springframework.ai:spring-ai-bom:${springAiVersion}&quot;
 }
}

tasks.named('test') {
 useJUnitPlatform()
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Step 3: Create a REST Endpoint&lt;/strong&gt;&lt;br&gt;
After setting up the dependencies, all we need is a simple REST endpoint that receives a user prompt, sends it to the LLaMA 3 model, and returns the response.&lt;br&gt;
For this, we can use the ChatModel class.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.api.OllamaModel;
import org.springframework.ai.ollama.api.OllamaOptions;

@RestController
@RequiredArgsConstructor
public class ChatController {
    private final ChatModel chatModel;

    @GetMapping(&quot;/message&quot;)
    public String handleMessage(@RequestParam String message) {
        var response = chatModel.call(
                new Prompt(
                        message,
                        OllamaOptions.builder()
                                .model(OllamaModel.LLAMA3)
                                .temperature(0.4)
                                .build()
                ));
        return response.getResult().getOutput().getText();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Key Components:&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;ChatModel&lt;/strong&gt; — Interface that calls the AI model to generate responses.&lt;br&gt;
&lt;strong&gt;Prompt&lt;/strong&gt; — Wraps the user’s message and AI configuration into a single request.&lt;br&gt;
&lt;strong&gt;OllamaOptions&lt;/strong&gt; — Configures model settings such as temperature and model selection.&lt;br&gt;
&lt;strong&gt;OllamaModel.LLAMA3&lt;/strong&gt; — Specifies the LLaMA 3 model for processing the input.&lt;br&gt;
&lt;strong&gt;temperature&lt;/strong&gt; — Controls the creativity of the response (0 = strict, 1 = more random).&lt;/p&gt;
&lt;p&gt;Its time to test:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://coderlegion.com/?qa=blob&amp;amp;qa_blobid=9451787985168007589&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
Using Ollama locally with Spring AI makes it easy to build AI-powered APIs without relying on external cloud services. Without spending anything for the LLM model, an AI-powered chat endpoint is ready. We can do a little bit of prompt engineering to make it more specialized.&lt;/p&gt;
</description>
<category>Java</category>
<guid isPermaLink="true">https://coderlegion.com/4333/power-up-java-with-ai-integrate-llama-3-using-spring-boot</guid>
<pubDate>Wed, 30 Jul 2025 07:25:28 +0000</pubDate>
</item>
<item>
<title>When AI Speaks Your Language(s): Multilingual TTS for Smarter Healthcare</title>
<link>https://coderlegion.com/4276/when-ai-speaks-your-language-s-multilingual-tts-for-smarter-healthcare</link>
<description>&lt;p&gt;&lt;strong&gt;Most AI voices sound smooth — until you ask them to speak like a real person.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;In the real world, especially in places like Bangladesh, we don’t speak in perfect monolingual sentences. We mix languages. We jump between English and Bengali effortlessly. But most Text-to-Speech (TTS) systems? They’re still stuck in translation mode.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;the-reality-of-multilingual-speech&quot;&gt;The Reality of Multilingual Speech&lt;/h3&gt;
&lt;p&gt;In multilingual societies, language mixing isn’t a bug — it’s a feature. People code-switch all the time, especially in healthcare, where speed, clarity, and comfort matter most.&lt;/p&gt;
&lt;p&gt;But here's the catch:&lt;br&gt;
TTS systems don’t know how to &lt;strong&gt;sound natural&lt;/strong&gt; when switching between two languages. They stumble, mispronounce, or sound robotic — and in sensitive environments like hospitals, that’s a real problem.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;the-fix-medibeng-orpheus-3b-0-1-ft&quot;&gt;The Fix: Medibeng-Orpheus-3b-0.1-ft&lt;/h3&gt;
&lt;p&gt;That’s why I built &lt;strong&gt;Medibeng-Orpheus-3b-0.1-ft&lt;/strong&gt;, a fine-tuned TTS model designed to generate &lt;strong&gt;natural, code-switched Bengali-English speech&lt;/strong&gt; — optimized for the healthcare domain.&lt;/p&gt;
&lt;p&gt;It’s a project under &lt;strong&gt;The Data Dilemma&lt;/strong&gt;, built using &lt;strong&gt;Orpheus TTS&lt;/strong&gt;, fine-tuned on real-world healthcare-style dialogues, and accelerated by &lt;strong&gt;Unsloth AI&lt;/strong&gt; using the &lt;strong&gt;Canopy LLaMA base&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt; &lt;strong&gt;Objective&lt;/strong&gt;: Build an AI voice that sounds like someone you’d actually hear in a hospital in Dhaka or Sylhet — fluent in both languages, and emotionally tuned.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;key-features&quot;&gt;Key Features&lt;/h3&gt;
&lt;p&gt;✅ &lt;strong&gt;Multilingual Code-Switching&lt;/strong&gt;&lt;br&gt;
Handles mixed-language input without awkward drops or pauses.&lt;/p&gt;
&lt;p&gt;✅ &lt;strong&gt;Real-Time Friendly&lt;/strong&gt;&lt;br&gt;
Optimized for deployment in live settings like hospital kiosks, telemedicine bots, or mobile health apps.&lt;/p&gt;
&lt;p&gt;✅ &lt;strong&gt;Healthcare-Aware Speech&lt;/strong&gt;&lt;br&gt;
The voice understands tone, urgency, and medical context better than generic TTS models.&lt;/p&gt;
&lt;p&gt;✅ &lt;strong&gt;Privacy-Conscious&lt;/strong&gt;&lt;br&gt;
Trained with ethical standards, making it safer for use in sensitive, regulated domains.&lt;/p&gt;
&lt;hr&gt;
&lt;h3 id=&quot;want-to-explore-&quot;&gt;Want to Explore?&lt;/h3&gt;
&lt;p&gt;I’ve made everything open for the community. You can test it, fork it, or fine-tune it further.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://lnkd.in/dSSHhBgY&quot;&gt;GitHub Repository&lt;/a&gt;  &lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://lnkd.in/dpka7zsD&quot;&gt;Hugging Face Model&lt;/a&gt;  &lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://lnkd.in/d9pfC9j6&quot;&gt;Explore the Dataset&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;hr&gt;
&lt;h3 id=&quot;final-thoughts&quot;&gt;Final Thoughts&lt;/h3&gt;
&lt;p&gt;Speech is more than words. It’s rhythm, context, culture — and sometimes, it’s two languages at once. If we want AI to truly support humans in critical areas like healthcare, we need systems that &lt;strong&gt;speak like us&lt;/strong&gt; — not just understand us.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Medibeng-Orpheus&lt;/strong&gt; is a step toward that vision:&lt;br&gt;
A voice that blends technology with reality.&lt;/p&gt;
&lt;hr&gt;
&lt;blockquote&gt;&lt;p&gt; &lt;strong&gt;Let’s make AI sound less artificial, and more like us.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;hr&gt;
&lt;h4 id=&quot;tags&quot;&gt;Tags&lt;/h4&gt;
&lt;p&gt;&lt;code&gt;#TTS&lt;/code&gt; &lt;code&gt;#SpeechSynthesis&lt;/code&gt; &lt;code&gt;#MultilingualAI&lt;/code&gt; &lt;code&gt;#HealthcareAI&lt;/code&gt; &lt;code&gt;#CodeSwitching&lt;/code&gt; &lt;code&gt;#EthicalAI&lt;/code&gt; &lt;code&gt;#OpenSource&lt;/code&gt; &lt;code&gt;#OrpheusTTS&lt;/code&gt; &lt;code&gt;#LLM&lt;/code&gt; &lt;code&gt;#BangladeshTech&lt;/code&gt; &lt;code&gt;#AIForGood&lt;/code&gt;&lt;/p&gt;
</description>
<category>Python3</category>
<guid isPermaLink="true">https://coderlegion.com/4276/when-ai-speaks-your-language-s-multilingual-tts-for-smarter-healthcare</guid>
<pubDate>Sat, 26 Jul 2025 07:56:12 +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>