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

كيف تعمل LLMs وكيف تختارها

LLMs: How They Work and How to Choose

Tokenization, transformers, sampling, hallucinations, context, model selection, cost and lifecycle.

  • Advanced
  • ~16 min read
  • 21 sections
  • 9 code examples
  • 1 diagrams
  • 8 questions
  • Priority L2 · Essential
  • Transformers · Hosted and local models

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

  • تشرح حلقة التوليد: tokenize → attention → logits → sampling.
  • تفسّر ليه الـ output أغلى من الـ input وليه الموديل «بينسى».
  • تضبط temperature وtop-p حسب المهمة وتعرف حدودهم.
  • تختار موديل بـ eval set وتكلفة وlatency مش بـ leaderboard.

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

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

مستوى التعمق المطلوب

PRACTICALExplain to a teammate how an LLM produces an answer, and pick a model for a feature with numbers to back it up.

01

LLM بيتعلم إزاي؟

Tokens and next-token prediction
Deep dive

النص يتحول إلى tokens، وهي وحدات tokenizer وليست كلمات بالضرورة. النموذج autoregressive يتنبأ بتوزيع token التالي بناءً على tokens السابقة، ويكرر العملية حتى stop condition. لذلك الإجابة generated وليست بحثًا تلقائيًا في قاعدة حقائق موثوقة.

Pretraining يتعلم أنماطًا من corpora واسعة، instruction tuning يجعله يتبع تعليمات، و preference optimization يحسن السلوك وفق تفضيلات. هذا لا يضمن صحة كل معلومة أو حداثتها أو فهمًا مطابقًا للبشر.

02

من النص للـ token التالي

How a decoder-only LLM produces text
Basics
PrompttextTokenizerids (cost unit)N × transformer blockself-attention (KV cache)feed-forwardcontext window limitSoftmaxtemperature, top-pNext tokenappended and fed back: output tokens are generated one by one (latency, cost)
Tokens → embeddings → stacked transformer blocks → probabilities for the next token; repeat
03

Transformer و Attention و Context Window

Why context length is not infinite memory
Deep dive

Transformer يستخدم self-attention لتكوين تمثيلات تعتمد على العلاقات بين tokens. Query/Key/Value تحدد كيف يجمع كل token معلومات من غيره. Multi-head attention يلتقط أنماطًا مختلفة، والـ feed-forward layers تحول التمثيل، مع residual connections و normalization لتسهيل التدريب.

Context window حد لما يمكن أن يدخل في request واحد، وليس ذاكرة دائمة ولا ضمان أن النموذج سيستخدم كل ما بداخله بدقة. Long context قد يرفع التكلفة ويضعف التركيز؛ RAG يختار أدلة مرتبطة بالسؤال بدل حشو كل الملفات.

04

Sampling Parameters و Hallucinations

Control generation without confusing certainty
Practical

Temperature تؤثر على عشوائية sampling، و top-p يقيّد مجموعة tokens المحتملة، و max output tokens يحدد سقف الطول، و stop sequences تنهي generation عند نمط محدد. لا تجعل temperature=0 مرادفًا للصحة؛ ما زال النموذج قد يهلوس أو يختار إجابة خاطئة.

Hallucination تظهر عندما ينتج النموذج محتوى غير مدعوم أو غير صحيح. خففها بتوفير مصادر موثوقة، retrieval، abstention عند نقص الدليل، constrained output، verification، وقياس groundedness. لا تعرض confidence لفظية من النموذج كاحتمال معاير دون تحقق.

05

اختيار النموذج ومقارنة Open/Closed/Local

Quality, latency, privacy and economics
Deep dive

اختيار model قرار product/architecture: جودة المهمة، latency، context، modalities، structured output/tool support، data residency، rate limits، reliability، pricing، availability، versioning، و deprecation policy. Benchmarks العامة لا تمثل domain الخاص بك؛ ابنِ evaluation set من use cases الحقيقية.

Open weights تتيح تشغيلًا وتخصيصًا أكبر لكن تتطلب GPU/ops/security expertise. Hosted APIs تقلل operational burden لكنها تربطك بمزود وحدود استخدام. Local models تفيد privacy/offline/latency لبعض السيناريوهات، لكنها ليست مجانية؛ احسب hardware و maintenance و quality trade-off.

Long context vs RAG: اختر long context لو input محدود ومكتمل، و RAG لو corpus كبير ومتغير وتحتاج citations/ACL. Prompting يغير behavior، RAG يضيف evidence، fine-tuning يغير model behavior/weights.

06

Token Cost و Rate Limits و Model Lifecycle

Operate model choices over time
Practical

قدّر cost = input tokens × input rate + output tokens × output rate، مع اختلاف cached tokens و modalities حسب provider. أضف retries و tool calls و embedding calls و failed attempts إلى unit economics. قس cost per successful workflow وليس cost per API call فقط.

ضع concurrency limits، queueing، retry-after handling، jitter، model pinning حيث متاح، و deprecation calendar. احتفظ ب contract tests و golden evals لتبديل model version. لا تعتمد على اسم alias متحرك دون مراقبة التغير.

07

Model Selection Scorecard

A repeatable provider decision
Practical

اعمل scorecard لكل model: task quality على golden set، p50/p95 latency، tokens/sec، price per successful task، context window، structured output/tool reliability، multilingual performance، privacy/data residency، rate limits، SLA، version stability، و fallback options. حدّد hard constraints أولًا ثم weighted score؛ لا تجعل سعر token وحده يحسم القرار.

اختبر prompts نفسها على providers مختلفة مع ضبط output schema والـ evaluation. سجل model ID الفعلي، لا display name فقط. أعد الاختبار عند model update أو deprecation.

PythonA repeatable provider decision
scorecard = {
  "quality_pass": True,
  "p95_latency_ms": 1400,
  "cost_per_1000_tasks": 4.20,
  "structured_output_pass_rate": 0.995,
  "data_region": "approved-region",
  "fallback_available": True,
}
08

Context Window و Tokenizer عمليًا

Budget context deliberately
Practical

احسب budget للـ system instructions و conversation history و retrieved chunks و tool outputs و expected output. اترك headroom للـ model و provider constraints. Token count يختلف حسب اللغة والرموز والكود؛ النص العربي قد يتجزأ بشكل مختلف عن الإنجليزية. استخدم tokenizer/provider counting متى توفر ولا تعتمد على عدد الكلمات.

Conversation summarization قد يقلل history لكنه قد يفقد constraints أو user intent. احتفظ state structured منفصلًا عن summary، واسمح بإعادة retrieval من source of truth بدل الاعتماد على ذاكرة ملخصة فقط.

09

Reasoning Models و Multimodal Constraints

Choose capabilities by workload
Basics

Reasoning-capable models قد تستخدم internal reasoning budget أطول وتكون أفضل في بعض tasks متعددة الخطوات، لكنها قد تكون أبطأ وأغلى. لا تطلب chain-of-thought الخام كدليل على الصحة؛ اطلب concise rationale أو evidence/result structure. قارن الأداء على task set لديك.

Vision/audio models لها limits في resolution، duration، file format، و safety. افصل transcription عن reasoning إذا كان ذلك يقلل التكلفة أو يسمح بالمراجعة. احتفظ consent وسياسة retention للوسائط.

10

Model Deprecation و Provider Portability

Avoid hidden coupling
Deep dive

Provider abstraction يقلل coupling في transport/API shape لكنه لا يلغي اختلاف tool calling، structured output، embeddings، context, safety, و tokenization. أنشئ capability matrix لكل provider/model. Pin versions، تابع deprecation notices، واختبر candidate model على golden set قبل migration.

احتفظ adapter layer و provider-specific options في Infrastructure، ولا تجعل domain/business logic يعتمد على vendor-specific response objects. لكن لا تخفِ features مهمة خلف abstraction ضعيف؛ expose capabilities explicitly.

11

النموذج الذهني: LLM = دالة بتتوقع الـ token اللي جاي

One forward pass predicts one token; generation is a loop
Deep dive

كل اللي الـ LLM بيعمله في الأساس حاجة واحدة: ياخد تسلسل tokens ويطلّع توزيع احتمالات على الـ token اللي بعده. الإجابة الطويلة اللي بتشوفها هي نتيجة تكرار الخطوة دي مئات المرات. لما تفهم الحلقة دي، أغلب سلوك الموديل «الغريب» بيبقى منطقي.

Tokenization: النص بيتقطّع لـ tokens (أجزاء كلمات) وكل token ليه رقم.
Embedding: كل رقم بيتحوّل لـ vector، وبيتضاف له معلومة عن موقعه في التسلسل.
Transformer layers: في كل layer، كل token «بيبص» على اللي قبله (attention) ويحدّث تمثيله، وبعدين شبكة صغيرة (MLP) تعالجه. ده بيتكرر عشرات المرات.
Logits: آخر vector بيتحوّل لدرجة (logit) لكل token في الـ vocabulary.
Sampling: الـ logits بتتحول لاحتمالات (softmax) وبنختار token واحد حسب الـ temperature والـ top-p.
الحلقة: الـ token المختار بيتضاف للتسلسل ونرجع للخطوة 1، لحد ما الموديل يطلّع token النهاية أو نوصل لـ max_tokens.

نتايج مباشرة من النموذج ده

  • الموديل مالوش ذاكرة بين الـ requests. «المحادثة» هي إن التطبيق بيبعت كل الرسائل السابقة من جديد كل مرة. عشان كده التكلفة بتزيد مع طول المحادثة.
  • الـ output أغلى وأبطأ من الـ input. الـ input كله بيتعالج في forward pass واحد (بالتوازي)، لكن كل output token محتاج pass لوحده (بالتسلسل). ده سبب إن تسعير الـ output أعلى، وإن الـ latency بتتناسب مع طول الرد.
  • الـ hallucination مش bug استثنائي. الموديل دايمًا بيطلّع «أكتر تكملة محتملة»، ومفيش عنده خطوة منفصلة بتتأكد من الصحة. لو المعلومة مش في الـ context ولا راسخة في التدريب، التكملة المحتملة هتبقى كلام شكله صح.
  • الموديل مش بيشوف حروف ولا كلمات. بيشوف tokens، وده سبب ضعفه في العدّ والـ spelling والحساب الطويل.
12

Tokenization: ابنِ BPE بنفسك

Byte Pair Encoding, trained and applied in 40 lines
Deep dive

أغلب الـ LLMs بتستخدم نسخة من Byte Pair Encoding: نبدأ بالحروف كـ tokens، وكل خطوة ندمج أكتر زوج متجاور متكرر في token جديد. بعد آلاف الدمجات، الكلمات الشائعة بتبقى token واحد والنادرة بتتقسم لأجزاء.

Pythonbpe.py — train merges on a tiny corpus, then encode unseen wordsExecuted ✓
from collections import Counter

corpus = "low lower lowest new newer newest wide wider widest " * 5

def train(text, num_merges):
    words = Counter(tuple(w) + ("</w>",) for w in text.split())     # each word = sequence of symbols
    merges = []
    for _ in range(num_merges):
        pairs = Counter()
        for symbols, freq in words.items():
            for a, b in zip(symbols, symbols[1:]):
                pairs[(a, b)] += freq
        if not pairs:
            break
        (a, b), _ = max(pairs.items(), key=lambda kv: (kv[1], kv[0]))   # most frequent pair (ties: deterministic)
        merges.append((a, b))
        merged = {}
        for symbols, freq in words.items():
            out, i = [], 0
            while i < len(symbols):
                if i + 1 < len(symbols) and (symbols[i], symbols[i + 1]) == (a, b):
                    out.append(a + b); i += 2
                else:
                    out.append(symbols[i]); i += 1
            merged[tuple(out)] = merged.get(tuple(out), 0) + freq
        words = merged
    return merges

def encode(word, merges):
    symbols = list(word) + ["</w>"]
    for a, b in merges:                          # apply merges in the order they were learned
        i = 0
        while i + 1 < len(symbols):
            if (symbols[i], symbols[i + 1]) == (a, b):
                symbols[i:i + 2] = [a + b]
            else:
                i += 1
    return symbols

merges = train(corpus, 12)
print("first merges:", [a + "+" + b for a, b in merges[:6]])
for w in ["lowest", "newer", "widest", "lowering", "xyz"]:
    toks = encode(w, merges)
    print(f"{w:<9} -> {len(toks)} tokens  {toks}")
ConsoleOutput — captured from a real run
first merges: ['w+e', 'w+i', 'wi+d', 'wid+e', 't+</w>', 's+t</w>']
lowest    -> 2 tokens  ['lo', 'west</w>']
newer     -> 2 tokens  ['ne', 'wer</w>']
widest    -> 2 tokens  ['wide', 'st</w>']
lowering  -> 7 tokens  ['lo', 'we', 'r', 'i', 'n', 'g', '</w>']
xyz       -> 4 tokens  ['x', 'y', 'z', '</w>']

اللي يستاهل تلاحظه: الكلمات اللي اتشافت في التدريب بقت tokens قليلة. lowering ما اتشافتش، فاتقسمت لجزء معروف وحروف فردية. و xyz اتقسمت لحروف — الـ BPE عمره ما بيقول «كلمة مجهولة»، بيرجع للحروف.

التأثير العملي: النص العربي، الأسماء، الأكواد، والـ JSON بياخدوا tokens أكتر من الإنجليزي العادي لنفس عدد الحروف. يعني نفس المحتوى بالعربي بيكلّف أكتر وبياخد مساحة أكبر من الـ context window. ما تقدّرش التكلفة بعدد الكلمات — عدّ الـ tokens بالـ tokenizer بتاع الموديل نفسه.

13

Attention بالأرقام

Scaled dot-product self-attention with a causal mask, in NumPy
Deep dive

الـ attention بيجاوب على سؤال: «وأنا بحسب تمثيل الـ token ده، آخد قد إيه من كل token قبله؟». كل token بيطلّع 3 vectors: Query (أنا بدوّر على إيه)، Key (أنا عندي إيه)، Value (المعلومة اللي هديها). الوزن = تشابه الـ Query مع كل Key.

Attention(Q, K, V) = softmax( Q·Kᵀ / √d + mask ) · V
Pythonattention.py — one attention head, step by stepExecuted ✓
import numpy as np
np.set_printoptions(precision=2, suppress=True)
rng = np.random.default_rng(0)

tokens = ["The", "cat", "sat", "down"]
T, d = len(tokens), 8                      # sequence length, embedding size

X = rng.normal(size=(T, d))                # token embeddings (+ positions) coming from the previous layer
Wq, Wk, Wv = (rng.normal(size=(d, d)) / np.sqrt(d) for _ in range(3))    # learned projections

Q, K, V = X @ Wq, X @ Wk, X @ Wv
scores = Q @ K.T / np.sqrt(d)              # (T, T): how much token i wants to look at token j

mask = np.triu(np.ones((T, T), dtype=bool), k=1)     # True above the diagonal = "future" positions
scores = np.where(mask, -np.inf, scores)   # a decoder token must not see what comes after it

weights = np.exp(scores - scores.max(axis=1, keepdims=True))
weights /= weights.sum(axis=1, keepdims=True)        # softmax per row => each row sums to 1

out = weights @ V                          # new representation: weighted mix of the values

print("attention weights (row = token being computed, column = token attended to):")
print("        " + "  ".join(f"{t:>5}" for t in tokens))
for t, row in zip(tokens, weights):
    print(f"{t:>6}  " + "  ".join(f"{w:5.2f}" for w in row))
print("\nrow sums:", weights.sum(axis=1))
print("output shape:", out.shape, "(same as the input: one vector per token)")
ConsoleOutput — captured from a real run
attention weights (row = token being computed, column = token attended to):
          The    cat    sat   down
   The   1.00   0.00   0.00   0.00
   cat   1.00   0.00   0.00   0.00
   sat   0.31   0.34   0.35   0.00
  down   0.22   0.28   0.21   0.29

row sums: [1. 1. 1. 1.]
output shape: (4, 8) (same as the input: one vector per token)

الـ causal mask: المثلث اللي فوق القطر كله أصفار. The شايف نفسه بس (1.00)، و down شايف الأربعة. ده اللي بيخلي الموديل يتدرّب على توقع الـ token الجاي من غير ما «يغش» ويشوفه.

الأوزان هنا عشوائية لأن الـ matrices مش متدرّبة — الغرض تشوف الحسابات. في موديل حقيقي التدريب بيخلي head معيّن يربط الفعل بفاعله، و head تاني يربط الضمير بالاسم اللي بيرجع له، وهكذا.

التكلفة: مصفوفة الـ scores حجمها T×T. يعني ضعف طول الـ context = 4 أضعاف حسابات الـ attention. ده سبب إن الـ context الطويل أبطأ وأغلى، وسبب أهمية الـ KV cache: في التوليد، الـ K والـ V بتوع الـ tokens القديمة بيتخزنوا ومش بيتحسبوا تاني، فكل token جديد بيحسب صف واحد بس.

Prompt caching: نفس الفكرة على مستوى الـ API — لو بداية الـ prompt (system prompt + مستندات ثابتة) متطابقة حرفيًا بين requests، المزوّد يقدر يعيد استخدام الحسابات ويحاسبك أقل. عشان كده حط الجزء الثابت في الأول والمتغير في الآخر.

14

Temperature و Top-p: إزاي الـ token بيتاختار

From logits to a sampled token, with measured effects
Practical
Pythonsampling.py — temperature reshapes the distribution, top-p truncates itExecuted ✓
import numpy as np
rng = np.random.default_rng(7)

vocab  = ["Paris", "London", "Rome", "banana", "the"]
logits = np.array([5.0, 3.0, 2.5, 0.5, 0.2])      # raw scores for the prompt "The capital of France is"

def softmax(x):
    e = np.exp(x - x.max())
    return e / e.sum()

def distribution(logits, temperature=1.0, top_p=1.0):
    p = softmax(logits / temperature)              # T<1 sharpens, T>1 flattens
    order = np.argsort(-p)
    keep = np.cumsum(p[order]) - p[order] < top_p  # smallest set whose probability mass reaches top_p
    q = np.zeros_like(p)
    q[order[keep]] = p[order[keep]]
    return q / q.sum()

print(f"{'setting':<22}" + "".join(f"{v:>8}" for v in vocab))
for label, t, tp in [("T=1.0", 1.0, 1.0), ("T=0.2", 0.2, 1.0), ("T=2.0", 2.0, 1.0), ("T=1.0, top_p=0.9", 1.0, 0.9)]:
    print(f"{label:<22}" + "".join(f"{x:8.3f}" for x in distribution(logits, t, tp)))

def unique_answers(t, n=1000):
    p = distribution(logits, t)
    return {vocab[i] for i in rng.choice(len(vocab), size=n, p=p)}

print("\ndistinct tokens seen in 1000 samples:")
for t in (0.2, 1.0, 2.0):
    print(f"  T={t}: {sorted(unique_answers(t))}")
ConsoleOutput — captured from a real run
setting                  Paris  London    Rome  banana     the
T=1.0                    0.809   0.109   0.066   0.009   0.007
T=0.2                    1.000   0.000   0.000   0.000   0.000
T=2.0                    0.540   0.199   0.155   0.057   0.049
T=1.0, top_p=0.9         0.881   0.119   0.000   0.000   0.000

distinct tokens seen in 1000 samples:
  T=0.2: ['Paris']
  T=1.0: ['London', 'Paris', 'Rome', 'banana', 'the']
  T=2.0: ['London', 'Paris', 'Rome', 'banana', 'the']

Temperature بتقسم الـ logits قبل الـ softmax: قيمة صغيرة بتكبّر الفروق (الأعلى بياخد تقريبًا كل الاحتمال)، وقيمة كبيرة بتسطّح التوزيع فـ banana بيبقى ليها فرصة حقيقية.

Top-p بيقطع «الذيل»: بنرتّب الـ tokens ونحتفظ بأصغر مجموعة مجموع احتمالها يوصل لـ p، والباقي احتماله يبقى صفر. ده بيمنع الاختيارات الشاذة من غير ما يلغي التنوع بين الاختيارات المعقولة.

المهمةالإعداد المعقولليه
استخراج بيانات، تصنيف، JSON، tool callingtemperature منخفضة (0–0.2)عايز نفس الإجابة كل مرة
شرح، تلخيص، إجابة أسئلةمتوسطة (0.3–0.7)صياغة طبيعية من غير شطحات
brainstorming، كتابة إبداعيةأعلى (0.8–1.0+)التنوع مطلوب
مفاهيم غلط شائعة
  • «temperature = 0 يعني deterministic». بيقلل التباين جدًا لكن مش ضمان: ترتيب العمليات على الـ GPU، الـ batching، وتحديثات الموديل ممكن تغيّر النتيجة. لو محتاج ثبات: خزّن الرد (cache) بدل ما تعتمد على إعادة التوليد.
  • «temperature منخفضة بتمنع الـ hallucination». بتخلي الموديل يختار أكتر تكملة محتملة — ولو أكتر تكملة محتملة غلط، هيقولها بثبات كل مرة. الحل: context صح (RAG) وتحقق، مش sampling.
  • مش كل الموديلات بتقبل الإعدادات دي. بعض موديلات الـ reasoning بتتجاهل أو ترفض temperature/top_p. راجع توثيق الموديل المحدد.
15

اختيار الموديل: قرار هندسي بأرقام

Decide with an evaluation set, latency and cost — not with leaderboards
Practical

الـ leaderboards العامة بتقيس مهام عامة. مهمتك أنت (تصنيف تذاكر دعم بالعربي المصري مثلًا) ممكن ترتيب الموديلات فيها يبقى مختلف تمامًا. الطريقة الوحيدة الموثوقة: eval set صغير من بياناتك.

Pythonchoose_model.py — compare candidates on quality, latency and cost per 1,000 requestsExecuted ✓
# Prices and measurements below are ILLUSTRATIVE placeholders. Replace them with your provider's
# current price list and with numbers measured on your own evaluation set.
candidates = {
    #  name            accuracy   p95 latency (s)   $ per 1M input   $ per 1M output
    "small-model":    (0.86,       0.9,              0.15,            0.60),
    "medium-model":   (0.93,       1.8,              1.00,            4.00),
    "large-model":    (0.95,       4.5,              5.00,            20.00),
}
IN_TOKENS, OUT_TOKENS = 1200, 150          # measured average per request for THIS task
MIN_ACCURACY, MAX_P95 = 0.90, 3.0          # product requirements

print(f"{'model':<14}{'acc':>6}{'p95':>6}{'$ / 1k req':>12}  verdict")
for name, (acc, p95, pin, pout) in candidates.items():
    cost_1k = 1000 * (IN_TOKENS * pin + OUT_TOKENS * pout) / 1_000_000
    reasons = [r for ok, r in [(acc >= MIN_ACCURACY, "accuracy below target"),
                               (p95 <= MAX_P95, "too slow")] if not ok]
    print(f"{name:<14}{acc:>6.2f}{p95:>6.1f}{cost_1k:>12.2f}  {'OK' if not reasons else 'rejected: ' + ', '.join(reasons)}")
ConsoleOutput — captured from a real run
model            acc   p95  $ / 1k req  verdict
small-model     0.86   0.9        0.27  rejected: accuracy below target
medium-model    0.93   1.8        1.80  OK
large-model     0.95   4.5        9.00  rejected: too slow

القاعدة: أصغر موديل بيعدّي متطلبات الجودة والسرعة. والنمط الشائع في الإنتاج هو الـ routing: الموديل الصغير للحالات السهلة (الأغلبية)، والتصعيد للأكبر لما الثقة تبقى قليلة أو المهمة معقدة.

أسئلة قبل الاختيار

  • هل المهمة محتاجة reasoning متعدد الخطوات، ولا استخراج/تصنيف مباشر؟
  • الـ context window كفاية للـ prompt + المستندات + الرد؟ وهل الجودة ثابتة لما الـ context يتملي؟
  • محتاج structured output أو tool calling موثوق؟ مش كل الموديلات زي بعض فيهم.
  • البيانات مسموح تخرج لمزوّد خارجي؟ (خصوصية، residency، عقود.)
  • إيه خطة الـ deprecation؟ الموديلات بتتسحب — لازم يكون عندك eval set يخليك تبدّل بأمان.
16

تمارين وتقييم

Exercises and assessment
Practical
  • Beginner: في sampling.py جرّب top_p=0.5. كام token فضل احتماله أكبر من صفر؟ ليه؟
  • Intermediate: في bpe.py زوّد عدد الدمجات لـ 30 وشوف lowering بقت كام token. إيه العلاقة بين حجم الـ vocabulary وطول التسلسل؟
  • Intermediate: في attention.py شيل الـ mask وقارن أوزان الصف الأول. اشرح ليه ده بيبقى «غش» في التدريب.
  • Advanced: ضيف head تاني بـ matrices مختلفة واعمل concatenate للـ outputs — ده أساس الـ multi-head attention.
  • Engineering challenge: اكتب eval set من 30 مثال لمهمة حقيقية عندك، وقارن موديلين على الدقة والـ p95 latency والتكلفة لكل 1000 request بأسعار المزوّد الحالية.

ليه الـ output tokens بتتسعّر أغلى من الـ input tokens عادةً؟

مستخدم بيشتكي إن الـ chatbot «نسي» حاجة قالها في بداية محادثة طويلة جدًا. أرجح سبب؟

عايز نفس الإجابة بالظبط لنفس السؤال كل مرة (مثلاً لتقرير رسمي). أضمن حل؟

17

اختبر فهمك

Knowledge Check
Practical
هل temperature=0 تضمن factual correctness؟
لا. هي تقلل sampling randomness لكنها لا تمنع hallucination أو معلومات خاطئة.
متى نختار RAG بدل long context؟
عندما يكون corpus كبيرًا أو متغيرًا أو يحتاج ACL و citations واسترجاعًا انتقائيًا.

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

هل temperature=0 تعني deterministic factual output؟
لا تضمن factual correctness، وقد لا تضمن تطابقًا كاملًا بين runtimes/providers.
ما الفرق بين prefill و decode؟
Prefill يعالج prompt ويبني KV cache؛ decode يولد token تلو الآخر مع إعادة استخدام cache.
لماذا لا يمكن استبدال tokenizer دون تغيير model weights؟
لأن token IDs و vocabulary mappings جزء من تمثيل النموذج المتعلم؛ mapping مختلف يجعل embeddings غير متوافقة.
18

Tokenization, Embeddings and Position Information

The actual sequence the model processes
Deep dive

Tokenizer يحول Unicode text إلى token IDs وفق vocabulary/merge rules. Token boundaries لا تطابق الكلمات؛ whitespace، punctuation، Arabic morphology، code، و rare names تؤثر على segmentation. Embedding layer يحول token IDs إلى vectors، وتضاف position information (absolute أو rotary/relative variants) حتى يميز النموذج ترتيب tokens. اختلاف tokenizer يعني اختلاف token count و embedding vocabulary ولا يمكن استبداله عشوائيًا مع weights.

احسب token budget باستخدام tokenizer الخاص بالنموذج كلما أمكن. قيّم multilingual token efficiency على corpus عربي/إنجليزي واقعي؛ context window بال tokens قد يستوعب عدد كلمات مختلفًا جدًا حسب اللغة والمحتوى.

PythonThe actual sequence the model processes
# Use the exact tokenizer shipped with the selected model when available.
# Hugging Face example:
# from transformers import AutoTokenizer
# tok = AutoTokenizer.from_pretrained(model_id)
# ids = tok("مرحبا بالعالم — AI engineering", add_special_tokens=True)["input_ids"]
# print(len(ids), tok.convert_ids_to_tokens(ids))
19

Pretraining, Instruction Tuning and Preference Optimization

Different training stages create different capabilities
Deep dive

Pretraining عادةً يتعلم next-token prediction على large corpus؛ جودة/تغطية/تكرار/تلوث البيانات تؤثر في knowledge واللغة. Supervised fine-tuning يستخدم demonstrations لتعليم formats/instructions. Preference optimization مثل DPO-style objectives يستخدم preferences بين outputs لتقريب السلوك لتفضيلات محددة. هذه المراحل لا تجعل النموذج database موثوقًا ولا تضمن policy compliance في كل سياق.

Data contamination تعني أن benchmark/test examples ربما ظهرت في training corpus، فتبدو النتيجة أعلى من generalization الحقيقي. Model cards و system cards تساعد على فهم intended use والقيود، لكنها ليست بديلًا عن evaluation محلي.

PythonDifferent training stages create different capabilities
training_stages = [
  ('pretraining', 'learn broad statistical structure'),
  ('supervised_finetuning', 'imitate curated demonstrations'),
  ('preference_optimization', 'align outputs with preference signals'),
]
for stage, purpose in training_stages:
    print(stage, '->', purpose)
20

Sampling Mathematics: Temperature, Top-k and Top-p

Logits become a distribution before decoding
Deep dive

النموذج يخرج logits z لكل token. Softmax يحولها إلى probabilities. Temperature T يغير sharpness عبر softmax(z/T): T أقل يجعل التوزيع أكثر تركيزًا، و T أعلى يجعله أكثر flattening. Top-k يحتفظ بأعلى k tokens، و top-p يحتفظ بأصغر مجموعة cumulative probability تبلغ p ثم يعيد normalization. ترتيب تطبيق filters قد يختلف حسب implementation/provider.

Greedy decoding يختار أعلى probability كل مرة، لكنه قد ينتج تكرارًا أو إجابة أقل تنوعًا. Beam search يحتفظ بعدة sequences وقد يفيد بعض generation tasks لكنه ليس ضمانًا لجودة الحوار. Decoding strategy يجب أن تقاس على task؛ لا يوجد parameter preset عالمي.

PythonLogits become a distribution before decoding
import numpy as np

def softmax(logits, temperature=1.0):
    z = np.asarray(logits, dtype=float) / temperature
    z -= z.max()
    p = np.exp(z)
    return p / p.sum()

logits = [2.0, 1.0, 0.1]
for t in [0.5, 1.0, 2.0]:
    print(t, np.round(softmax(logits, t), 3))
21

Inference Anatomy: Prefill, Decode and KV Cache

Why first token and later tokens behave differently
Deep dive

Prefill يعالج prompt tokens بالتوازي نسبيًا ويحسب hidden states و KV tensors للطبقات. Decode يولد token واحدًا في كل خطوة autoregressive، ويعيد استخدام KV cache بدل إعادة حساب كل previous keys/values. لذلك time-to-first-token يرتبط كثيرًا بـ prompt length/prefill، بينما inter-token latency يرتبط decode speed و memory bandwidth و batching.

KV cache يستهلك memory تقريبًا proportional to layers × sequence length × KV heads × head dimension × bytes × batch. Long contexts و concurrent sessions قد يجعلوا KV cache bottleneck حتى لو model weights fit. Paged attention و cache eviction/quantization خيارات serving حسب runtime.

PythonWhy first token and later tokens behave differently
def kv_cache_bytes(layers, batch, seq, kv_heads, head_dim, bytes_per_value=2):
    # K and V tensors both stored.
    return 2 * layers * batch * seq * kv_heads * head_dim * bytes_per_value

size = kv_cache_bytes(32, batch=4, seq=8192, kv_heads=8, head_dim=128)
print(round(size / (1024**3), 2), 'GiB')
↗

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

References & further reading

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

خريطة التغطية: 19 عنصر من الـ Roadmap ومكان شرحه في الدرس
New sectionTokens and tokenization§01
New sectionContext window§01
New sectionNext-token prediction§01
New sectionPretraining, instruction tuning, preference tuning§01
New sectionTemperature, top-p, max tokens, stop sequences§04
New sectionSystem / user / assistant roles§03
New sectionWhy hallucinations happen§04
New sectionReasoning models and thinking budget§04
New sectionMultimodal input (vision, audio)§03
New sectionOpen vs closed models§05
New sectionSmall and local models (Ollama, llama.cpp)§05
New sectionChoosing a model: quality, cost, latency, privacy§05
New sectionLong context vs RAG§05
New sectionPrompting vs RAG vs fine-tuning: how to decide§05
New sectionBenchmarks and their limits§04
New sectionConstrained decoding and structured output§04
New sectionEstimating cost from input and output tokens§05
New sectionRate limits and batch APIs§05
New sectionModel deprecation and version pinning§05

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

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