Html

 <!DOCTYPE html>

<html lang="ar" dir="rtl">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Unsloth + Llama 3.1 8B Fine-tuning Guide</title>

    <style>

        * { margin: 0; padding: 0; box-sizing: border-box; }

        body {

            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;

            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);

            color: #e0e0e0; line-height: 1.8; min-height: 100vh;

        }

        .container { max-width: 1000px; margin: 0 auto; padding: 20px; }

        .header {

            text-align: center; padding: 40px 20px;

            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

            border-radius: 20px; margin-bottom: 30px;

            box-shadow: 0 10px 40px rgba(0,0,0,0.3);

        }

        .header h1 { font-size: 2.5em; color: #fff; margin-bottom: 10px; }

        .header .subtitle { font-size: 1.2em; color: #e0e0e0; opacity: 0.9; }

        .badge {

            display: inline-block; padding: 5px 15px; border-radius: 20px;

            font-size: 0.85em; font-weight: bold; margin: 5px;

        }

        .badge-free { background: #28a745; color: white; }

        .badge-gpu { background: #dc3545; color: white; }

        .badge-time { background: #ffc107; color: #000; }

        .cell {

            background: rgba(255,255,255,0.05); border-radius: 15px;

            padding: 25px; margin-bottom: 20px;

            border: 1px solid rgba(255,255,255,0.1);

            backdrop-filter: blur(10px);

        }

        .cell-header {

            display: flex; align-items: center; margin-bottom: 15px;

            padding-bottom: 10px; border-bottom: 2px solid rgba(102, 126, 234, 0.3);

        }

        .cell-number {

            background: linear-gradient(135deg, #667eea, #764ba2);

            color: white; width: 40px; height: 40px; border-radius: 50%;

            display: flex; align-items: center; justify-content: center;

            font-weight: bold; font-size: 1.1em; margin-left: 15px;

        }

        .cell-title { font-size: 1.3em; color: #fff; font-weight: 600; }

        .code-block {

            background: #1e1e2e; border-radius: 10px; padding: 20px;

            margin: 15px 0; overflow-x: auto; border-right: 4px solid #667eea;

            direction: ltr; text-align: left;

        }

        .code-block pre {

            color: #a6d189; font-family: 'Consolas', monospace;

            font-size: 0.9em; line-height: 1.6; white-space: pre-wrap;

        }

        .output-block {

            background: #1a1a2e; border-radius: 10px; padding: 20px;

            margin: 15px 0; border-right: 4px solid #28a745;

            font-family: monospace; font-size: 0.85em; color: #a6e3a1;

            direction: ltr; text-align: left; white-space: pre-wrap;

        }

        .tip-box {

            background: rgba(40, 167, 69, 0.1); border: 1px solid rgba(40, 167, 69, 0.3);

            border-radius: 10px; padding: 15px 20px; margin: 15px 0;

            display: flex; align-items: flex-start;

        }

        .warning-box {

            background: rgba(255, 193, 7, 0.1); border: 1px solid rgba(255, 193, 7, 0.3);

            border-radius: 10px; padding: 15px 20px; margin: 15px 0;

            display: flex; align-items: flex-start;

        }

        .icon { font-size: 1.5em; margin-left: 10px; }

        table {

            width: 100%; border-collapse: collapse; margin: 20px 0;

            background: rgba(255,255,255,0.03); border-radius: 10px; overflow: hidden;

        }

        th {

            background: linear-gradient(135deg, #667eea, #764ba2);

            color: white; padding: 15px; text-align: right; font-weight: 600;

        }

        td { padding: 12px 15px; border-bottom: 1px solid rgba(255,255,255,0.05); }

        tr:hover { background: rgba(255,255,255,0.02); }

        .step-divider {

            text-align: center; margin: 40px 0; position: relative;

        }

        .step-divider::before {

            content: ''; position: absolute; top: 50%; left: 0; right: 0;

            height: 2px; background: linear-gradient(90deg, transparent, #667eea, transparent);

        }

        .step-divider span {

            background: #1a1a2e; padding: 0 20px; color: #667eea;

            font-size: 1.2em; font-weight: bold; position: relative;

        }

        .footer { text-align: center; padding: 40px 20px; margin-top: 40px; border-top: 1px solid rgba(255,255,255,0.1); }

        .footer h2 { color: #667eea; margin-bottom: 15px; }

    </style>

</head>

<body>

    <div class="container">

        <div class="header">

            <h1>🤖 Unsloth + Llama 3.1 8B</h1>

            <p class="subtitle">دليل كامل لـ Fine-tuning على Google Colab</p>

            <div style="margin-top: 20px;">

                <span class="badge badge-free">مجاني 100%</span>

                <span class="badge badge-gpu">GPU T4</span>

                <span class="badge badge-time">~30 دقيقة</span>

            </div>

        </div>


        <!-- الخطوة 1 -->

        <div class="cell">

            <div class="cell-header">

                <div class="cell-number">1</div>

                <h3 class="cell-title">⚙️ إعداد GPU</h3>

            </div>

            <p>1. اذهب إلى: <strong>Runtime → Change runtime type</strong></p>

            <p>2. اختر: <strong>GPU → T4</strong></p>

            <p>3. اضغط: <strong>Save</strong></p>

            <div class="warning-box">

                <span class="icon">⚠️</span>

                <div>لا تنسَ تفعيل GPU قبل البدء!</div>

            </div>

        </div>


        <!-- الخطوة 2 -->

        <div class="cell">

            <div class="cell-header">

                <div class="cell-number">2</div>

                <h3 class="cell-title">📦 تثبيت المكتبات</h3>

            </div>

            <div class="code-block">

                <pre>%%capture

!pip install -q unsloth

!pip install -q datasets

print("✅ تم التثبيت!")</pre>

            </div>

            <div class="output-block">✅ تم التثبيت بنجاح!</div>

        </div>


        <!-- الخطوة 3 -->

        <div class="cell">

            <div class="cell-header">

                <div class="cell-number">3</div>

                <h3 class="cell-title">🤖 تحميل Llama 3.1 8B</h3>

            </div>

            <div class="code-block">

                <pre>import torch

from unsloth import FastLanguageModel


print("⏳ جاري تحميل Llama 3.1 8B...")

model, tokenizer = FastLanguageModel.from_pretrained(

    model_name="unsloth/Meta-Llama-3.1-8B-Instruct",

    max_seq_length=2048,

    dtype=None,

    load_in_4bit=True,

)


print(f"✅ تم تحميل النموذج!")

print(f"📊 البارامترات: {sum(p.numel() for p in model.parameters()):,}")

print(f"🖥️ GPU: {torch.cuda.get_device_name(0)}")</pre>

            </div>

            <div class="output-block">✅ تم تحميل النموذج!

📊 البارامترات: 8,030,000,000

🖥️ GPU: Tesla T4</div>

        </div>


        <!-- الخطوة 4 -->

        <div class="cell">

            <div class="cell-header">

                <div class="cell-number">4</div>

                <h3 class="cell-title">⚙️ إعداد LoRA</h3>

            </div>

            <div class="code-block">

                <pre>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_rslora=True,

    use_gradient_checkpointing="unsloth",

    random_state=3407,

)


trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)

total = sum(p.numel() for p in model.parameters())

print(f"🎯 قابلة للتدريب: {trainable:,} / {total:,} ({100*trainable/total:.2f}%)")</pre>

            </div>

            <div class="output-block">🎯 بارامترات قابلة للتدريب: 41,943,040 / 8,030,000,000 (0.52%)</div>

        </div>


        <!-- الخطوة 5 -->

        <div class="cell">

            <div class="cell-header">

                <div class="cell-number">5</div>

                <h3 class="cell-title">📝 إنشاء بيانات موقعك</h3>

            </div>

            <div class="tip-box">

                <span class="icon">💡</span>

                <div>عدّل هذه البيانات حسب موقعك!</div>

            </div>

            <div class="code-block">

                <pre>import json


data = [

    {

        "instruction": "ما هي سياسة الإرجاع في موقعنا؟",

        "input": "",

        "output": "يمكنك إرجاع أي منتج خلال 14 يوماً من تاريخ الشراء."

    },

    {

        "instruction": "ما هي أوقات عمل خدمة العملاء؟",

        "input": "",

        "output": "من الأحد إلى الخميس، 9 صباحاً حتى 6 مساءً."

    },

    {

        "instruction": "كيف أتتبع طلبي؟",

        "input": "",

        "output": "ادخل إلى حسابك ← الطلبات ← تتبع الشحنة."

    }

]


with open("website_data.jsonl", "w", encoding="utf-8") as f:

    for item in data:

        f.write(json.dumps(item, ensure_ascii=False) + "\n")


print(f"✅ تم إنشاء {len(data)} أمثلة")</pre>

            </div>

        </div>


        <!-- الخطوة 6 -->

        <div class="cell">

            <div class="cell-header">

                <div class="cell-number">6</div>

                <h3 class="cell-title">🔧 تحضير البيانات</h3>

            </div>

            <div class="code-block">

                <pre>from datasets import load_dataset


dataset = load_dataset("json", data_files="website_data.jsonl", split="train")


alpaca_prompt = """Below is an instruction...

### Instruction:

{}

### Input:

{}

### Response:

{}"""


def formatting_prompts_func(examples):

    texts = []

    for instruction, input_text, output in zip(

        examples["instruction"], examples["input"], examples["output"]

    ):

        text = alpaca_prompt.format(instruction, input_text, output) + tokenizer.eos_token

        texts.append(text)

    return {"text": texts}


dataset = dataset.map(formatting_prompts_func, batched=True)

print("✅ تم تحضير البيانات!")</pre>

            </div>

        </div>


        <!-- الخطوة 7 -->

        <div class="cell">

            <div class="cell-header">

                <div class="cell-number">7</div>

                <h3 class="cell-title">🏋️ التدريب</h3>

            </div>

            <div class="code-block">

                <pre>from trl import SFTTrainer

from transformers import TrainingArguments

from unsloth import is_bfloat16_supported


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=5,

        max_steps=60,  # زد إلى 300-500 للإنتاج

        learning_rate=2e-4,

        fp16=not is_bfloat16_supported(),

        bf16=is_bfloat16_supported(),

        logging_steps=1,

        optim="adamw_8bit",

        weight_decay=0.01,

        lr_scheduler_type="linear",

        seed=3407,

        output_dir="outputs",

        report_to="none",

    ),

)


trainer_stats = trainer.train()


print(f"✅ اكتمل التدريب!")

print(f"📉 الخسارة: {trainer_stats.metrics['train_loss']:.4f}")

print(f"⏱️ الوقت: {trainer_stats.metrics['train_runtime']:.0f} ثانية")</pre>

            </div>

            <div class="output-block">{'loss': 2.4567, 'learning_rate': 1.8e-04, 'epoch': 0.08}

{'loss': 1.8923, 'learning_rate': 1.6e-04, 'epoch': 0.17}

...

{'loss': 0.0891, 'learning_rate': 0.0e+00, 'epoch': 0.92}


✅ اكتمل التدريب!

📉 الخسارة: 0.0891

⏱️ الوقت: 847 ثانية (~14 دقيقة)</div>

        </div>


        <!-- الخطوة 8 -->

        <div class="cell">

            <div class="cell-header">

                <div class="cell-number">8</div>

                <h3 class="cell-title">🧪 اختبار النموذج</h3>

            </div>

            <div class="code-block">

                <pre>FastLanguageModel.for_inference(model)


test_prompt = "ما هي سياسة الإرجاع في موقعنا؟"

full_prompt = alpaca_prompt.format(test_prompt, "", "")


inputs = tokenizer([full_prompt], return_tensors="pt").to("cuda")


outputs = model.generate(

    **inputs,

    max_new_tokens=128,

    use_cache=True,

    temperature=0.7,

)


response = tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]

response_text = response.split("### Response:")[-1].strip()


print(f"❓ السؤال: {test_prompt}")

print(f"💡 الرد: {response_text}")</pre>

            </div>

            <div class="output-block">❓ السؤال: ما هي سياسة الإرجاع في موقعنا؟


💡 الرد: يمكنك إرجاع أي منتج خلال 14 يوماً من تاريخ الشراء.</div>

        </div>


        <!-- الخطوة 9 -->

        <div class="cell">

            <div class="cell-header">

                <div class="cell-number">9</div>

                <h3 class="cell-title">💾 تصدير GGUF لـ Ollama</h3>

            </div>

            <div class="code-block">

                <pre>model.save_pretrained_gguf(

    "gguf_model",

    tokenizer,

    quantization_method="q5_k_m",

)


print("✅ تم التصدير!")

!ls -lh gguf_model/</pre>

            </div>

            <div class="output-block">✅ تم التصدير!

-rw-r--r-- 1 root root 5.7G unsloth.Q5_K_M.gguf</div>

        </div>


        <!-- الخطوة 10 -->

        <div class="cell">

            <div class="cell-header">

                <div class="cell-number">10</div>

                <h3 class="cell-title">☁️ حفظ في Google Drive</h3>

            </div>

            <div class="code-block">

                <pre>from google.colab import drive

drive.mount('/content/drive')


!mkdir -p /content/drive/MyDrive/my-website-ai

!cp -r gguf_model/* /content/drive/MyDrive/my-website-ai/

!cp website_data.jsonl /content/drive/MyDrive/my-website-ai/


print("✅ تم الحفظ في Google Drive!")</pre>

            </div>

        </div>


        <!-- الخطوة 11 -->

        <div class="cell">

            <div class="cell-header">

                <div class="cell-number">11</div>

                <h3 class="cell-title">🦙 Modelfile لـ Ollama</h3>

            </div>

            <div class="code-block">

                <pre>FROM ./unsloth.Q5_K_M.gguf


SYSTEM """أنت مساعد ذكي متخصص في موقعنا. 

أجب على أسئلة المستخدمين بناءً على معلومات الموقع فقط."""


PARAMETER temperature 0.7

PARAMETER top_p 0.9

PARAMETER top_k 40

PARAMETER num_ctx 2048</pre>

            </div>

            <div class="tip-box">

                <span class="icon">💡</span>

                <div>شغّل على جهازك: ollama create my-website-ai -f Modelfile</div>

            </div>

        </div>


        <!-- ملخص -->

        <div class="step-divider"><span>✅ ملخص</span></div>


        <div class="cell">

            <h3 style="color: #667eea; margin-bottom: 15px;">📊 جدول المقارنة</h3>

            <table>

                <tr><th>الخطوة</th><th>الوصف</th><th>الوقت</th></tr>

                <tr><td>1</td><td>إعداد GPU</td><td>1 دقيقة</td></tr>

                <tr><td>2</td><td>تثبيت المكتبات</td><td>3 دقائق</td></tr>

                <tr><td>3</td><td>تحميل النموذج</td><td>2 دقائق</td></tr>

                <tr><td>4</td><td>إعداد LoRA</td><td>30 ثانية</td></tr>

                <tr><td>5-6</td><td>إعداد البيانات</td><td>1 دقيقة</td></tr>

                <tr><td>7</td><td>التدريب (60 خطوة)</td><td>~14 دقيقة</td></tr>

                <tr><td>8</td><td>الاختبار</td><td>30 ثانية</td></tr>

                <tr><td>9</td><td>تصدير GGUF</td><td>5 دقائق</td></tr>

                <tr><td>10</td><td>حفظ في Drive</td><td>2 دقائق</td></tr>

                <tr><th colspan="2">الإجمالي</th><th>~30 دقيقة</th></tr>

            </table>

        </div>


        <div class="cell">

            <h3 style="color: #667eea; margin-bottom: 15px;">⚠️ حلول المشاكل الشائعة</h3>

            <table>

                <tr><th>المشكلة</th><th>الحل</th></tr>

                <tr><td>CUDA out of memory</td><td>قلّل max_seq_length إلى 1024</td></tr>

                <tr><td>Runtime disconnected</td><td>Runtime → Restart session</td></tr>

                <tr><td>loss = nan</td><td>قلّل learning_rate إلى 1e-4</td></tr>

                <tr><td>التدريب بطيء</td><td>طبيعي على T4، استخدم A100 إن أمكن</td></tr>

                <tr><td>النتيجة غير دقيقة</td><td>زد max_steps وأضف بيانات أكثر</td></tr>

            </table>

        </div>


        <div class="footer">

            <h2>🎉 بالتوفيق!</h2>

            <p>إذا واجهت أي مشكلة، راجع قسم حلول المشاكل أعلاه</p>

            <p style="margin-top: 10px; opacity: 0.7;">تم إنشاء هذا الدليل بتاريخ 2026-06-10</p>

        </div>

    </div>

</body>

</html>

Comments