Software Engineer Encyclopedia
0%
Domain 11 · LLM Engineering & AI Integration · Topic 11.4

LLM Engineering المتقدم

Advanced LLM Engineering

Inference internals, model routing, multimodal, local models, optimization and fine-tuning trade-offs.

  • Advanced
  • ~15 min read
  • 15 sections
  • 6 code examples
  • 1 diagrams
  • 7 questions
  • Priority L2 · Essential
  • LLM inference · .NET · Local models

بعد الدرس ده هتقدر

  • تصمم model gateway بـ routing وfallback وretry وbudget.
  • تفرّق بين التعامل مع 429 والتعامل مع 5xx.
  • تشرح LoRA وQLoRA بالأرقام وتقرر إمتى fine-tuning وإمتى RAG وإمتى prompt.

المتطلبات قبل ما تبدأ

Backend بـ .NET + أساسيات الـ ML والـ embeddings من المجال 10.

01

Inference lifecycle: Prefill و Decode و KV Cache

Understand latency and throughput
Deep dive

في inference، prefill يعالج prompt tokens ويحسب representations، و decode يولد token تلو الآخر. لذلك طول input يؤثر على prefill، وطول output يؤثر على decode. KV cache يحتفظ بمفاتيح وقيم attention السابقة لتجنب إعادة الحساب لكل token، لكنه يستهلك ذاكرة تتزايد مع context و batch/model dimensions.

الـ batching يحسن throughput لكنه قد يزيد queueing latency. Continuous batching يستغل GPU بشكل أفضل في serving engines، لكنه تفاصيل تشغيلية متقدمة. كمهندس تكامل، افهم هذه المفاهيم لتفسر لماذا context طويل أو concurrency عالي يرفع latency والتكلفة.

02

Model gateway في رسمة

An LLM gateway layer
Basics
Chat featureBatch summarizerAgentLLM gateway (IChatClient pipeline)route by task/tier · budget per tenantprompt cache · retries · fallbackinput/output guardrails · redactionOTel GenAI spans · cost attributionLarge modelSmall / cheap modelSelf-hosted (vLLM/Ollama)
One internal gateway: routing, budgets, caching, guardrails and telemetry for every model call
03

Model Routing و Fallback و Local Inference

Route by task and constraints
Practical

Model routing يختار model حسب task complexity، privacy، modality، latency budget، token budget، أو availability. ابدأ بقواعد deterministic قابلة للتفسير؛ semantic routing يحتاج evaluation ومراقبة. Fallback لا ينبغي أن يخفض safety أو permissions؛ حافظ على نفس output contract والـ policy gates.

Local models مثل Ollama/llama.cpp قد تناسب development أو privacy-sensitive workloads، لكن قِس hardware capacity، quantization quality، context limit، concurrency، updates، security patching، و observability. لا تعتبر local = zero cost.

Provider Routing Policy و Canary

Routing policy قد تعتمد على task class، sensitivity، context length، budget، or provider health. ابدأ بقواعد واضحة قابلة للتدقيق. لا توجه البيانات الحساسة إلى local/hosted model دون policy check. Canary نسبة صغيرة من traffic، لكن لا ترسل sensitive cohorts إلى candidate غير معتمد.

قارن success/quality/latency/cost، وليس response time فقط. عند fallback تأكد من أن tool schemas و structured output متوافقة. سجل route decision reason و candidate model version.

Model Gateway: Routing و Fallback و Retry و Budget في مكان واحد

في الإنتاج مفيش «نداء موديل» واحد. فيه مزوّد بيقع، rate limits، موديل غالي لمهمة سهلة، وميزانية لكل عميل. الـ gateway هو الطبقة اللي بتحط القرارات دي في مكان واحد بدل ما تتبعتر في الكود. المحاكاة دي بتشغّل 2000 request على مزوّدين وهميين بأعطال عشوائية.

Pythongateway.py — cascade routing, retry with backoff on 429, provider fallback, per-tenant budgetExecuted ✓
import random
random.seed(11)

PROVIDERS = {   # name: (cost per request in cents, mean latency s, P(rate limited), P(outage error), quality on hard tasks)
    "small@A": (0.02, 0.4, 0.05, 0.01, 0.55),
    "large@A": (0.60, 2.0, 0.10, 0.01, 0.95),
    "large@B": (0.75, 2.4, 0.02, 0.02, 0.94),   # second provider: pricier, used as fallback
}

class RateLimited(Exception): pass
class Unavailable(Exception): pass

def call(provider, hard):
    cost, latency, p429, p5xx, quality = PROVIDERS[provider]
    r = random.random()
    if r < p429: raise RateLimited()
    if r < p429 + p5xx: raise Unavailable()
    correct = random.random() < (quality if hard else 0.98)
    return correct, cost, random.expovariate(1 / latency)

def with_retry(provider, hard, stats, attempts=3):
    waited = 0.0
    for attempt in range(attempts):
        try:
            ok, cost, latency = call(provider, hard)
            return ok, cost, latency + waited
        except RateLimited:
            stats["retries"] += 1
            waited += min(8, 0.5 * 2 ** attempt) * random.uniform(0.5, 1.0)   # exponential backoff + jitter
        except Unavailable:
            break                                                              # do not hammer a broken provider
    raise Unavailable()

def gateway(hard, looks_hard, budget, stats, strategy):
    chain = {"always large": ["large@A", "large@B"],
             "cascade":      (["large@A", "large@B"] if looks_hard else ["small@A", "large@A", "large@B"])}[strategy]
    for provider in chain:
        if budget["left"] < PROVIDERS[provider][0]:
            stats["budget_stops"] += 1
            return None
        try:
            ok, cost, latency = with_retry(provider, hard, stats)
        except Unavailable:
            stats["fallbacks"] += 1
            continue
        budget["left"] -= cost
        stats["by_provider"][provider] = stats["by_provider"].get(provider, 0) + 1
        return ok, cost, latency
    return None

def simulate(strategy, n=2000, budget_cents=400):
    stats = {"retries": 0, "fallbacks": 0, "budget_stops": 0, "by_provider": {}}
    budget, served, correct, cost, lat = {"left": budget_cents}, 0, 0, 0.0, []
    for _ in range(n):
        hard = random.random() < 0.2                                  # 20% of traffic is genuinely hard
        looks_hard = hard if random.random() < 0.85 else not hard     # the classifier is right 85% of the time
        out = gateway(hard, looks_hard, budget, stats, strategy)
        if out:
            served += 1; correct += out[0]; cost += out[1]; lat.append(out[2])
    lat.sort()
    print(f"{strategy:<13} served={served:>4}/{n}  correct={correct / max(served, 1):.3f}  cost={cost:6.1f}c  "
          f"p50={lat[len(lat) // 2]:.2f}s p95={lat[int(len(lat) * .95)]:.2f}s  retries={stats['retries']} fallbacks={stats['fallbacks']} "
          f"budget_stops={stats['budget_stops']}  {stats['by_provider']}")

simulate("always large")
simulate("cascade")
ConsoleOutput — captured from a real run
always large  served= 663/2000  correct=0.970  cost= 399.5c  p50=1.49s p95=5.70s  retries=76 fallbacks=13 budget_stops=1336  {'large@A': 652, 'large@B': 11}
cascade       served=2000/2000  correct=0.961  cost= 398.1c  p50=0.46s p95=4.01s  retries=150 fallbacks=31 budget_stops=0  {'small@A': 1386, 'large@A': 601, 'large@B': 13}

«always large» خلّص الميزانية قبل ما يخدم كل الطلبات: الجودة عالية للي اتخدموا، والباقي اترفض. الـ cascade خدم الكل بجزء من التكلفة وبـ latency أقل بكتير — بتمن نزول بسيط في الدقة، جاي من الطلبات الصعبة اللي الـ classifier غلط فيها وبعتها للموديل الصغير.

ده trade-off مش حل سحري: جودة الـ router بتحدد كل حاجة. الأنماط الشائعة لتحديد «صعب ولا سهل»: classifier صغير، قواعد (طول الـ input، نوع المهمة)، أو تصعيد بناءً على ثقة الموديل الصغير أو فشل الـ validation.

429 ≠ 5xx: الـ rate limit مؤقت فبنستنى ونعيد (backoff + jitter عشان الـ clients ما يرجعوش كلهم في نفس اللحظة). العطل بنسيبه ونروح للمزوّد التاني فورًا. خلط الاتنين بيدّي إما retries بتزوّد الضغط على مزوّد واقع، أو fallback مالوش لازمة.

الـ budget بيتفحص قبل النداء: ده الفرق بين «فاتورة مفاجئة» و«429 برسالة واضحة للـ tenant». الأسعار والنسب هنا أرقام محاكاة — استبدلها بقياساتك.

Model Routing, Cascades and Fallbacks

Model router يختار model بناءً على task complexity، modality، latency budget، privacy، و cost. Cascade قد يبدأ بنموذج أرخص، ثم يصعّد الحالات غير الواثقة أو التي تفشل schema/evaluation. لكن confidence self-reported من LLM ليست reliable تلقائيًا؛ استخدم deterministic signals مثل schema validity، retrieval coverage، task classifier validated، or verifier.

Routing errors لها تكلفة: wrong cheap answer قد يكون أسوأ من expensive fallback. قِس quality/cost/latency jointly، وراقب route distribution drift. ضع circuit breaker لكل provider، وأبقِ fallback compatible مع output contract.

PythonSpend expensive reasoning only where needed
def route(task: str, needs_private_data: bool, budget_ms: int) -> str:
    if needs_private_data:
        return 'approved-local-model'
    if task == 'simple_classification' and budget_ms < 800:
        return 'small-fast-model'
    return 'quality-model'

print(route('simple_classification', False, 500))
04

Multimodal AI و Structured Outputs

Text, image, audio and schema-constrained generation
Practical

Multimodal models قد تستقبل text/image/audio/video حسب provider. كل modality لها limits و preprocessing و cost؛ image resolution و audio duration تؤثر في tokenization/latency. احصل على consent وحقوق المحتوى، وافحص الملفات قبل إرسالها.

Structured outputs و function calling يفصلان response عن free text. تحقق من JSON schema، ثم domain rules، ثم authorization. لا تسمح لاسم tool أو argument يحدد tenant أو user identity؛ خذها من authenticated context.

05

Optimization: Caching و Batching و Quantization

Reduce cost without silent quality loss
Deep dive

Optimization يبدأ بقياس: tokens/request، p95 latency، provider errors، cache hit rate، output usefulness. Prompt caching يقلل تكلفة prefix المتكرر عند دعم provider. Semantic cache قد يجيب عن query مشابهة، لكنه خطر إذا تجاهل tenant/ACL/freshness/model version. Batching مناسب للعمليات غير التفاعلية، ولا يناسب دائمًا real-time UX.

Quantization تقلل precision وحجم weights، وقد تؤثر في reasoning/quality. LoRA fine-tuning يضيف adapters بتكلفة تدريب أقل من full fine-tuning، لكنه ما زال يحتاج data governance و evaluation و deployment strategy. قارن against prompting/RAG قبل التدريب.

Caching Semantics for AI Systems

AI caching يشمل exact response cache، semantic cache، prompt prefix cache، و embedding cache. Cache key يجب أن يشمل tenant/security scope، normalized request، model/version، prompt version، retrieval/index version، locale، و relevant parameters. Semantic cache أخطر من exact cache لأنه قد يعيد جوابًا لسؤال “قريب” لكنه مختلف في رقم أو permission أو time-sensitive fact.

حدد TTL و invalidation و privacy retention، ولا تخزن response تحتوي PII بلا policy. لا تجعل cache bypass authorization؛ افحص access قبل إرجاع cached result. قس hit rate مع answer correctness؛ cache hit ليس نجاحًا إذا stale أو cross-tenant.

PythonCache keys must include every behavior-changing input
import hashlib, json

def ai_cache_key(payload: dict) -> str:
    canonical = json.dumps(payload, sort_keys=True, separators=(',', ':'))
    return hashlib.sha256(canonical.encode()).hexdigest()

key = ai_cache_key({'tenant':'t1','model':'m3','prompt':'v7','index':'idx42','query':'refund status'})
print(key[:16])
06

LLM Engineering Capstone

A versioned, observable, provider-portable assistant
Practical

صمم خدمة ‎.NET فيها IChatClient abstraction، model router، provider adapters، structured response، SSE streaming، bounded tool registry، tenant-aware RAG، و human approval. ضع Python ingestion worker منفصلًا فقط عندما يضيف قيمة فعلية، واستخدم queue للوثائق الطويلة.

سلّم architecture diagram، ADR لاختيار provider/vector store، golden eval dataset، threat model، cost model، load test، dashboard، rollback procedure، و README تشغيل محلي. هذه هي النقلة من API demo إلى AI feature هندسية.

07

Inference Capacity Planning

Tokens per second and queueing
Deep dive

قدّر demand من concurrent users × requests/user × average input/output tokens. قِس prefill latency و decode throughput حيث يوفر serving stack هذه القياسات. Batch يزيد throughput لكنه قد يزيد wait time؛ streaming يحسن perceived latency ولا يقلل بالضرورة total compute. Long context يرفع memory pressure و prefill work.

ضع concurrency cap و queue timeout و max tokens، وراقب queue depth و GPU utilization و OOM. عند saturation، reject/degrade gracefully بدل قبول requests تتراكم إلى أجل غير مسمى.

08

Fine-tuning Decision Record

When training is justified
Deep dive

قبل fine-tuning، أثبت أن prompt/RAG/tools لم تحل المشكلة. اجمع data عالية الجودة ومصرح بها، افصل train/validation/test، افحص PII/copyright، وقس baseline. LoRA يقلل trainable parameters لكنه لا يلغي الحاجة إلى GPU، evaluation، model registry، safety review، و rollback. لا fine-tune لإضافة معلومات تتغير كل يوم؛ استخدم retrieval.

قرار fine-tuning يجب أن يذكر expected gain، data rights، compute budget، eval criteria، serving cost، و maintenance owner. لو لا تستطيع قياس التحسن، لا تبدأ التدريب.

09

Local Model Operations

Serving is software operations
Basics

تشغيل local model يتطلب model artifact provenance، license review، sandboxing، network isolation، quantization compatibility، hardware sizing، patching، و observability. لا تسمح بتحميل arbitrary model files من user input. افحص memory requirements قبل deployment.

Local inference قد يكون ممتازًا للتطوير أو privacy scenarios، لكنه ليس تلقائيًا أرخص أو أسرع من managed API. اعمل benchmark حقيقيًا مع concurrency والـ context lengths المتوقعة.

10

LoRA بالأرقام: ليه Fine-tuning بقى ممكن على GPU واحد

Low-rank updates: parameter counts and a rank experiment in NumPy — executed
Deep dive

الـ full fine-tuning بيعدّل كل وزن في الموديل: مليارات الـ parameters، ونسخة كاملة من الموديل لكل مهمة. LoRA مبني على ملاحظة: التغيير المطلوب في مصفوفة الأوزان لمهمة معيّنة غالبًا low-rank — يعني ينفع يتمثّل بحاصل ضرب مصفوفتين صغيرتين.

W' = W + ΔW , ΔW ≈ B·A (W: d×k frozen, B: d×r, A: r×k, r ≪ d)
Pythonlora_math.py — how many parameters, and how well a rank-r update can fit a taskExecuted ✓
import numpy as np
rng = np.random.default_rng(0)

d = k = 4096                                         # one attention projection matrix in a mid-size model
print(f"full update of one {d}x{k} matrix: {d * k:,} trainable parameters")
for r in (4, 8, 16, 64):
    n = r * (d + k)
    print(f"  LoRA rank {r:>2}: {n:>9,} parameters  ({100 * n / (d * k):.2f}% of the full matrix)")

# ---- experiment: the "ideal" task update has low intrinsic rank plus a little noise ----
d = 256
true_rank = 6
delta = rng.normal(size=(d, true_rank)) @ rng.normal(size=(true_rank, d)) + 0.05 * rng.normal(size=(d, d))

U, S, Vt = np.linalg.svd(delta)
print(f"\nideal update is {d}x{d}; share of its energy captured by the best rank-r approximation:")
for r in (1, 2, 4, 6, 8, 16):
    approx = (U[:, :r] * S[:r]) @ Vt[:r]
    captured = 1 - np.linalg.norm(delta - approx) ** 2 / np.linalg.norm(delta) ** 2
    print(f"  r={r:>2}: {captured:6.1%}   trainable={r * 2 * d:>5} vs full={d * d}")

# ---- merging: at inference the adapter can be folded into W, so there is no extra latency ----
W = rng.normal(size=(d, d))
B, A = U[:, :8] * S[:8], Vt[:8]
x = rng.normal(size=d)
print("\nmerged weights give the same output as base + adapter:", np.allclose((W + B @ A) @ x, W @ x + B @ (A @ x)))

# ---- quantisation: what 4-bit storage does to memory (weights only) ----
params = 7e9
for bits in (32, 16, 8, 4):
    print(f"  7B parameters at {bits:>2}-bit: {params * bits / 8 / 1e9:5.1f} GB")
ConsoleOutput — captured from a real run
full update of one 4096x4096 matrix: 16,777,216 trainable parameters
  LoRA rank  4:    32,768 parameters  (0.20% of the full matrix)
  LoRA rank  8:    65,536 parameters  (0.39% of the full matrix)
  LoRA rank 16:   131,072 parameters  (0.78% of the full matrix)
  LoRA rank 64:   524,288 parameters  (3.12% of the full matrix)

ideal update is 256x256; share of its energy captured by the best rank-r approximation:
  r= 1:  21.0%   trainable=  512 vs full=65536
  r= 2:  40.9%   trainable= 1024 vs full=65536
  r= 4:  75.3%   trainable= 2048 vs full=65536
  r= 6: 100.0%   trainable= 3072 vs full=65536
  r= 8: 100.0%   trainable= 4096 vs full=65536
  r=16: 100.0%   trainable= 8192 vs full=65536

merged weights give the same output as base + adapter: True
  7B parameters at 32-bit:  28.0 GB
  7B parameters at 16-bit:  14.0 GB
  7B parameters at  8-bit:   7.0 GB
  7B parameters at  4-bit:   3.5 GB

عدد الـ parameters: rank 8 على مصفوفة 4096×4096 = أقل من نصف في المية من حجمها. الـ adapter كله بيبقى ملف بعشرات الميجابايت بدل نسخة كاملة من الموديل — وتقدر تبدّل بين adapters لمهام مختلفة فوق نفس الـ base model.

تجربة الـ rank: التحديث «المثالي» اتبنى بـ rank 6 + ضوضاء. الـ energy المتلقطة بتطلع بسرعة لحد r=6 وبعدها الزيادة تافهة. ده معناه إن اختيار r أكبر من الـ rank الحقيقي للمهمة بيزوّد parameters من غير فايدة — وفي الواقع الـ rank الحقيقي مجهول فبتجرّب (8 و16 نقط بداية شائعة) وتقيس على eval set.

الـ merge: بعد التدريب W + BA بتتحسب مرة وتتخزن، فالـ inference بنفس سرعة الموديل الأصلي.

QLoRA = LoRA فوق base model متحمّل بـ 4-bit quantization: الـ base المجمّد بياخد ربع الذاكرة تقريبًا (شوف الجدول الأخير) والـ adapters بتتدرّب بدقة كاملة. ده اللي خلّى fine-tuning موديل 7B ممكن على GPU استهلاكي. الأرقام دي للأوزان بس — الـ activations والـ KV cache والـ optimizer state بياخدوا ذاكرة إضافية.

عايز تغيّرالأداة الصحليه
المعلومات اللي الموديل يعرفها (مستندات، بيانات حديثة)RAGبتتحدّث من غير تدريب، وفيها citations وصلاحيات
شكل الـ output أو التعليماتPrompt + structured output + few-shotأرخص وأسرع تجربة؛ ابدأ هنا دايمًا
أسلوب/نبرة ثابتة أو مهمة ضيقة متكررة بدقة أعلىFine-tuning (LoRA)لما عندك مئات–آلاف الأمثلة الجيدة والـ prompt وصل لسقفه
تكلفة/latency لمهمة محددةFine-tune موديل صغير على outputs موديل كبير (distillation)موديل أصغر متخصص يوصل لجودة قريبة بجزء من التكلفة
Fine-tuning مش بيضيف معلومات بشكل موثوق

لو هدفك «الموديل يعرف منتجاتنا»، الـ fine-tuning هيخليه يتكلم بأسلوب اللي يعرف، وهيألّف التفاصيل. المعلومات مكانها الـ context (RAG). وكل fine-tune محتاج eval set قبل وبعد، وإلا مش هتعرف هل اتحسّن ولا بس اتغيّر.

عندك 300 مثال ممتاز لتحويل ملاحظات الأطباء لصيغة تقرير ثابتة، والـ few-shot prompt بيدّي 85% والمطلوب 95%. الخطوة المنطقية؟

مزوّد الـ LLM رجّع 429. التصرف الصح في الـ gateway؟

11

اختبر فهمك

Knowledge Check
Practical
ما وظيفة KV cache؟
الاحتفاظ بمفاتيح وقيم attention السابقة لتجنب إعادة حسابها أثناء decode، مقابل استهلاك ذاكرة.
هل fallback model يمكنه تخطي نفس safety gates؟
لا. يجب أن يحافظ على نفس authorization و privacy و output validation والسياسات.

اختبار الإتقان المهني

متى يكون RAG أنسب من fine-tuning لتحديث المعرفة؟
عندما تكون الحقائق متغيرة أو تحتاج citations و ACL؛ fine-tuning ليس قاعدة معرفة قابلة للتحديث الفوري.
هل 4-bit quantization تعني تلقائيًا inference أسرع بأربع مرات؟
لا؛ السرعة تعتمد على kernels و hardware و memory bandwidth والـ batching وقد توجد quality trade-offs.
ما الذي يجب أن يتضمنه AI cache key؟
كل مدخل يغير السلوك مثل tenant/model/prompt/index versions واللغة والمعاملات، مع authorization قبل إرجاع cached data.
12

Fine-Tuning Workflow and Dataset Construction

Quality data dominates clever training tricks
Deep dive

ابدأ بتحديد behavior gap measurable لا يحله prompting أو retrieval. اجمع examples تمثل input distribution، واكتب labeling guideline، وراجع disagreement، وأزل duplicates/PII/contamination. قس train/validation split على مستوى source/entity لتجنب leakage. synthetic data مفيدة لتوسيع coverage لكنها قد تكرر أخطاء teacher model أو تضيق diversity.

قبل training احسب memory: weights + gradients + optimizer states + activations + temporary buffers. Mixed precision و gradient checkpointing و gradient accumulation و LoRA تقلل الموارد بطرق مختلفة مع trade-offs. احتفظ dataset fingerprint و training config و base model revision و seed و checkpoint metadata.

PythonQuality data dominates clever training tricks
def estimate_full_finetune_gib(parameters: int, bytes_per_param_total: float = 16.0) -> float:
    # Rough planning estimate only; actual optimizer/runtime overhead varies.
    return parameters * bytes_per_param_total / (1024**3)
print(round(estimate_full_finetune_gib(7_000_000_000), 1), 'GiB rough estimate')
13

Quantization: Weights, Activations and Calibration

Smaller representation, measurable quality trade-off
Deep dive

Quantization maps floating-point values إلى lower-bit representations. Weight-only quantization يقلل model weight memory، بينما activation quantization يغير intermediate tensors وقد يحتاج calibration/quantization-aware training. INT8/INT4 formats ليست متساوية في kernels أو accuracy. Group size، symmetric/asymmetric scales، outlier handling، و hardware kernels تؤثر على النتيجة.

قارن perplexity أو task-specific quality على golden set، memory peak، throughput، TTFT، و tail latency على target hardware. لا تفترض أن 4-bit يعني 4x أسرع؛ kernel support و memory bandwidth و batch size قد يغيروا النتيجة. احتفظ quantization config مع artifact.

PythonSmaller representation, measurable quality trade-off
# Storage lower bound for raw weights only (ignores scales/metadata/runtime buffers)
params = 7_000_000_000
for bits in (16, 8, 4):
    gib = params * bits / 8 / (1024**3)
    print(bits, round(gib, 2), 'GiB')
14

Fine-tuning عملي بـ LoRA و PEFT وقياس قبل/بعد

Train a small adapter and compare on a held-out set
Practical

استخدم fine-tuning لما السلوك أو صيغة المهمة ما تتحسنش كفاية بالـ prompt/examples، وبعد ما يتوفر dataset مرخّص ومقسوم. لو المطلوب حقائق جديدة متغيرة، RAG أنسب غالبًا. LoRA تجمد أغلب أوزان base model وتضيف مصفوفتين منخفضتي الرتبة؛ ده يقلل trainable parameters لكنه لا يلغي memory أو التقييم.

المعمل يستخدم بيانات محلية مصطنعة للتعلّم، ويطبع accuracy قبل/بعد على نفس held-out split ونسبة الأوزان القابلة للتدريب. الكود يحتاج PyTorch و Transformers و PEFT وملفات model موثوقة محلية/من Hub؛ لا يحتاج API key. target_modules تختلف حسب architecture.

Pythonpeft_lora_classifier.py — fixed test set and parameter count
import os
import torch
from peft import LoraConfig, TaskType, get_peft_model
from transformers import AutoModelForSequenceClassification, AutoTokenizer

model_id = os.environ["BASE_MODEL"]
train_rows = [
    ("delivery was quick and the package was great", 1),
    ("support solved my issue", 1), ("works as described", 1),
    ("happy with this purchase", 1), ("item arrived damaged", 0),
    ("billing was wrong and nobody replied", 0), ("the app crashes every time", 0),
    ("this was a frustrating experience", 0),
]
test_rows = [
    ("the product is excellent", 1), ("I regret ordering this", 0),
    ("fast service and a helpful answer", 1), ("it stopped working after one day", 0),
]
torch.manual_seed(19)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
tokenizer = AutoTokenizer.from_pretrained(model_id)
base = AutoModelForSequenceClassification.from_pretrained(model_id, num_labels=2).to(device)

def score(model, rows):
    model.eval()
    correct = 0
    with torch.no_grad():
        for text, label in rows:
            batch = tokenizer(text, return_tensors="pt", truncation=True, max_length=128)
            batch = {key: value.to(device) for key, value in batch.items()}
            correct += model(**batch).logits.argmax(-1).item() == label
    return correct / len(rows)

before = score(base, test_rows)
model = get_peft_model(base, LoraConfig(
    task_type=TaskType.SEQ_CLS, r=4, lora_alpha=8, lora_dropout=0.05,
    target_modules=["q_lin", "v_lin"],  # this configuration assumes DistilBERT-style attention modules
    modules_to_save=["pre_classifier", "classifier"],
)).to(device)
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
total = sum(p.numel() for p in model.parameters())
optimizer = torch.optim.AdamW((p for p in model.parameters() if p.requires_grad), lr=2e-4)
for epoch in range(8):
    model.train()
    for text, label in train_rows:
        batch = tokenizer(text, return_tensors="pt", truncation=True, max_length=128)
        batch = {key: value.to(device) for key, value in batch.items()}
        batch["labels"] = torch.tensor([label], device=device)
        optimizer.zero_grad(set_to_none=True)
        loss = model(**batch).loss
        loss.backward()
        optimizer.step()
after = score(model, test_rows)
print(f"test_accuracy_before={before:.3f}")
print(f"test_accuracy_after={after:.3f}")
print(f"trainable={trainable:,}/{total:,} ({100 * trainable / total:.2f}%)")

أربع test cases لا تثبت تعميمًا؛ والـ classification head قد يبدأ عشوائيًا. استخدم بيانات أكبر وممثلة، baseline بسيط، وفحص false positives/negatives حسب الشرائح. انخفاض loss وحده مش فائدة للمنتج.

حالة التحقق

المعمل لم يُشغّل أو يُعمل له compile في هذه الدفعة؛ لم تُسجّل نتيجة قبل/بعد. يلزم model متوافق ومراجعة أسماء الطبقات والـ license والـ hardware والنسخ.

تمارين وحلول ومشروع adapter

أساسي: احسب نسبة trainable parameters. الحل: اجمع numel() للمعاملات ذات requires_grad واقسم على الإجمالي.

متوسط: غيّر rank وحده. الحل: ثبّت split وال seed والـ training budget، وقارن الجودة والذاكرة؛ لا تختار بالـ train accuracy.

متقدم: التدريب تحسن والاختبار ساء. الحل: راجع overfitting/leakage أو ضبط hyperparameters على test؛ ارجع إلى validation واحتفظ بالاختبار مقفولًا.

مشروع: خزّن adapter منفصلًا عن base model مع provenance و metrics. معيار القبول: reproducible load، مقارنة baseline، وقرار إبقاء أو rollback.

15

تشغيل محلي وقياس latency و throughput

Ollama, llama.cpp, ONNX Runtime and vLLM
Deep dive

اختار runtime حسب workload، وقِس على الجهاز والـ model المستهدفين:

الخيارمناسب لماقيد لازم تقيسه
Ollamaتطوير محلي سريع و HTTP API لنموذج محلي.تحميل model و RAM/VRAM؛ لا تكشف endpoint المحلي للعامة بلا حماية.
llama.cppGGUF وتشغيل CPU/GPU و quantization على أجهزة مختلفة.السرعة تعتمد على quantization و chat template؛ API المتوافقة جزئيًا لا تضمن تطابق السلوك.
ONNX Runtime / GenAIإدماج inference في ‎.NET أو أجهزة متنوعة عبر Execution Providers.تحقق من export/operators و parity؛ GenAI API موصوفة في docs كـ preview، راجع حالتها.
vLLMتقديم GPU متعدد الطلبات مع batching وجدولة throughput.يحتاج إعداد خدمة و GPU مناسب؛ قِس queue time و TTFT و inter-token latency مع tokens/sec.

الـ benchmark التالي يقيس warm requests إلى Ollama المحلي باستخدام response fields. ضع model محمّلًا في OLLAMA_MODEL. الـ wall latency هنا لا تقيس TTFT لأن الطلب non-streaming؛ قِس cold start منفصلًا، واختبر أطوال prompts و concurrency واقعية.

Pythonbenchmark_ollama.py — local request timing
import json
import os
import statistics
import time
from urllib.request import Request, urlopen

model = os.environ["OLLAMA_MODEL"]
url = "http://localhost:11434/api/chat"
payload = {"model": model, "messages": [{"role": "user", "content": "Why validate API inputs?"}],
           "stream": False, "options": {"num_predict": 96}}

def call():
    request = Request(url, data=json.dumps(payload).encode(), headers={"Content-Type": "application/json"})
    start = time.perf_counter()
    with urlopen(request, timeout=180) as response:
        result = json.loads(response.read())
    wall = time.perf_counter() - start
    generated = result.get("eval_count", 0)
    generation = result.get("eval_duration", 0) / 1_000_000_000
    return wall, generated / generation if generation else 0.0

call()  # warmup is separate from steady-state samples
latencies, rates = [], []
for _ in range(7):
    latency, rate = call()
    latencies.append(latency)
    rates.append(rate)
ordered = sorted(latencies)
p95 = ordered[min(len(ordered) - 1, int(0.95 * len(ordered)))]
print(f"runs={len(latencies)} median_wall_seconds={statistics.median(latencies):.3f}")
print(f"p95_wall_seconds={p95:.3f} mean_generation_tokens_per_second={statistics.mean(rates):.1f}")

ده wall latency لطلبات متسلسلة، وسرعة generation مستخرجة من عداد النموذج؛ مش throughput تحت حمل. اختبر concurrent clients وسجّل p50/p95 و queue time ونسبة النجاح واستهلاك الذاكرة. vLLM يوفّر per-request metrics وأدوات benchmark موثقة.

حالة التحقق

الـ benchmark لم يُشغّل؛ مفيش latency أو throughput مدّعى أنه ناتج حقيقي. السكربت يطبع القياس الفعلي عند تشغيله على جهاز محلي.

↗

المراجع والقراءة الإضافية

References & further reading

الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)

خريطة التغطية: 18 عنصر من الـ Roadmap ومكان شرحه في الدرس
New sectionTransformer Architecture§01
New sectionAttention Mechanisms§01
New sectionLLM Inference Fundamentals (prefill, decode, KV cache)§01
New sectionStructured Outputs and JSON Schema§04
New sectionFunction Calling and Tool Calling§04
New sectionStreaming AI Responses§04
SuggestedTransformer Architecture§06
SuggestedAttention Mechanisms§06
SuggestedLLM Inference Fundamentals (prefill, decode, KV cache)§06
SuggestedStructured Outputs and JSON Schema§06
SuggestedFunction Calling and Tool Calling§06
SuggestedStreaming AI Responses§06
SuggestedModel Selection§03
SuggestedModel Routing§03
SuggestedMultimodal AI: Vision, Audio, Image Understanding§03
SuggestedAI Cost and Latency Optimization§03
SuggestedQuantization and Local Models§03
SuggestedFine-tuning (LoRA)§03

خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.

محتويات الدرس