> 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/finetune-llm.md).

# Fine-tune LLM

CLORE.AI GPU पर कुशल फाइन-ट्यूनिंग तकनीकों का उपयोग करके अपना कस्टम LLM प्रशिक्षित करें।

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

## CLORE.AI पर किराए पर लेना

1. देखें [CLORE.AI Marketplace](https://clore.ai/marketplace)
2. GPU प्रकार, VRAM और कीमत के अनुसार फ़िल्टर करें
3. चुनें **On-Demand** (निश्चित दर) या **Spot** (बोली मूल्य)
4. अपना ऑर्डर कॉन्फ़िगर करें:
   * Docker इमेज चुनें
   * पोर्ट सेट करें (SSH के लिए TCP, वेब UIs के लिए HTTP)
   * ज़रूरत हो तो environment variables जोड़ें
   * स्टार्टअप कमांड दर्ज करें
5. भुगतान चुनें: **CLORE**, **BTC**या **USDT/USDC**
6. ऑर्डर बनाएं और deployment की प्रतीक्षा करें

### अपने सर्वर तक पहुँचें

* कनेक्शन विवरण यहाँ पाएँ **My Orders**
* वेब interfaces: HTTP port URL का उपयोग करें
* SSH: `ssh -p <port> root@<proxy-address>`

## LoRA/QLoRA क्या है?

* **LoRA** (Low-Rank Adaptation) - पूरे मॉडल के बजाय छोटे adapter layers को प्रशिक्षित करें
* **QLoRA** - और भी कम VRAM के लिए quantization के साथ LoRA
* एक ही RTX 3090 पर 7B मॉडल प्रशिक्षित करें
* एक ही A100 पर 70B मॉडल प्रशिक्षित करें

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

| मॉडल | विधि      | न्यूनतम VRAM | अनुशंसित                                                                                                 |
| ---- | --------- | ------------ | -------------------------------------------------------------------------------------------------------- |
| 7B   | QLoRA     | 12GB         | [RTX 3090](https://clore.ai/rent-3090.html?utm_source=docs\&utm_medium=guide\&utm_campaign=finetune-llm) |
| 13B  | QLoRA     | 20GB         | [RTX 4090](https://clore.ai/rent-4090.html?utm_source=docs\&utm_medium=guide\&utm_campaign=finetune-llm) |
| 70B  | QLoRA     | 48GB         | A100 80GB                                                                                                |
| 7B   | Full LoRA | 24GB         | RTX 4090                                                                                                 |

## तेज़ डिप्लॉयमेंट

**Docker इमेज:**

```
pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel
```

**पोर्ट्स:**

```
22/tcp
8888/http
6006/http
```

**कमांड:**

```bash
pip install "transformers>=4.45" "datasets>=2.20" accelerate "peft>=0.14" \
    bitsandbytes "trl>=0.12" wandb jupyterlab && \
jupyter lab --ip=0.0.0.0 --port=8888 --allow-root
```

## अपनी सेवा तक पहुँचना

डिप्लॉयमेंट के बाद, अपना `http_pub` URL यहाँ पाएँ **My Orders**:

1. पर जाएँ **My Orders** पेज
2. अपने ऑर्डर पर क्लिक करें
3. ढूँढें `http_pub` URL (उदा., `abc123.clorecloud.net`)

उपयोग करें `https://YOUR_HTTP_PUB_URL` के बजाय `localhost` नीचे दिए गए उदाहरणों में।

## डेटासेट तैयारी

### Chat Format (अनुशंसित)

```json
[
  {
    "messages": [
      {"role": "system", "content": "आप एक सहायक assistant हैं."},
      {"role": "user", "content": "Python क्या है?"},
      {"role": "assistant", "content": "Python एक प्रोग्रामिंग भाषा है..."}
    ]
  }
]
```

### Instruction Format

```json
[
  {
    "instruction": "फ़्रेंच में अनुवाद करें",
    "input": "Hello, how are you?",
    "output": "Bonjour, comment allez-vous?"
  }
]
```

### Alpaca Format

```json
[
  {
    "instruction": "स्वस्थ रहने के लिए तीन सुझाव दें.",
    "input": "",
    "output": "1. संतुलित भोजन करें..."
  }
]
```

## समर्थित आधुनिक मॉडल (2025)

| मॉडल                        | HF ID                                     | न्यूनतम VRAM (QLoRA) |
| --------------------------- | ----------------------------------------- | -------------------- |
| Llama 3.1 / 3.3 8B          | `meta-llama/Llama-3.1-8B-Instruct`        | 12GB                 |
| Qwen 2.5 7B / 14B           | `Qwen/Qwen2.5-7B-Instruct`                | 12GB / 20GB          |
| DeepSeek-R1-Distill (7B/8B) | `deepseek-ai/DeepSeek-R1-Distill-Qwen-7B` | 12GB                 |
| Mistral 7B v0.3             | `mistralai/Mistral-7B-Instruct-v0.3`      | 12GB                 |
| Gemma 2 9B                  | `google/gemma-2-9b-it`                    | 14GB                 |
| Phi-4 14B                   | `microsoft/phi-4`                         | 20GB                 |

## QLoRA फाइन-ट्यूनिंग स्क्रिप्ट

PEFT 0.14+, Flash Attention 2, DoRA support, और Qwen2.5 / DeepSeek-R1 compatibility के साथ आधुनिक उदाहरण:

```python
import torch
from transformers import (
    AutoModelForCausalLM,
    AutoTokenizer,
    BitsAndBytesConfig,
    TrainingArguments,
)
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
from datasets import load_dataset
from trl import SFTTrainer, SFTConfig

# === कॉन्फ़िगरेशन ===
# इनमें से एक चुनें: Qwen2.5, DeepSeek-R1-Distill, Llama 3.1, Mistral, आदि।
MODEL_NAME = "Qwen/Qwen2.5-7B-Instruct"
# MODEL_NAME = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
# MODEL_NAME = "meta-llama/Llama-3.1-8B-Instruct"

DATASET = "your_dataset.json"  # या HuggingFace dataset name
OUTPUT_DIR = "./output"
MAX_SEQ_LENGTH = 4096           # Qwen2.5 32K context तक सपोर्ट करता है
USE_DORA = True                 # DoRA, standard LoRA की तुलना में गुणवत्ता सुधारता है
USE_FLASH_ATTN = True           # Flash Attention 2 VRAM बचाता है और गति बढ़ाता है

# === 4-bit Quantization के साथ मॉडल लोड करें ===
bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16,
    bnb_4bit_use_double_quant=True,
)

model = AutoModelForCausalLM.from_pretrained(
    MODEL_NAME,
    quantization_config=bnb_config,
    device_map="auto",
    trust_remote_code=True,  # Qwen2.5 और DeepSeek के लिए आवश्यक
    # Flash Attention 2: Ampere+ GPU (RTX 30/40, A100) की आवश्यकता होती है
    attn_implementation="flash_attention_2" if USE_FLASH_ATTN else "eager",
)

tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
if tokenizer.pad_token is None:
    tokenizer.pad_token = tokenizer.eos_token
tokenizer.padding_side = "right"

# === वैकल्पिक DoRA के साथ LoRA कॉन्फ़िगर करें ===
# DoRA (Weight-Decomposed Low-Rank Adaptation) — PEFT >= 0.14 आवश्यक
# use_dora=True weights को magnitude + direction में विभाजित करता है ताकि गुणवत्ता बेहतर हो
lora_config = LoraConfig(
    r=64,                    # Rank (जितना अधिक = उतनी अधिक क्षमता, उतनी अधिक VRAM)
    lora_alpha=16,           # Scaling factor (r के बराबर या आधा रखें)
    target_modules=[
        "q_proj", "k_proj", "v_proj", "o_proj",  # Attention layers
        "gate_proj", "up_proj", "down_proj",      # MLP layers
    ],
    lora_dropout=0.05,
    bias="none",
    task_type="CAUSAL_LM",
    use_dora=USE_DORA,        # DoRA: बेहतर गुणवत्ता (PEFT 0.14+)
    # use_rslora=True,        # वैकल्पिक: Rank-Stabilized LoRA
)

# QLoRA प्रशिक्षण के लिए मॉडल तैयार करें
model = prepare_model_for_kbit_training(
    model,
    use_gradient_checkpointing=True,
    gradient_checkpointing_kwargs={"use_reentrant": False},
)
model = get_peft_model(model, lora_config)

# प्रशिक्षण योग्य parameters का सारांश प्रिंट करें
model.print_trainable_parameters()
# उदाहरण आउटपुट: trainable params: 42,991,616 || all params: 7,284,891,648 || trainable%: 0.59

# === Dataset लोड करें ===
dataset = load_dataset("json", data_files=DATASET)
# या public dataset का उपयोग करें:
# dataset = load_dataset("HuggingFaceH4/ultrachat_200k")

# === Qwen2.5 / ChatML format के लिए dataset फ़ॉर्मेट करें ===
def format_chat_qwen(example):
    """Qwen2.5 के लिए ChatML template का उपयोग करके फ़ॉर्मेट करें."""
    messages = example.get("messages", [])
    if not messages:
        # alpaca-style data को संभालें
        text = f"<|im_start|>system\nआप एक सहायक assistant हैं.<|im_end|>\n"
        text += f"<|im_start|>user\n{example['instruction']}"
        if example.get("input"):
            text += f"\n{example['input']}"
        text += f"<|im_end|>\n<|im_start|>assistant\n{example['output']}<|im_end|>"
    else:
        # messages format (ChatML) को संभालें
        text = tokenizer.apply_chat_template(
            messages,
            tokenize=False,
            add_generation_prompt=False,
        )
    return {"text": text}

dataset = dataset.map(format_chat_qwen, remove_columns=dataset["train"].column_names)

# === Training Arguments (PEFT 0.14+ / TRL 0.12+) ===
training_args = SFTConfig(
    output_dir=OUTPUT_DIR,
    num_train_epochs=3,
    per_device_train_batch_size=2,
    gradient_accumulation_steps=8,         # प्रभावी batch = 2 * 8 = 16
    learning_rate=2e-4,
    weight_decay=0.001,
    warmup_ratio=0.03,
    lr_scheduler_type="cosine",
    logging_steps=10,
    save_steps=100,
    save_total_limit=3,
    bf16=True,                             # आधुनिक GPUs (A100, RTX 30/40) के लिए bf16 का उपयोग करें
    # fp16=True,                           # पुराने GPUs के लिए fp16 का उपयोग करें
    optim="paged_adamw_8bit",
    max_grad_norm=0.3,
    group_by_length=True,
    report_to="wandb",                     # या "tensorboard"
    # SFTConfig-specific:
    max_seq_length=MAX_SEQ_LENGTH,
    dataset_text_field="text",
    packing=True,                          # दक्षता के लिए multiple examples pack करें
)

# === Train ===
trainer = SFTTrainer(
    model=model,
    train_dataset=dataset["train"],
    tokenizer=tokenizer,
    args=training_args,
)

trainer.train()

# === LoRA adapter सहेजें ===
trainer.save_model(f"{OUTPUT_DIR}/final")
tokenizer.save_pretrained(f"{OUTPUT_DIR}/final")
print(f"Model saved to {OUTPUT_DIR}/final")
```

## Flash Attention 2

Flash Attention 2 VRAM उपयोग कम करता है और प्रशिक्षण की गति काफी बढ़ाता है। Ampere+ GPU (RTX 3090, RTX 4090, A100) आवश्यक है।

```bash
# Flash Attention 2 इंस्टॉल करें
pip install flash-attn --no-build-isolation
```

```python
# मॉडल लोडिंग में सक्षम करें:
model = AutoModelForCausalLM.from_pretrained(
    MODEL_NAME,
    attn_implementation="flash_attention_2",  # <-- इसे जोड़ें
    torch_dtype=torch.bfloat16,               # FA2 के लिए bf16 या fp16 आवश्यक है
    device_map="auto",
)
```

| सेटिंग                    | VRAM (7B) | गति      |
| ------------------------- | --------- | -------- |
| Standard attention (fp16) | \~22GB    | baseline |
| Flash Attention 2 (bf16)  | \~16GB    | +30%     |
| Flash Attention 2 + QLoRA | \~12GB    | +30%     |

## DoRA (Weight-Decomposed LoRA)

DoRA (PEFT >= 0.14) pre-trained weights को magnitude और direction components में विभाजित करता है। यह fine-tuning गुणवत्ता सुधारता है, खासकर छोटे ranks पर।

```python
from peft import LoraConfig

# Standard LoRA
lora_config = LoraConfig(r=64, lora_alpha=16, use_dora=False, ...)

# DoRA — समान parameters, बेहतर गुणवत्ता
lora_config = LoraConfig(r=64, lora_alpha=16, use_dora=True, ...)
# Note: DoRA standard LoRA की तुलना में ~5-10% VRAM overhead जोड़ता है
# Note: सभी मामलों में quantized (4-bit/8-bit) models के साथ compatible नहीं है
```

## Qwen2.5 और DeepSeek-R1-Distill उदाहरण

### Qwen2.5 फाइन-ट्यूनिंग

```python
MODEL_NAME = "Qwen/Qwen2.5-7B-Instruct"
# 14B के लिए: "Qwen/Qwen2.5-14B-Instruct" (QLoRA के साथ 20GB+ VRAM चाहिए)

model = AutoModelForCausalLM.from_pretrained(
    MODEL_NAME,
    quantization_config=bnb_config,
    device_map="auto",
    trust_remote_code=True,          # Qwen2.5 के लिए आवश्यक
    attn_implementation="flash_attention_2",
)
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)

# Qwen2.5 ChatML format का उपयोग करता है — apply_chat_template का उपयोग करें
messages = [
    {"role": "system", "content": "आप एक सहायक assistant हैं."},
    {"role": "user", "content": "नमस्ते!"},
    {"role": "assistant", "content": "नमस्ते! मैं आपकी कैसे मदद कर सकता हूँ?"},
]
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)
```

### DeepSeek-R1-Distill फाइन-ट्यूनिंग

DeepSeek-R1-Distill मॉडल (Qwen-7B, Qwen-14B, Llama-8B, Llama-70B) reasoning-focused हैं। अपने डोमेन के अनुसार chain-of-thought शैली को अनुकूलित करने के लिए इन्हें fine-tune करें।

```python
# DeepSeek-R1-Distill variants
MODEL_NAME = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"   # Qwen2.5 base पर 7B
# MODEL_NAME = "deepseek-ai/DeepSeek-R1-Distill-Llama-8B" # Llama3 base पर 8B
# MODEL_NAME = "deepseek-ai/DeepSeek-R1-Distill-Qwen-14B" # 14B (A100 चाहिए)

model = AutoModelForCausalLM.from_pretrained(
    MODEL_NAME,
    quantization_config=bnb_config,
    device_map="auto",
    trust_remote_code=True,
    attn_implementation="flash_attention_2",
)

# DeepSeek-R1 reasoning के लिए <think>...</think> tags का उपयोग करता है
# chain-of-thought क्षमता बनाए रखने के लिए इसे training data में रखें
example_format = """<|im_start|>user
हल करें: 15 * 23 क्या है?<|im_end|>
<|im_start|>assistant
<think>
15 * 23 = 15 * 20 + 15 * 3 = 300 + 45 = 345
</think>
उत्तर 345 है.<|im_end|>"""

# DeepSeek-R1-Distill (Qwen2.5 base) के लिए LoRA target modules
lora_config = LoraConfig(
    r=32,
    lora_alpha=16,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
                    "gate_proj", "up_proj", "down_proj"],
    use_dora=True,
    task_type="CAUSAL_LM",
)
```

## Axolotl का उपयोग करना (आसान)

Axolotl YAML configs के साथ fine-tuning को सरल बनाता है:

```bash
pip install axolotl

# कॉन्फ़िग बनाएँ
cat > config.yml << 'EOF'
base_model: mistralai/Mistral-7B-v0.1
model_type: MistralForCausalLM
tokenizer_type: LlamaTokenizer

load_in_4bit: true
adapter: qlora
lora_r: 32
lora_alpha: 16

datasets:
  - path: your_data.json
    type: alpaca

sequence_len: 4096
sample_packing: true

gradient_accumulation_steps: 4
micro_batch_size: 2
num_epochs: 3
learning_rate: 2e-4

output_dir: ./output
EOF

# ट्रेन करें
accelerate launch -m axolotl.cli.train config.yml
```

## Axolotl Config उदाहरण

### Chat Model

```yaml
base_model: mistralai/Mistral-7B-Instruct-v0.2
load_in_4bit: true
adapter: qlora

datasets:
  - path: data.json
    type: sharegpt

chat_template: mistral
```

### Code Model

```yaml
base_model: codellama/CodeLlama-7b-hf
load_in_4bit: true
adapter: qlora

datasets:
  - path: code_data.json
    type: alpaca

sequence_len: 8192  # कोड के लिए लंबा context
```

## LoRA Weights को Merge करना

प्रशिक्षण के बाद, LoRA को base model में वापस merge करें:

```python
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer

# base model लोड करें
base_model = AutoModelForCausalLM.from_pretrained(
    "mistralai/Mistral-7B-v0.1",
    torch_dtype=torch.float16,
    device_map="auto",
)

# LoRA लोड करें
model = PeftModel.from_pretrained(base_model, "./output/final")

# Merge
merged_model = model.merge_and_unload()

# merged model सहेजें
merged_model.save_pretrained("./merged_model")
tokenizer.save_pretrained("./merged_model")
```

## GGUF में बदलें

llama.cpp/Ollama के साथ उपयोग के लिए:

```bash

# llama.cpp क्लोन करें
git clone https://github.com/ggerganov/llama.cpp
cd llama.cpp

# Convert करें
python convert.py ../merged_model --outtype f16 --outfile model-f16.gguf

# Quantize करें
./quantize model-f16.gguf model-q4_k_m.gguf q4_k_m
```

## Training की निगरानी

### Weights & Biases

```python
import wandb
wandb.init(project="llm-finetune", name="mistral-7b-lora")
```

### TensorBoard

```python

# training args में
report_to="tensorboard"
logging_dir="./logs"

# देखें
tensorboard --logdir ./logs --port 6006 --bind_all
```

## सर्वोत्तम अभ्यास

### Hyperparameters

| Parameter   | 7B Model | 13B Model | 70B Model |
| ----------- | -------- | --------- | --------- |
| batch\_size | 4        | 2         | 1         |
| grad\_accum | 4        | 8         | 16        |
| lr          | 2e-4     | 1e-4      | 5e-5      |
| lora\_r     | 64       | 32        | 16        |
| epochs      | 3        | 2-3       | 1-2       |

### डेटासेट आकार

* न्यूनतम: 1,000 examples
* अच्छा: 10,000+ examples
* गुणवत्ता > मात्रा

### Overfitting से बचना

```python
training_args = TrainingArguments(
    ...
    weight_decay=0.01,
    warmup_ratio=0.03,
    save_total_limit=3,
    load_best_model_at_end=True,
    evaluation_strategy="steps",
    eval_steps=100,
)
```

## Multi-GPU Training

```bash

# accelerate के साथ
accelerate launch --multi_gpu --num_processes 4 train.py

# DeepSpeed के साथ
accelerate launch --use_deepspeed --num_processes 4 train.py
```

DeepSpeed config:

```json
{
  "bf16": {"enabled": true},
  "zero_optimization": {
    "stage": 2,
    "offload_optimizer": {"device": "cpu"}
  }
}
```

## Saving & Exporting

```bash

# LoRA adapter सहेजें
trainer.save_model("./lora_adapter")

# merged model सहेजें
merged_model.save_pretrained("./full_model")

# HuggingFace पर upload करें
huggingface-cli login
merged_model.push_to_hub("username/my-model")
```

## Troubleshooting

### OOM Errors

* batch size कम करें
* gradient accumulation बढ़ाएँ
* उपयोग करें `gradient_checkpointing=True`
* lora\_r कम करें

### Training Loss कम नहीं हो रही

* डेटा प्रारूप जाँचें
* लर्निंग रेट बढ़ाएँ
* डेटा संबंधी समस्याओं की जाँच करें

### NaN लॉस

* लर्निंग रेट कम करें
* fp16 के बजाय fp32 का उपयोग करें
* दूषित डेटा की जाँच करें

## लागत अनुमान

2026 तक CLORE.AI मार्केटप्लेस की सामान्य दरें:

| GPU       | प्रति घंटा दर | दैनिक दर | 4-घंटे का सत्र |
| --------- | ------------- | -------- | -------------- |
| RTX 3060  | \~$0.03       | \~$0.70  | \~$0.12        |
| RTX 3090  | \~$0.06       | \~$1.50  | \~$0.25        |
| RTX 4090  | \~$0.10       | \~$2.30  | \~$0.40        |
| A100 40GB | \~$0.17       | \~$4.00  | \~$0.70        |
| A100 80GB | \~$0.25       | \~$6.00  | \~$1.00        |

*कीमतें प्रदाता और मांग के अनुसार बदलती हैं। देखें* [*CLORE.AI Marketplace*](https://clore.ai/marketplace) *वर्तमान दरों के लिए।*

> 📚 यह भी देखें: [क्लाउड GPU पर LLaMA 3 को फ़ाइन-ट्यून कैसे करें — चरण-दर-चरण मार्गदर्शिका](https://blog.clore.ai/how-to-fine-tune-llama-3-cloud-gpu/)

**पैसे बचाएँ:**

* उपयोग करें **Spot** लचीले वर्कलोड के लिए मार्केट (अक्सर 30-50% सस्ता)
* से भुगतान करें **CLORE** टोकन
* विभिन्न प्रदाताओं के बीच कीमतों की तुलना करें


---

# 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/finetune-llm.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.
