> 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 तेज़ फ़ाइन-ट्यूनिंग

Clore.ai पर Unsloth का उपयोग करके 70% कम VRAM के साथ LLMs को 2x तेज़ फ़ाइन-ट्यून करें

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

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

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

* **2 गुना तेज़ प्रशिक्षण** — attention, RoPE, cross-entropy, और RMS norm के लिए कस्टम Triton kernels
* **70% कम VRAM** — बुद्धिमान gradient checkpointing और memory-mapped weights
* **सीधे-उपयोग योग्य HuggingFace प्रतिस्थापन** — सिर्फ एक import बदलाव, और कुछ नहीं
* **QLoRA / LoRA / पूर्ण fine-tune** — सभी मोड स्वाभाविक रूप से समर्थित हैं
* **मूल निर्यात** — सीधे GGUF (सभी quant प्रकार), LoRA adapters, या merged 16-bit में सहेजें
* **व्यापक मॉडल कवरेज** — 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   | 12.8+          | 12.8+          |
| Python | 3.10           | 3.11           |

**Clore.ai pricing:** RTX 4090 ≈ $0.14–0.42/घंटा · RTX 3090 ≈ $0.07–0.21/घंटा · RTX 3060 ≈ $0.03–0.07/घंटा

4-बिट QLoRA वाला 7B मॉडल समा जाता है **\~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-बिट क्वांटाइज़ेशन के साथ मॉडल लोड करें

```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 adapters लागू करें

```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"प्रशिक्षण हानि: {stats.training_loss:.4f}")
```

## मॉडल निर्यात करना

### केवल LoRA adapter सहेजें

```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 में quantize करें (आकार और गुणवत्ता के बीच अच्छा संतुलन)
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 "transformers architecture के मुख्य बिंदुओं का सारांश दें"
```

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

### कस्टम चैट डेटासेट पर Fine-Tune करें

```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": "आप एक सहायक सहायक हैं."},
        {"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 reference model को आंतरिक रूप से संभालता है
    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-बिट  | QLoRA | \~10 GB | RTX 3060    |
| Llama 3.1 8B   | 16-बिट | LoRA  | \~18 GB | RTX 3090    |
| Qwen 2.5 14B   | 4-बिट  | QLoRA | \~14 GB | RTX 3090    |
| Mistral 7B     | 4-बिट  | QLoRA | \~9 GB  | RTX 3060    |
| DeepSeek-R1 7B | 4-बिट  | QLoRA | \~10 GB | RTX 3060    |
| Llama 3.3 70B  | 4-बिट  | QLoRA | \~44 GB | 2× RTX 3090 |

## सुझाव

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

## समस्या निवारण

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

## संसाधन

* [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.
