> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-hi/training/unsloth-finetune.md).

# Unsloth 2x तेज़ Fine-tuning

Unsloth HuggingFace Transformers के प्रदर्शन-नजरिए हिस्सों को हाथ से अनुकूलित Triton कर्नेल्स के साथ पुनर्लेखन करता है, प्रदान करते हुए **2x प्रशिक्षण गति** और **70% VRAM कमी** बिना किसी सटीकता हानि के। यह एक drop-in रिप्लेसमेंट है — आयात बदलने के बाद आपके मौजूदा TRL/PEFT स्क्रिप्ट बिना बदलाव के काम करेंगे।

{% hint style="success" %}
सभी उदाहरण GPU सर्वरों पर चलते हैं जो कि के माध्यम से किराये पर लिए गए हैं [CLORE.AI मार्केटप्लेस](https://clore.ai/marketplace).
{% endhint %}

## प्रमुख विशेषताएँ

* **2x तेज़ प्रशिक्षण** — attention, RoPE, cross-entropy, और RMS norm के लिए कस्टम Triton कर्नेल्स
* **70% कम VRAM** — बुद्धिमान gradient checkpointing और memory-mapped weights
* **Drop-in HuggingFace रिप्लेसमेंट** — केवल एक import परिवर्तन, और कुछ भी नहीं
* **QLoRA / LoRA / पूर्ण फाइन-ट्यून** — सभी मोड बॉक्स से बाहर समर्थित
* **मूल (नेटिव) एक्सपोर्ट** — सीधे GGUF (सभी क्वांट प्रकार), LoRA एडाप्टर्स, या मर्ज्ड 16-बिट में सहेजें
* **विस्तृत मॉडल कवरेज** — Llama 3.x, Mistral, Qwen 2.5, Gemma 2, DeepSeek-R1, Phi-4, और भी बहुत कुछ
* **मुफ्त और ओपन सोर्स** (Apache 2.0)

## आवश्यकताएँ

| घटक    | न्यूनतम        | अनुशंसित       |
| ------ | -------------- | -------------- |
| GPU    | RTX 3060 12 GB | RTX 4090 24 GB |
| VRAM   | 10 GB          | 24 GB          |
| RAM    | 16 GB          | 32 GB          |
| डिस्क  | 40 GB          | 80 GB          |
| CUDA   | 11.8           | 12.1+          |
| Python | 3.10           | 3.11           |

**Clore.ai मूल्य निर्धारण:** RTX 4090 ≈ $0.5–2/दिन · RTX 3090 ≈ $0.3–1/दिन · RTX 3060 ≈ $0.15–0.3/दिन

एक 7B मॉडल 4-bit QLoRA के साथ फिट हो जाता है **\~10 GB VRAM**, जिससे यहां तक कि एक RTX 3060 भी सक्षम बन जाता है।

## त्वरित प्रारम्भ

### 1. Unsloth इंस्टॉल करें

```bash
# एक venv बनाएं (अनुशंसित)
python -m venv /workspace/unsloth-env
source /workspace/unsloth-env/bin/activate

pip install --upgrade pip
pip install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
pip install --no-deps trl peft accelerate bitsandbytes xformers
```

### 2. 4-bit क्वांटाइज़ेशन के साथ एक मॉडल लोड करें

```python
from unsloth import FastLanguageModel
import torch

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name="unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit",
    max_seq_length=2048,
    dtype=None,            # ऑटो-डिटेक्ट (Ampere पर float16, Ada पर bfloat16)
    load_in_4bit=True,
)
```

### 3. LoRA एडाप्टर्स लागू करें

```python
model = FastLanguageModel.get_peft_model(
    model,
    r=16,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
                     "gate_proj", "up_proj", "down_proj"],
    lora_alpha=16,
    lora_dropout=0,
    bias="none",
    use_gradient_checkpointing="unsloth",   # 70% VRAM कमी
    random_state=42,
    use_rslora=False,
    loftq_config=None,
)
```

### 4. डेटा तैयार करें और प्रशिक्षण करें

```python
from datasets import load_dataset
from trl import SFTTrainer
from transformers import TrainingArguments

dataset = load_dataset("yahma/alpaca-cleaned", split="train")

trainer = SFTTrainer(
    model=model,
    tokenizer=tokenizer,
    train_dataset=dataset,
    dataset_text_field="text",
    max_seq_length=2048,
    dataset_num_proc=2,
    packing=True,
    args=TrainingArguments(
        per_device_train_batch_size=2,
        gradient_accumulation_steps=4,
        warmup_steps=10,
        num_train_epochs=1,
        learning_rate=2e-4,
        fp16=not torch.cuda.is_bf16_supported(),
        bf16=torch.cuda.is_bf16_supported(),
        logging_steps=10,
        optim="adamw_8bit",
        weight_decay=0.01,
        lr_scheduler_type="linear",
        seed=42,
        output_dir="/workspace/outputs",
    ),
)

stats = trainer.train()
print(f"Training loss: {stats.training_loss:.4f}")
```

## मॉडल का एक्सपोर्ट करना

### केवल LoRA एडाप्टर सहेजें

```python
model.save_pretrained("/workspace/lora-adapter")
tokenizer.save_pretrained("/workspace/lora-adapter")
```

### मर्ज करके पूर्ण मॉडल सहेजें (float16)

```python
model.save_pretrained_merged(
    "/workspace/merged-model",
    tokenizer,
    save_method="merged_16bit",
)
```

### Ollama / llama.cpp के लिए GGUF में एक्सपोर्ट करें

```python
# Q4_K_M में क्वांटाइज़ करें (आकार और गुणवत्ता का अच्छा संतुलन)
model.save_pretrained_gguf(
    "/workspace/gguf-output",
    tokenizer,
    quantization_method="q4_k_m",
)

# अन्य विकल्प: q5_k_m, q8_0, f16
```

एक्सपोर्ट के बाद, Ollama के साथ सर्व करें:

```bash
# एक Ollama modelfile बनाएं
cat > Modelfile <<EOF
FROM /workspace/gguf-output/unsloth.Q4_K_M.gguf
TEMPLATE "{{ .System }}\n{{ .Prompt }}"
PARAMETER temperature 0.7
EOF

ollama create my-finetuned -f Modelfile
ollama run my-finetuned "Summarize the key points of transformers architecture"
```

## उपयोग के उदाहरण

### कस्टम चैट डेटासेट पर फाइन-ट्यून करें

```python
from unsloth.chat_templates import get_chat_template

tokenizer = get_chat_template(tokenizer, chat_template="llama-3.1")

def format_chat(example):
    messages = [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": example["instruction"]},
        {"role": "assistant", "content": example["output"]},
    ]
    return {"text": tokenizer.apply_chat_template(messages, tokenize=False)}

dataset = dataset.map(format_chat)
```

### DPO / ORPO एलाइनमेंट प्रशिक्षण

```python
from trl import DPOTrainer, DPOConfig

dpo_trainer = DPOTrainer(
    model=model,
    ref_model=None,          # Unsloth संदर्भ मॉडल आंतरिक रूप से संभालता है
    args=DPOConfig(
        per_device_train_batch_size=2,
        gradient_accumulation_steps=4,
        learning_rate=5e-6,
        num_train_epochs=1,
        beta=0.1,
        output_dir="/workspace/dpo-output",
    ),
    train_dataset=dpo_dataset,
    tokenizer=tokenizer,
)
dpo_trainer.train()
```

## VRAM उपयोग संदर्भ

| मॉडल           | क्वांट | विधि  | VRAM    | GPU         |
| -------------- | ------ | ----- | ------- | ----------- |
| Llama 3.1 8B   | 4-bit  | QLoRA | \~10 GB | RTX 3060    |
| Llama 3.1 8B   | 16-bit | LoRA  | \~18 GB | RTX 3090    |
| Qwen 2.5 14B   | 4-bit  | QLoRA | \~14 GB | RTX 3090    |
| Mistral 7B     | 4-bit  | QLoRA | \~9 GB  | RTX 3060    |
| DeepSeek-R1 7B | 4-bit  | QLoRA | \~10 GB | RTX 3060    |
| Llama 3.3 70B  | 4-bit  | QLoRA | \~44 GB | 2× RTX 3090 |

## टिप्स

* **हमेशा उपयोग करें `use_gradient_checkpointing="unsloth"`** — यह एकल सबसे बड़ा VRAM बचाने वाला है, जो Unsloth के लिए विशिष्ट है
* **सेट करें `lora_dropout=0`** — Unsloth के Triton कर्नेल्स शून्य dropout के लिए अनुकूलित हैं और तेज़ चलते हैं
* **उपयोग करें `packing=True`** SFTTrainer में ताकि छोटे उदाहरणों पर padding की बर्बादी से बचा जा सके
* **के साथ शुरू करें `r=16`** LoRA रैंक के लिए — केवल तभी 32 या 64 बढ़ाएँ जब validation loss प्लेट्यू हो जाए
* **wandb के साथ मॉनिटर करें** — जोड़ें `report_to="wandb"` loss ट्रैकिंग के लिए TrainingArguments में
* **बैच साइज ट्यूनिंग** — बढ़ाएँ `per_device_train_batch_size` जब तक आप VRAM सीमा के पास न पहुँचें, फिर क्षतिपूर्ति करें `gradient_accumulation_steps`

## समस्याओं का निवारण

| समस्या                                | समाधान                                                                            |
| ------------------------------------- | --------------------------------------------------------------------------------- |
| `OutOfMemoryError` प्रशिक्षण के दौरान | बैच साइज को 1 तक घटाएं, कम करें `max_seq_length`, या 4-bit क्वांट का उपयोग करें   |
| Triton कर्नेल कंपाइलेशन त्रुटियाँ     | चलाएँ `pip install triton --upgrade` और सुनिश्चित करें कि CUDA टूलकिट मेल खाता है |
| पहला कदम धीमा (कम्पाइलिंग)            | सामान्य — Triton पहले रन पर कर्नेल्स कम्पाइल करता है, बाद में कैश हो जाते हैं     |
| `bitsandbytes` CUDA संस्करण त्रुटि    | मेल खाता हुआ वर्शन इंस्टॉल करें: `pip install bitsandbytes --upgrade`             |
| प्रशिक्षण के दौरान loss spike होना    | learning rate को 1e-4 तक घटाएँ, warmup steps जोड़ें                               |
| GGUF एक्सपोर्ट क्रैश होना             | कन्वर्ज़न के लिए पर्याप्त RAM (मॉडल साइज़ का 2×) और डिस्क स्पेस सुनिश्चित करें    |

## संसाधन

* [Unsloth GitHub](https://github.com/unslothai/unsloth)
* [Unsloth Wiki — सभी नोटबुक्स](https://github.com/unslothai/unsloth/wiki)
* [CLORE.AI मार्केटप्लेस](https://clore.ai/marketplace)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-hi/training/unsloth-finetune.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
