Lecture 03 · N-grams

المحاضرة 03 · نماذج N-grams

Evaluating a Language Model

تقييم نموذج اللغة

Slides 28–32الشرائح 28–32 P3 SKIM

Two ways to measure a language model, three data splits that keep the measurement honest, and the reason raw probability cannot be the metric.

طريقتان لقياس language model، وثلاث شرائح من البيانات تحافظ على نزاهة القياس، والسبب في أن الاحتمال الخام لا يصلح مقياساً.

Two kinds of evaluation

نوعان من التقييم

You can judge a language model by what it does for an application, or by how well it predicts text. Those are extrinsic and intrinsic evaluation.

يمكنك تقييم language model بما يفعله داخل تطبيق حقيقي، أو بمدى جودة تنبؤه بالنص. هذان هما extrinsic evaluation وintrinsic evaluation.

Extrinsic

خارجي (Extrinsic)

Plug the LM into a real system and measure the system.

ضع language model داخل نظام حقيقي، ثم قِس النظام نفسه.

  • Speech recognition: word error rate (WER).

    في speech recognition: word error rate (WER).

  • Machine translation: BLEU, COMET.

    في machine translation: BLEU وCOMET.

Most realistic, because it measures the thing you actually care about. Expensive: you have to build and run the whole pipeline for every candidate model.

الأكثر واقعية، لأنه يقيس ما يهمك فعلاً. لكنه مكلف: عليك بناء وتشغيل pipeline كامل لكل نموذج مرشّح.

Intrinsic

داخلي (Intrinsic)

Measure the LM directly on held-out text.

قِس language model مباشرة على نص محجوز (held-out).

  • Standard metric: perplexity.

    المقياس القياسي: perplexity.

Fast, so you can iterate on dozens of model variants in an afternoon. Only an approximation of what you care about.

سريع، فتستطيع تجربة عشرات النماذج في جلسة واحدة. لكنه مجرد تقريب لما يهمك فعلاً.

Comparison, side by side

مقارنة جنباً إلى جنب

ExtrinsicخارجيIntrinsicداخلي
What it measuresما الذي يقيسهend-task qualityجودة المهمة النهائيةprobability assigned to held-out textالاحتمال المُسنَد إلى نص محجوز (held-out)
Typical metricالمقياس المعتادWER, BLEU, COMETperplexity
Cost per runتكلفة كل تشغيلhigh (full pipeline)عالية (خط المعالجة كاملاً)low (one pass over test text)منخفضة (مرور واحد على نص الاختبار)
Realismالواقعيةhighعاليةproxy onlyمؤشر بديل فقط
Good forمناسب لـfinal decisions, publication claimsالقرارات النهائية، وادعاءات النشرrapid model iterationالتكرار السريع على النموذج
Weaknessنقطة الضعفslow, needs a whole systemبطيء، ويحتاج إلى نظام كاملgains may not transfer to the taskقد لا تنتقل التحسينات إلى المهمة

يقارن الجدول بين extrinsic وintrinsic في ستة أسطر. اقرأه عمودياً: extrinsic يقيس جودة المهمة النهائية بمقاييس مثل WER وBLEU، وهو غالٍ وواقعي ويُستخدم للقرار النهائي. وintrinsic يقيس الاحتمال المُعطى للنص المحجوز عبر perplexity، وهو رخيص وسريع لكنه مجرد وكيل. السطر الأخير هو نقطة الامتحان: تحسّن perplexity قد لا ينتقل إلى المهمة الحقيقية.

Memory hookخطّاف للذاكرة

Extrinsic looks externally, at the application around the model. Intrinsic looks inside, at the model's own predictions. Intrinsic is the cheap screening test, extrinsic is the real exam.

Extrinsic ينظر إلى externally، أي خارجاً نحو التطبيق المحيط بالنموذج. وIntrinsic ينظر إلى inside، أي داخلاً نحو تنبؤات النموذج ذاته. Intrinsic هو الفحص الأولي الرخيص، وextrinsic هو الامتحان الحقيقي.

The Shannon Game: what a language model is being asked to do

لعبة شانون (Shannon Game): ما المطلوب من نموذج اللغة

Cover the next word and guess it. A better model is simply one that assigns higher probability to the word that actually occurred.

غطِّ الكلمة التالية وخمّنها. النموذج الأفضل هو ببساطة الذي يعطي احتمالاً أعلى للكلمة التي ظهرت فعلاً.

I always order pizza with cheese and ____
The 33rd President of the US was ____
I saw a ____

ثلاثة فراغات من الشرائح، كل واحد منها سياقه مختلف تماماً: الأول يتوقع إضافات البيتزا، والثاني اسم رئيس، والثالث اسماً عاماً. انتبه إلى اختلاف السياقات، فهو أساس الفقرة التالية.

For the first prompt a good model spreads its probability like this:

في الفراغ الأول، يوزّع النموذج الجيد احتماله على هذا النحو:

Candidate next wordالكلمة التالية المرشحةP
mushrooms0.1
pepperoni0.1
anchovies0.01
……
fried rice0.0001
……
and10⁻¹⁰⁰

يعرض الجدول كلمات مرشّحة بعد "cheese and" مع احتمال كل واحدة. اقرأه من الأعلى للأسفل كترتيب تنازلي: الإضافات المعقولة مثل mushrooms وpepperoni تأخذ 0.1، والأقل معقولية تنزل إلى 0.0001، والمستحيل نحوياً مثل and ينزل إلى 10⁻¹⁰⁰. الأرقام نفسها غير مهمة، المهم هو الترتيب.

The shape of that list is the model's quality. Mass on plausible continuations, near-zero on impossible ones.

شكل هذا التوزيع هو جودة النموذج: كتلة احتمالية على الاستكمالات المعقولة، وشبه صفر على المستحيلة.

Why unigrams are terrible at this game

لماذا الـ unigrams سيئة جداً في هذه اللعبة

A unigram model ignores the context completely. It gives the same distribution for every blank, so it answers all three prompts identically with whatever is most frequent in the corpus: the, of, and.

نموذج unigram يتجاهل السياق تماماً، فيعطي التوزيع نفسه لكل فراغ، ويجيب على الفراغات الثلاثة بالإجابة ذاتها: أكثر الكلمات تكراراً في corpus، أي the، of، and.

UNIGRAM BIGRAM context: "...cheese and" "...President was" "...I saw a" same answer P(the), P(of)… context is discarded so the guess is always the corpus-wide most frequent word high perplexity context: "and" "was" "a" mushrooms, pepperoni… born, elected, a… man, dog, movie… one word of context already narrows the field to grammatical continuations lower perplexity
A unigram model answers every blank the same way. That is why its perplexity is so much worse.نموذج unigram يجيب عن كل فراغ بالطريقة نفسها. ولهذا تكون perplexity الخاصة به أسوأ بكثير.

يقسم الرسم الشاشة إلى نصفين. على اليسار UNIGRAM: السياقات الثلاثة المختلفة كلها تؤدي إلى صندوق واحد مكتوب عليه "same answer"، لأن السياق يُرمى، فالنتيجة high perplexity. على اليمين BIGRAM: كل سياق يُختصر إلى كلمة واحدة سابقة ("and"، "was"، "a")، فيعطي كل واحد قائمة استكمالات مختلفة ومناسبة، فالنتيجة lower perplexity. الخلاصة: كلمة واحدة من السياق تكفي لتضييق المجال بشكل هائل.

Trapفخ

"Unigrams are bad" is not about unigram counts being inaccurate. The counts are perfectly accurate. The problem is that a unigram model throws the context away, so it cannot distinguish one blank from another. Accuracy of estimation and usefulness of the conditioning are different things.

عبارة "unigrams are bad" لا تعني أن عدّات unigram غير دقيقة، فهي دقيقة تماماً. المشكلة أن نموذج unigram يرمي السياق، فلا يستطيع التفريق بين فراغ وآخر. دقة التقدير وفائدة الشرط (conditioning) شيئان مختلفان.

Train, dev, test

التدريب، والتطوير، والاختبار (Train, dev, test)

Three disjoint slices of data, three different jobs. Mixing up the jobs is how published numbers become lies.

ثلاث شرائح منفصلة من البيانات، ولكل واحدة وظيفة مختلفة. خلط الوظائف هو ما يحوّل الأرقام المنشورة إلى أكاذيب.

SplitالتقسيمJobالمهمةHow often you touch itكم مرة تلمسه
Training setمجموعة التدريب (Training set)estimate the model parameters, which for an n-gram model means the countsتقدير معاملات النموذج، وهي في نموذج n-gram العدّاتconstantlyباستمرار
Dev set (held-out, validation)مجموعة التطوير (Dev set، أي held-out أو validation)tune hyperparameters: interpolation weights, the k in add-k smoothing, discount values, backoff orderضبط الـ hyperparameters: أوزان interpolation، وk في add-k smoothing، وقيم الخصم، ورتبة backoffas often as you likeبقدر ما تشاء
Test setمجموعة الاختبار (Test set)final evaluation only, to report an unbiased estimate of generalizationالتقييم النهائي فقط، للإبلاغ عن تقدير غير متحيز للتعميمonce, or very few timesمرة واحدة، أو مرات قليلة جداً

يربط الجدول كل شريحة بوظيفتها وبعدد المرات المسموح بلمسها. Training set لتقدير معاملات النموذج، وهي العدّات في حالة n-gram، وتُستخدم باستمرار. Dev set (ويسمى أيضاً held-out أو validation) لضبط hyperparameters مثل أوزان interpolation وk في smoothing، ويُستخدم كما تشاء. Test set للتقييم النهائي فقط، ويُلمس مرة واحدة. العمود الأخير هو الأهم: عدد مرات اللمس هو الذي يحدد نزاهة الرقم.

TRAIN fit the counts DEV tune k, λ TEST report once iterate here, not on test LEAKAGE: test text inside train the model has memorised the answers, so perplexity looks great and means nothing
Train fits, dev tunes, test reports. Any flow of test text back into training destroys the measurement.التدريب يُلائم، والتطوير يضبط، والاختبار يُبلغ. وأي تسرّب لنص الاختبار إلى التدريب يُفسد القياس.

يرسم المخطط شريط البيانات مقسوماً إلى ثلاثة صناديق: TRAIN الكبير لملاءمة العدّات، وDEV لضبط k وλ، وTEST للتقرير مرة واحدة. السهم المنقّط العائد من TEST إلى DEV يعني: كرّر تجاربك هنا لا على test. والسهم الأحمر المشطوب بدائرة يمثل LEAKAGE، أي تسرب نص الاختبار إلى التدريب، وحينها يكون النموذج قد حفظ الأجوبة، فتبدو perplexity ممتازة وهي لا تعني شيئاً.

Data contamination

تلوّث البيانات (Data contamination)

Contamination is anything that lets information about the test set influence the model. It comes in two flavours, and both are on the slides.

Contamination هو أي شيء يسمح لمعلومات عن test set بأن تؤثر على النموذج. وله نوعان، وكلاهما مذكور في الشرائح.

1. Leakage: test sentences end up in the training data

1. التسرّب (Leakage): جمل الاختبار تنتهي في بيانات التدريب

The model has literally seen the test text, so every test bigram has a healthy count.

النموذج رأى نص الاختبار حرفياً، فكل bigram في الاختبار له عدّة جيدة.

This is the dominant worry for modern LLMs trained on web scrapes, because public benchmark sets are on the web.

هذا هو القلق الأكبر في نماذج LLM الحديثة المُدرَّبة على سحب الويب، لأن مجموعات benchmark العامة منشورة على الويب أصلاً.

2. Repeated tuning on the test set

2. الضبط المتكرر على مجموعة الاختبار

You never put test text into training, but you evaluate on test, change a hyperparameter, evaluate again, and keep the setting that scored best. Nothing leaked, yet you have still overfit to the test set through your own decisions.

أنت لم تضع نص الاختبار في التدريب إطلاقاً، لكنك تقيّم على test، ثم تغيّر hyperparameter، ثم تقيّم مرة أخرى، وتُبقي الإعداد الذي أعطى أفضل نتيجة. لم يتسرب شيء، ومع ذلك وقعت في overfitting على test set عبر قراراتك أنت.

Workedمثال محلول
honest protocol

  train    -> count bigrams
  dev      -> try k = 0.01, 0.1, 0.5, 1.0
              dev PP:  184,  170,  179,  201
              pick k = 0.1
  test     -> evaluate ONCE with k = 0.1
              test PP: 173        <- the number you report

contaminated protocol

  train    -> count bigrams
  test     -> try k = 0.01, 0.1, 0.5, 1.0
              test PP: 181, 166, 175, 198
              pick k = 0.1
  test     -> report 166           <- biased low, and you have
                                      no held-out data left to check it

يقارن المقطع بين بروتوكولين. النزيه: نعدّ على train، ونجرّب قيم k على dev فنختار k = 0.1، ثم نقيّم على test مرة واحدة ونُبلّغ 173. والملوّث: نجرّب قيم k على test نفسه ونُبلّغ أدنى رقم، أي 166، ولم تبقَ لدينا بيانات محجوزة للتحقق.

The two protocols differ by one word (dev versus test) and by about 7 perplexity points of self-deception. Both selected the same k here, which is the point: the harm is not the choice, it is that the reported number was chosen to be the minimum.

البروتوكولان يختلفان بكلمة واحدة (dev مقابل test) وبنحو 7 نقاط perplexity من خداع الذات. وقد اختار كلاهما قيمة k نفسها، وهذا هو بيت القصيد: الضرر ليس في الاختيار، بل في أن الرقم المُبلَّغ اختير ليكون الأدنى.

Memory hookخطّاف للذاكرة

Dev is the sparring partner, test is the title fight. You spar as many rounds as you want. You fight once. If you keep "testing" to pick settings, you have turned your title fight into sparring and you have nothing left to report.

Dev هو شريك التدريب، وtest هو نزال اللقب. تتدرب كما تشاء من الجولات، لكنك تنازل مرة واحدة. وإذا ظللت تختبر على test لاختيار الإعدادات، فقد حوّلت نزال اللقب إلى تدريب، ولم يبقَ عندك ما تُبلّغ به.

Why raw probability is not a usable metric

لماذا لا يصلح الاحتمال الخام مقياساً

You might think: just report P(test set). Two reasons that fails.

قد تظن أن الحل هو الإبلاغ عن P(test set) مباشرة. سببان يجعلان ذلك فاشلاً.

It shrinks with length

يتناقص مع الطول

Every factor in the chain rule is at most 1, so a longer test set always gets a smaller probability, no matter how good the model is. The number tells you more about the length of the text than about the quality of the model.

كل عامل في chain rule لا يزيد عن 1، فأي test set أطول يحصل دائماً على احتمال أصغر، مهما كان النموذج جيداً. الرقم يخبرك عن طول النص أكثر مما يخبرك عن جودة النموذج.

Workedمثال محلول
a model that assigns 0.1 to every word

  2 words:   P = 0.1^2  = 0.01
  5 words:   P = 0.1^5  = 0.00001
 20 words:   P = 0.1^20 = 1e-20

the model never changed. only the length did.

so you cannot compare P on a 10-word test set
against P on a 1000-word test set. the longer one
loses automatically.

يأخذ المقطع نموذجاً ثابتاً يعطي 0.1 لكل كلمة، ويحسب P عند ثلاثة أطوال: 0.01 لكلمتين، و0.00001 لخمس كلمات، و1e-20 لعشرين كلمة. النموذج لم يتغير أبداً، الطول وحده هو الذي تغيّر. فلا يمكن مقارنة P على نص اختبار من 10 كلمات بـ P على نص من 1000 كلمة، لأن الأطول يخسر تلقائياً.

Different test sets are not comparable

مجموعات الاختبار المختلفة غير قابلة للمقارنة

Two models evaluated on test sets of different sizes cannot be ranked by raw probability at all. Even on the same test set, the magnitude is uninterpretable: is 1e-20 good? There is no scale.

نموذجان قُيّما على مجموعتي اختبار بحجمين مختلفين لا يمكن ترتيبهما بالاحتمال الخام إطلاقاً. وحتى على test set نفسها، المقدار غير قابل للتفسير: هل 1e-20 جيد؟ لا يوجد مقياس مرجعي للحكم.

The fix: normalize by the number of tokens

الحل: التطبيع بعدد الـ tokens

Divide the work out per word. That gives a per-word score that does not drift with length, and perplexity is exactly that: an inverse probability normalized by the number of tokens.

وزّع الحساب على كل كلمة. هذا يعطي درجة لكل كلمة لا تنزلق مع الطول، وperplexity هي هذا بالضبط: احتمال مقلوب مُطبَّع على عدد الـ tokens.

P(W)shrinks with N, no interpretable scaleيتناقص مع N، ولا مقياس قابل للتفسير 1P(W)right direction, still grows with Nالاتجاه صحيح، لكنه ما زال يكبر مع N (1P(W))1/Nper-word, length-independent = perplexityلكل كلمة، ومستقل عن الطول = perplexity

تقرأ المعادلة في ثلاث خطوات من الأعلى للأسفل. الأولى P(W): تتقلص مع N وبلا مقياس مفهوم. الثانية 1 / P(W): الاتجاه صار صحيحاً (الأفضل أصغر) لكنها ما زالت تنمو مع N. الثالثة رفع المقلوب للقوة 1/N: صارت لكل كلمة ومستقلة عن الطول، وهذه بالضبط هي perplexity.

Candidate metricالمقياس المرشحLength-independent?مستقل عن الطول؟Interpretable scale?مقياس قابل للتفسير؟Verdictالحكم
P(W)noلاnoلاunusableغير صالح
log P(W)noلاpartlyجزئياًfixes underflow, not lengthيعالج underflow، لا الطول
average log P per wordمتوسط log P لكل كلمةyesنعمpartlyجزئياًfine, and equals −log₂(PP) in bitsجيد، ويساوي −log₂(PP) بالبتات
perplexity, P(W)−1/Nperplexity، P(W)−1/Nyesنعمyes, reads as a branching factorنعم، تُقرأ كـ branching factorthe standardالمعيار المعتمد

يفحص الجدول أربعة مقاييس مرشّحة بمعيارين: هل هو مستقل عن الطول، وهل له مقياس قابل للتفسير. P(W) يفشل في الاثنين. log P(W) يحل مشكلة underflow فقط لا الطول. متوسط log P لكل كلمة ينجح في الطول ويساوي −log₂(PP) بالـ bits. وperplexity ينجح في الاثنين ويُقرأ كـ branching factor، ولذلك هو المقياس القياسي.

The next page builds perplexity from these two requirements step by step.

الصفحة التالية تبني perplexity من هذين الشرطين خطوة بخطوة.

One more caution before you trust perplexity

تحذير أخير قبل أن تثق بالـ perplexity

Perplexity is intrinsic. Lower perplexity usually correlates with better downstream performance, but it is not a guarantee. If a decision matters, confirm it extrinsically on the real task.

Perplexity مقياس intrinsic. انخفاضه يرتبط عادة بأداء أفضل في المهمة النهائية، لكنه ليس ضماناً. وإذا كان القرار مهماً، فأكّده extrinsically على المهمة الحقيقية.

Check yourself

اختبر نفسك

You swap your bigram LM into a speech recognizer and the word error rate drops from 14.2% to 12.8%. What kind of evaluation is that?

أدخلت نموذج bigram في نظام speech recognizer فانخفض word error rate من 14.2% إلى 12.8%. أي نوع من التقييم هذا؟

Judging the LM through a downstream task (ASR, MT) is extrinsic by definition. Option D is the specific error the slides warn about: WER and perplexity are correlated but not monotonically related, so an intrinsic gain does not guarantee an extrinsic one.

الجواب B. تقييم language model عبر مهمة نهائية مثل ASR أو MT هو extrinsic بالتعريف. والخيار D هو الخطأ الذي تحذّر منه الشرائح تحديداً: WER وperplexity مترابطان لكن ليست علاقتهما رتيبة (monotonic)، فالتحسن في intrinsic لا يضمن تحسناً في extrinsic.

Why does a unigram model perform so badly at the Shannon Game?

لماذا أداء نموذج unigram سيئ جداً في Shannon Game؟

A unigram model has no conditioning at all, so "pizza with cheese and ___" and "I saw a ___" get identical predictions, dominated by corpus-wide frequent words. Option C is backwards: unigrams suffer less from zeros than bigrams, because every word that appears at all has a non-zero unigram count. Sparsity gets worse with longer n-grams, not better.

الجواب D. نموذج unigram لا يشترط على أي سياق، فعبارة "pizza with cheese and ___" وعبارة "I saw a ___" تحصلان على تنبؤات متطابقة تسيطر عليها الكلمات الأكثر تكراراً في corpus. والخيار C معكوس: نماذج unigram تعاني من الأصفار أقل من bigram، لأن كل كلمة ظهرت ولو مرة لها عدّة غير صفرية. التشتت (sparsity) يسوء مع زيادة طول n-gram لا العكس.

You run 40 experiments, each time evaluating perplexity on the test set and keeping whichever smoothing parameter scored lowest. No test sentence was ever in the training data. What is wrong?

أجريت 40 تجربة، في كل مرة تقيس perplexity على test set وتُبقي قيمة smoothing التي أعطت أدنى نتيجة. ولم تدخل أي جملة اختبار في بيانات التدريب. ما الخطأ؟

Contamination is not only literal leakage. Every evaluation you use to make a decision passes test-set information into the model through your choices, so after 40 peeks the minimum you report is biased low. Hyperparameter selection belongs on the dev set; the test set is run once at the end.

الجواب C. Contamination ليس التسرب الحرفي فقط. كل تقييم تستخدمه لاتخاذ قرار ينقل معلومات من test set إلى النموذج عبر اختياراتك، فبعد 40 نظرة يكون الحد الأدنى الذي تُبلّغ به متحيزاً نحو الأسفل. اختيار hyperparameters مكانه dev، وtest set يُشغَّل مرة واحدة في النهاية.

A test sentence accidentally appears in the training corpus. What happens to the perplexity you measure on it?

ظهرت جملة من الاختبار بالخطأ داخل training corpus. ماذا يحدث لـ perplexity التي تقيسها عليها؟

The model has counts for every bigram in that sentence, so the probability it assigns is high and the perplexity is low. Low perplexity is normally good news, which is why leakage is dangerous: it looks like success. Normalizing by token count (option C) fixes length, not contamination.

الجواب A. النموذج يملك عدّات لكل bigram في تلك الجملة، فالاحتمال الذي يعطيه مرتفع وperplexity منخفضة. وperplexity المنخفضة خبر سار عادة، ولهذا فإن leakage خطير: يبدو كأنه نجاح. والتطبيع على عدد الـ tokens (الخيار C) يحل مشكلة الطول، لا مشكلة contamination.

Why is raw P(W) rejected as an evaluation metric for language models?

لماذا يُرفض P(W) الخام كمقياس تقييم للنماذج اللغوية؟

Every chain-rule factor is at most 1, so the product can only decrease with length. A 1000-token test set always scores lower than a 10-token one regardless of the model, which makes the numbers incomparable. The fix is a length-normalized per-word score, and that is perplexity. Option C is impossible: a probability can never exceed 1.

الجواب B. كل عامل في chain rule لا يزيد عن 1، فحاصل الضرب لا يمكن إلا أن ينقص مع الطول. نص اختبار من 1000 token يحصل دائماً على درجة أدنى من نص من 10 بغض النظر عن النموذج، وهذا يجعل الأرقام غير قابلة للمقارنة. والحل درجة لكل كلمة مُطبَّعة على الطول، وهي perplexity. أما الخيار C فمستحيل: الاحتمال لا يتجاوز 1 أبداً.