ICS 582Lecture 02المحاضرة 02Full guideالشرح الكامل
Words and tokensالكلمات والرموز (Tokens)
The whole lecture on one page, taught concept by concept. Work through the parts in order, mark each concept once you understand it, and open the slide chips when you want the original slides.المحاضرة كاملة في صفحة واحدة، مشروحة مفهومًا مفهومًا. امشِ على الأجزاء بالترتيب، وعلّم كل مفهوم بعد أن تفهمه، وافتح أزرار الشرائح عندما تريد الرجوع إلى الشرائح الأصلية.
- Partsالأجزاء
- 11
- Conceptsالمفاهيم
- 46
- Slidesالشرائح
- 94
- Readingمدة القراءة
- 276 min276 دقيقة
Part 01: What counts as a wordما الذي يُعد كلمة
Why a word is not a universal unit, the difference between tokens and types, how corpus vocabularies compare, and the preprocessing decisions every tokenizer must make.لماذا الكلمة ليست وحدة عالمية، والفرق بين الرموز (tokens) والأنواع (types)، وكيف تُقارن مفردات المدونات، وقرارات المعالجة المسبقة التي يجب أن يتخذها كل مُقسِّم (tokenizer).
4 concepts4 مفاهيم, ، slides 1-10الشرائح 1-10
Why this part mattersلماذا يهمّ هذا الجزء
Every count, probability, embedding table and cost estimate in NLP starts from a decision about what a unit is. Before a language model can predict the next token, before a retrieval system can index a document, and before Zipf or Heaps can be plotted, someone has to say where one unit ends and the next begins.
This part makes that decision visible. It starts from a sentence that has no single word count, gives you the two definitions every later formula depends on (token and type), reads one famous table of corpus sizes, and finishes with the checklist of preprocessing choices a tokenizer must make. Your research pipeline will fix a tokenization policy once, and every N, |V| and sequence length downstream inherits it. Exams ask for token and type counts under a stated policy and for the consequences of each preprocessing choice.
كل عدّ، وكل احتمال، وكل جدول تضمينات (embedding table)، وكل تقدير للتكلفة في معالجة اللغات الطبيعية يبدأ من قرار حول ماهية الوحدة. قبل أن يتنبأ نموذج اللغة بالوحدة النصية التالية، وقبل أن يفهرس نظام الاسترجاع مستندًا، وقبل أن نرسم قانون Zipf أو Heaps، لا بد أن يحدد أحدٌ أين تنتهي وحدة وأين تبدأ التي تليها.
هذا الجزء يجعل ذلك القرار مرئيًا. يبدأ من جملة ليس لها عدد كلمات واحد، ثم يعطيك التعريفين اللذين تعتمد عليهما كل صيغة لاحقة (الوحدة النصية token والنوع type)، ثم يقرأ جدولًا شهيرًا لأحجام المدونات، وينتهي بقائمة اختيارات المعالجة المسبقة التي يجب أن يحسمها أي مقطِّع (tokenizer). ستثبّت سلسلة المعالجة في بحثك سياسة تقطيع مرة واحدة، وكل N و|V| وطول تسلسل بعدها يرث تلك السياسة. الاختبارات تطلب عدد الوحدات النصية والأنواع وفق سياسة محددة، وتطلب نتائج كل اختيار من اختيارات المعالجة المسبقة.
By the end you canفي نهاية هذا الجزء ستستطيع
- State the token and type definitions and compute N and |V| for a given string under a stated policy for case and punctuation.أن تذكر تعريفَي الوحدة النصية (token) والنوع (type)، وتحسب N و|V| لنص معطى وفق سياسة محددة للتعامل مع حالة الأحرف وعلامات الترقيم.
- Explain why the same sentence has 16 or 18 tokens and 14 or 16 types depending on the policy, and why speech transcripts may keep uh and main-.أن تشرح لماذا تحتوي الجملة نفسها على 16 أو 18 وحدة نصية و14 أو 16 نوعًا بحسب السياسة المتبعة، ولماذا قد تُبقي نصوص الكلام المفرّغ على uh وmain-.
- Read the SLP3 corpus table, compute the type to token ratio, and explain both the falling ratio and the Switchboard genre effect.أن تقرأ جدول المدونات في SLP3، وتحسب نسبة الأنواع إلى الوحدات النصية، وتشرح سبب انخفاض هذه النسبة وأثر النوع الأدبي في Switchboard.
- Name the four preprocessing decisions and the four ambiguous boundaries, with one downstream consequence each, and state the Penn Treebank convention.أن تسمّي قرارات المعالجة المسبقة الأربعة والحدود الملتبسة الأربعة مع نتيجة لاحقة واحدة لكل منها، وأن تذكر اصطلاح Penn Treebank.
The whole lecture answers one question: what unit does a model operate on, and how do we get from raw bytes to that unit? Everything else is a stop on the way. The roadmap has eight stops, and it is worth holding the shape in mind because the lecture overview page mirrors it exactly.
المحاضرة كلها تجيب عن سؤال واحد: ما الوحدة التي يعمل عليها النموذج، وكيف ننتقل من البايتات الخام إلى تلك الوحدة؟ وكل ما عدا ذلك محطة على الطريق. خريطة الطريق فيها ثماني محطات، ومن المفيد أن تبقي شكلها في ذهنك لأن صفحة نظرة عامة على المحاضرة تعكسها تمامًا.
- Words, with Zipf and Heaps. How to count units, and the two laws that govern how frequency and vocabulary behave as a corpus grows.الكلمات، مع قانونَي Zipf وHeaps. كيف نعدّ الوحدات، والقانونان اللذان يحكمان سلوك التكرار والمفردات كلما كبرت المدونة.
- Morphemes. The meaningful parts inside a word, which explain why walk, walks and walked are one lemma but three types.المورفيمات (Morphemes). الأجزاء ذات المعنى داخل الكلمة، وهي التي تفسر لماذا تكون walk وwalks وwalked أصلًا معجميًا (lemma) واحدًا لكنها ثلاثة أنواع (types).
- Corpora. Where the text comes from, and why genre, domain and time shift every count in this part.المدونات النصية (Corpora). من أين يأتي النص، ولماذا يغيّر النوع الأدبي والمجال والزمن كل رقم في هذا الجزء.
- Unicode. How characters become bytes, so that a tokenizer can promise to represent any script without an unknown symbol.يونيكود (Unicode). كيف تتحول الحروف إلى بايتات، حتى يستطيع المقطِّع (tokenizer) أن يضمن تمثيل أي نظام كتابة دون رمز مجهول.
- Tokenization with BPE. The algorithm that learns its own units from data instead of trusting spaces.التقطيع (Tokenization) باستخدام BPE. الخوارزمية التي تتعلم وحداتها بنفسها من البيانات بدلًا من الوثوق بالمسافات.
- Sentence segmentation. The period that ends a sentence versus the period inside Dr. or U.S.تقسيم الجمل (Sentence segmentation). النقطة التي تنهي الجملة مقابل النقطة الموجودة داخل Dr. أو U.S.
- Regular expressions. The pattern language behind pre-tokenizers, cleaners and feature extractors.التعبيرات النمطية (Regular expressions). لغة الأنماط التي تقوم عليها مراحل ما قبل التقطيع (pre-tokenizers) وأدوات تنظيف النص ومستخرجات السمات.
- Minimum edit distance. A distance between strings that scores spelling correction and speech recognizers alike.أدنى مسافة تحرير (Minimum edit distance). مقياس للمسافة بين سلسلتين نصيتين يُستخدم لتقييم التصحيح الإملائي وأنظمة التعرف على الكلام على حد سواء.
The first stop carries Zipf's law and Heaps' law. The second is the Morpheme. The third is the Corpus. The fourth turns a Code point into UTF-8 bytes. The fifth is Tokenization and byte-pair encoding. Then come Sentence segmentation, the Regular expression and, finally, Minimum edit distance. This part covers only the opening of the first stop, but it sets the vocabulary every later part reuses.
المحطة الأولى تحمل Zipf's law (قانون Zipf) وHeaps' law (قانون Heaps). والثانية هي المورفيم (morpheme). والثالثة هي المدونة النصية (corpus). والرابعة تحوّل نقطة الترميز (code point) إلى بايتات UTF-8. والخامسة هي التقطيع (tokenization) وترميز أزواج البايتات (byte-pair encoding). ثم يأتي تقسيم الجمل (sentence segmentation)، والتعبير النمطي (regular expression)، وأخيرًا أدنى مسافة تحرير (minimum edit distance). هذا الجزء يغطي بداية المحطة الأولى فقط، لكنه يضع المفردات التي يعيد كل جزء لاحق استخدامها.
The seven learning goals on slide 3 map onto the same stops: know why a word is not a universal unit, distinguish types from tokens and explain why vocabulary keeps growing, know what morphemes are, explain Unicode and byte-level processing, describe BPE and tokenizer design choices, use regular expressions, and compute minimum edit distance with dynamic programming. The first two goals are this part.
أهداف التعلم السبعة في الشريحة 3 ترتبط بالمحطات نفسها: أن تعرف لماذا ليست الكلمة وحدة عالمية، وأن تميّز الأنواع (types) من الوحدات النصية (tokens) وتشرح لماذا تستمر المفردات في النمو، وأن تعرف ما المورفيمات، وأن تشرح Unicode والمعالجة على مستوى البايت، وأن تصف BPE وخيارات تصميم المقطِّع، وأن تستخدم التعبيرات النمطية، وأن تحسب أدنى مسافة تحرير بالبرمجة الديناميكية (dynamic programming). الهدفان الأولان هما موضوع هذا الجزء.
Recall
Name the eight stops of the lecture roadmap in order.اذكر محطات خريطة طريق المحاضرة الثماني بالترتيب.
Count the words in this sentence before reading on: They picnicked by the pool, then lay back on the grass and looked at the stars. Most people say sixteen. Some say eighteen. Both are right, and the reason they can both be right is the subject of this concept.
عُدّ الكلمات في هذه الجملة قبل أن تكمل القراءة: They picnicked by the pool, then lay back on the grass and looked at the stars. معظم الناس يقولون ست عشرة. وبعضهم يقول ثماني عشرة. كلاهما صحيح، وسبب إمكان صحة الإجابتين معًا هو موضوع هذا المفهوم.
Worked exampleمثال محلول
Counting the picnic sentence three waysعدّ جملة النزهة بثلاث طرق
Split on spacesالتقسيم عند المسافات
Sixteen pieces: They, picnicked, by, the, pool,, then, lay, back, on, the, grass, and, looked, at, the, stars. The comma and the period ride along inside the pieces they touch.ست عشرة قطعة: They، picnicked، by، the، pool,، then، lay، back، on، the، grass، and، looked، at، the، stars. الفاصلة والنقطة تبقيان ملتصقتين بالقطعتين اللتين تلامسانهما.Give punctuation its own placeامنح علامات الترقيم مكانًا مستقلًا
Cut the comma off pool and the period off stars. Now there are eighteen units. Jurafsky and Martin note that large language models generally count punctuation as separate words, so eighteen is the modern default rather than a quirk.افصل الفاصلة عن pool والنقطة عن stars. الآن أصبح لدينا ثماني عشرة وحدة. ويلاحظ Jurafsky وMartin أن نماذج اللغة الكبيرة تعدّ علامات الترقيم عمومًا كلمات منفصلة، لذلك فإن ثماني عشرة هي الافتراض الحديث وليست حالة شاذة.Collapse repeatsادمج المتكررات
the occurs three times. Counting each distinct item once gives fourteen distinct words without punctuation, or sixteen if the comma and the period are counted as distinct items too.تظهر the ثلاث مرات. عدّ كل عنصر مميز مرة واحدة يعطي أربع عشرة كلمة مميزة دون علامات الترقيم، أو ست عشرة إذا عُدّت الفاصلة والنقطة عنصرين مميزين أيضًا.Lowercaseتحويل الأحرف إلى صغيرة
Folding They to they changes nothing here, because no other they appears. In another sentence it would merge two distinct items into one.تحويل They إلى they لا يغيّر شيئًا هنا، لأنه لا توجد they أخرى في الجملة. أما في جملة أخرى فقد يدمج عنصرين مميزين في عنصر واحد.Four answers, one sentenceأربع إجابات، جملة واحدة
The sentence never changed. The counting policy did.Policyالسياسة Tokens Nالوحدات النصية N Types |V|الأنواع |V| Whitespace onlyالمسافات فقط 1616 1414 Punctuation splitفصل علامات الترقيم 1818 1616 The picnic sentence under two counting policiesجملة النزهة وفق سياستين للعدّ الجملة لم تتغير. الذي تغيّر هو سياسة العدّ.Policyالسياسة Tokens Nالوحدات النصية N Types |V|الأنواع |V| Whitespace onlyالمسافات فقط 1616 1414 Punctuation splitفصل علامات الترقيم 1818 1616 The picnic sentence under two counting policiesجملة النزهة وفق سياستين للعدّ
In many writing systems spaces suggest boundaries, but a space is only a suggestion. The moment you want a number, you have to decide what to do with everything that a space does not settle, and each decision is tied to what the text is for. Splitting text into units is Tokenization, and the resulting units are tokens. Jurafsky and Martin put it plainly: how we define words depends on the task. The table below pairs each question from the slide with a task that answers yes and a task that answers no.
في كثير من أنظمة الكتابة توحي المسافات بالحدود، لكن المسافة مجرد إيحاء. فبمجرد أن تريد رقمًا، عليك أن تقرر ماذا تفعل بكل ما لا تحسمه المسافة، وكل قرار مرتبط بالغرض من النص. تقسيم النص إلى وحدات هو التقطيع (tokenization)، والوحدات الناتجة هي الوحدات النصية (tokens). ويقولها Jurafsky وMartin بوضوح: طريقة تعريفنا للكلمات تعتمد على المهمة. الجدول أدناه يقرن كل سؤال من الشريحة بمهمة تجيب بنعم ومهمة تجيب بلا.
| Questionالسؤال | A task that says yesمهمة تجيب بنعم | A task that says noمهمة تجيب بلا |
|---|---|---|
| Is punctuation its own token?هل علامة الترقيم وحدة نصية مستقلة؟ | Language models and parsers, where a period or a question mark carries meaningنماذج اللغة والمحللات النحوية، حيث تحمل النقطة أو علامة الاستفهام معنى | Bag-of-words retrieval, where punctuation only adds noiseالاسترجاع بحقيبة الكلمات (bag-of-words)، حيث لا تضيف علامات الترقيم إلا ضوضاء |
| Do we lowercase?هل نحوّل الأحرف إلى صغيرة؟ | Information retrieval, where a query rarely matches the case of the documentاسترجاع المعلومات، حيث نادرًا ما يطابق الاستعلام حالة الأحرف في المستند | Named entity recognition and part-of-speech tagging, where a capital is evidenceالتعرف على الكيانات المسماة ووسم أقسام الكلام، حيث يكون الحرف الكبير دليلًا |
| How do we treat numbers, URLs, emojis, hashtags?كيف نتعامل مع الأرقام والروابط والرموز التعبيرية والوسوم؟ | Social media analysis keeps #NLP and emojis whole because they carry sentimentتحليل وسائل التواصل الاجتماعي يُبقي #NLP والرموز التعبيرية كاملة لأنها تحمل المشاعر | A grammar checker may replace every number by one placeholderمدقق القواعد قد يستبدل كل رقم بعنصر نائب واحد |
| Do we keep disfluencies?هل نُبقي على تعثرات الكلام؟ | Speech recognition, where uh predicts a restart and identifies the speakerالتعرف على الكلام، حيث تتنبأ uh بإعادة البدء وتساعد على تحديد هوية المتحدث | Parsing and translation, which want the fluent sentence underneathالتحليل النحوي والترجمة، اللذان يريدان الجملة السليمة الكامنة تحتها |
Speech: where the units fall apartالكلام المنطوق: حيث تتفكك الوحدات
Written text at least offers spaces. A transcript of spontaneous speech offers something stranger. Consider the utterance I do uh main- mainly business data processing. There is a broken-off word, main-, which Jurafsky and Martin call a fragment, and a filler, uh, which they call a filled pause. Together these are a Disfluency. Should a tokenizer keep them?
النص المكتوب يقدم المسافات على الأقل. أما تفريغ الكلام العفوي فيقدم شيئًا أغرب. تأمل العبارة I do uh main- mainly business data processing. فيها كلمة مبتورة هي main-، يسميها Jurafsky وMartin جزءًا مبتورًا (fragment)، وفيها حشوة هي uh، يسميانها وقفة مملوءة (filled pause). ومعًا يشكلان ما يسمى تعثر الكلام (disfluency). فهل ينبغي للمقطِّع أن يحتفظ بهما؟
For speech recognition the answer is yes, and for a reason that surprises people: fillers help predict the upcoming word, because they signal that the speaker is restarting the clause or idea, and they are a cue to speaker identification. Clark and Fox Tree went further and argued that uh and um are conventional English words: uh announces an expected minor delay, um a major one. A parser or a translation system, on the other hand, wants the fluent sentence underneath, so it drops them. The Switchboard portion of the Penn Treebank release is explicitly annotated for disfluencies, so this decision is built into a real corpus, not a thought experiment.
بالنسبة للتعرف على الكلام فالإجابة نعم، ولسبب يفاجئ الناس: الحشوات تساعد على التنبؤ بالكلمة القادمة، لأنها تشير إلى أن المتحدث يعيد بدء الجملة أو الفكرة، كما أنها دليل يساعد على تحديد هوية المتحدث. وذهب Clark وFox Tree أبعد من ذلك، فقالا إن uh وum كلمتان إنجليزيتان متعارف عليهما: uh تعلن عن تأخير بسيط متوقع، وum عن تأخير كبير. أما المحلل النحوي (parser) أو نظام الترجمة فيريد الجملة السليمة الكامنة تحتها، لذلك يحذفهما. والجزء الخاص بـ Switchboard في إصدار Penn Treebank موسوم صراحة بتعثرات الكلام، فهذا القرار مبني داخل مدونة حقيقية، وليس تجربة ذهنية.
Languages with no spaces at allلغات بلا مسافات على الإطلاق
The space is a convention of some scripts, not of language. Chinese, Japanese and Thai are written without spaces between words, so there is no orthographic word to count. Jurafsky and Martin give a Chinese sentence about Yao Ming reaching the finals and show that its units depend on which standard you adopt. Chinese words average only 1.5 to 1.9 characters, so the character is often the practical unit, and the question "how many words?" simply has no answer until a segmentation standard is chosen.
المسافة عُرف في بعض أنظمة الكتابة، وليست من طبيعة اللغة. فالصينية واليابانية والتايلاندية تُكتب دون مسافات بين الكلمات، فلا توجد كلمة إملائية لنعدّها. ويعرض Jurafsky وMartin جملة صينية عن وصول Yao Ming إلى النهائيات، ويبيّنان أن وحداتها تعتمد على المعيار الذي تعتمده. متوسط طول الكلمة الصينية 1.5 إلى 1.9 حرف فقط، لذلك يكون الحرف في الغالب هو الوحدة العملية، والسؤال «كم كلمة؟» ببساطة لا جواب له حتى يُختار معيار للتقسيم.
One Chinese sentence, three counts (SLP3 section 2.1)جملة صينية واحدة، ثلاثة أعداد (SLP3، القسم 2.1)
- Chinese Treebank standardمعيار Chinese Treebank
- 3 words3 كلمات
- Peking University standardمعيار جامعة بكين (Peking University)
- 5 words5 كلمات
- Charactersالحروف
- 7 units7 وحدات
Recall
How many tokens and types does the picnic sentence have without punctuation, and with it?كم عدد الوحدات النصية (tokens) والأنواع (types) في جملة النزهة دون علامات الترقيم، وكم عددها معها؟
Recall
Give two reasons Jurafsky and Martin give for keeping uh and um in speech recognition.اذكر سببين يقدمهما Jurafsky وMartin للإبقاء على uh وum في التعرف على الكلام.
Quick checkاختبار سريع
Which of these is a reason a speech recognizer keeps the filler uh while a parser drops it?أيٌّ من الآتي سببٌ لاحتفاظ نظام التعرف على الكلام بالحشوة uh بينما يحذفها المحلل النحوي؟
Once a policy is fixed, two numbers describe any text. Take Hamlet's to be or not to be. Six units are written down in order. Only four different ones appear, because to and be each occur twice. Those two numbers have names, and the whole of corpus statistics is built on them.
بمجرد تثبيت السياسة، يصف أي نص رقمان. خذ عبارة هاملت to be or not to be. هناك ست وحدات مكتوبة بالترتيب. ولا يظهر منها إلا أربع مختلفة، لأن to وbe تتكرر كل منهما مرتين. لهذين الرقمين اسمان، وعليهما يقوم علم إحصاءات المدونات كله.
A Token is one occurrence of a unit in running text, and the total count of tokens is written N. A Type is a distinct vocabulary item, and the number of types is the size of the Vocabulary, written |V|. So to be or not to be has N = 6 tokens and |V| = 4 types: to, be, or, not. The two are tied together by a bookkeeping identity: every token belongs to exactly one type, so the type counts add up to the token count.
الوحدة النصية (token) هي ظهور واحد لوحدة في النص الجاري، ويُرمز لإجمالي عدد الوحدات النصية بـ N. والنوع (type) هو عنصر مفردات مميز، وعدد الأنواع هو حجم المفردات (vocabulary) ويُرمز له بـ |V|. إذن to be or not to be فيها N = 6 وحدات نصية و|V| = 4 أنواع: to، be، or، not. ويربط بينهما تطابق محاسبي: كل وحدة نصية تنتمي إلى نوع واحد بالضبط، لذلك يساوي مجموع أعداد الأنواع عدد الوحدات النصية.
Try it yourself. The counter below applies a tokenization policy to a sentence and recomputes both numbers live. Start with the picnic sentence, switch on punctuation splitting and watch N go from 16 to 18. Then load the Apple sentence and flip lowercase: N stays put while |V| drops, because Apple and apple have become one type. That asymmetry is the whole lesson of the next concept in miniature.
جرّبها بنفسك. العدّاد أدناه يطبق سياسة تقطيع على جملة ويعيد حساب الرقمين مباشرة. ابدأ بجملة النزهة، وفعّل فصل علامات الترقيم، وراقب N ينتقل من 16 إلى 18. ثم حمّل جملة Apple وفعّل تحويل الأحرف إلى صغيرة: يبقى N كما هو بينما ينخفض |V|، لأن Apple وapple أصبحتا نوعًا واحدًا. هذا اللاتماثل هو درس المفهوم التالي كله في صورة مصغرة.
16 tokens, 14 types
- They×1
- picnicked×1
- by×1
- the×3
- pool,×1
- then×1
- lay×1
- back×1
- on×1
- grass×1
- and×1
- looked×1
- at×1
- stars.×1
Punctuation and clitic tokens are teal, the <NUM> placeholder is in the accent color. Watch both counts change as you flip each policy.رموز علامات الترقيم والملحقات باللون الأخضر المزرق، والبديل <NUM> باللون المميز. راقب تغيّر العددين كلما بدّلت أي سياسة.
Five corpora, one tableخمس مدونات، جدول واحد
Jurafsky and Martin collect rough counts for several English corpora, and the lecture reproduces their table. Two columns are on the slide. The two on the right are computed here: types per thousand tokens, and its reciprocal, tokens per type. Read those computed columns first, because they tell a story the raw counts hide.
يجمع Jurafsky وMartin أعدادًا تقريبية لعدة مدونات إنجليزية، والمحاضرة تعيد عرض جدولهما. عمودان موجودان في الشريحة. أما العمودان على اليمين فمحسوبان هنا: عدد الأنواع لكل ألف وحدة نصية، ومقلوبه، أي عدد الوحدات النصية لكل نوع. اقرأ هذين العمودين المحسوبين أولًا، لأنهما يرويان قصة تخفيها الأعداد الخام.
| Corpusالمدونة | Genreالنوع الأدبي | Types |V|الأنواع |V| | Tokens Nالوحدات النصية N | Types per 1,000 tokensالأنواع لكل 1,000 وحدة نصية | Tokens per typeالوحدات النصية لكل نوع |
|---|---|---|---|---|---|
| ShakespeareShakespeare | Plays and poemsمسرحيات وقصائد | 31 thousand31 ألفًا | 884 thousand884 ألفًا | 35.135.1 | 28.528.5 |
| Brown corpusمدونة Brown | 15 written genres, 196115 نوعًا أدبيًا مكتوبًا، 1961 | 38 thousand38 ألفًا | 1 millionمليون واحد | 38.038.0 | 26.326.3 |
| SwitchboardSwitchboard | Telephone conversationمحادثات هاتفية | 20 thousand20 ألفًا | 2.4 million2.4 مليون | 8.38.3 | 120120 |
| COCACOCA | 8 balanced genres8 أنواع أدبية متوازنة | 2 million2 مليون | 440 million440 مليونًا | 4.54.5 | 220220 |
| Google n-gramsGoogle n-grams | Web textنصوص الويب | 13 million13 مليونًا | 1 trillion1 تريليون | 0.0130.013 | 76,92376,923 |
Down the table, N grows by six orders of magnitude while |V| grows by less than three. The ratio of types to tokens falls from about 35 per thousand for Shakespeare to about 0.013 per thousand for the Google corpus. This is the first preview of Heaps' law: vocabulary grows without bound but sublinearly, |V| = k N^β with β between 0 and 1, and Jurafsky and Martin report values from 0.44 to 0.56 or higher, so vocabulary goes up a little faster than the square root of the text length. Part 02 fits that law properly; here it is enough to see the bend.
بالنزول في الجدول، يكبر N بست مراتب عشرية بينما يكبر |V| بأقل من ثلاث. وتنخفض نسبة الأنواع إلى الوحدات النصية (type to token ratio) من نحو 35 لكل ألف في شكسبير إلى نحو 0.013 لكل ألف في مدونة Google. وهذه أول لمحة عن قانون Heaps: المفردات تنمو بلا حد لكن بمعدل أبطأ من الخطي، |V| = k N^β حيث β بين 0 و1، ويذكر Jurafsky وMartin قيمًا من 0.44 إلى 0.56 أو أعلى، أي أن المفردات تزداد أسرع قليلًا من الجذر التربيعي لطول النص. الجزء 02 يطابق هذا القانون على البيانات بشكل كامل؛ وهنا يكفي أن ترى الانحناء.
Now read across rows instead of down. Brown has one million tokens and 38 thousand types. Switchboard has more than twice as many tokens and only 20 thousand types, fewer even than Shakespeare with a third of Switchboard's tokens. Size alone cannot explain that. Switchboard is about 2,400 telephone conversations among 543 speakers on about 70 everyday topics, and casual conversation reuses a small everyday vocabulary. Brown samples 500 texts across 15 written genres, and Shakespeare's plays reach for coinages and archaic forms. This is the point of slide 6: even within one language, genre and domain shift the vocabulary, so |V| depends on the Corpus, not only on N.
اقرأ الآن عبر الصفوف بدلًا من النزول. في Brown مليون وحدة نصية و38 ألف نوع. وفي Switchboard أكثر من ضعف عدد الوحدات النصية لكن 20 ألف نوع فقط، أي أقل حتى من شكسبير الذي لديه ثلث وحدات Switchboard النصية. الحجم وحده لا يفسر ذلك. فـ Switchboard يضم نحو 2,400 محادثة هاتفية بين 543 متحدثًا حول نحو 70 موضوعًا يوميًا، والمحادثة العفوية تعيد استخدام مفردات يومية قليلة. أما Brown فيأخذ عينات من 500 نص عبر 15 نوعًا أدبيًا مكتوبًا، ومسرحيات شكسبير تلجأ إلى الكلمات المبتكرة والصيغ القديمة. هذه هي فكرة الشريحة 6: حتى داخل اللغة الواحدة، يغيّر النوع الأدبي والمجال المفردات، لذلك يعتمد |V| على المدونة (corpus)، وليس على N وحده.
Why the vocabulary never stops growingلماذا لا تتوقف المفردات عن النمو
The falling ratio and the endless growth have the same cause. Function words like the and of are seen early and then only repeat. Content words keep arriving. Slide 8 lists where they come from, and each source is a reason your model will meet a word it has never seen.
للنسبة المتناقصة والنمو الذي لا ينتهي سبب واحد. الكلمات الوظيفية مثل the وof تُرى مبكرًا ثم تتكرر فقط. أما كلمات المحتوى فتستمر في الوصول. والشريحة 8 تذكر مصادرها، وكل مصدر منها سبب لأن يصادف نموذجك كلمة لم يرها من قبل.
- Proper names and new products: every person, place, company and gadget is a type, and new ones appear every day.أسماء العلم والمنتجات الجديدة: كل شخص ومكان وشركة وجهاز هو نوع (type)، وتظهر أسماء جديدة كل يوم.
- Creative spellings and typos: cooool, gr8 and every misspelling is a fresh type under a wordform policy.التهجئات الإبداعية والأخطاء الإملائية: cooool وgr8 وكل خطأ إملائي هو نوع جديد في ظل سياسة تعتمد صيغة الكلمة (wordform).
- Code-switching: speakers mix languages within one utterance, so an English corpus carries Spanish, Hindi or Arabic types as well.التناوب اللغوي (Code-switching): يخلط المتحدثون اللغات داخل عبارة واحدة، لذلك تحمل المدونة الإنجليزية أنواعًا إسبانية أو هندية أو عربية أيضًا.
- Morphology: walk, walks, walked and walking are four wordform types but one Lemma. Inflection multiplies surface forms, and morphologically rich languages multiply them far more.الصرف: walk وwalks وwalked وwalking أربعة أنواع من حيث صيغة الكلمة لكنها أصل معجمي واحد (lemma). والتصريف (inflection) يضاعف الصيغ السطحية، واللغات الغنية صرفيًا تضاعفها أكثر بكثير.
- Compounding and multiword expressions: New York and ice cream behave as single lexical units but span a space. Sag and colleagues called multiword expressions a pain in the neck for NLP, and Jurafsky and Martin note that tokenizing them needs a dictionary and is tied up with named entity recognition.التركيب والتعبيرات متعددة الكلمات: New York وice cream تتصرفان كوحدتين معجميتين مفردتين لكنهما تمتدان عبر مسافة. وقد وصف Sag وزملاؤه التعبيرات متعددة الكلمات بأنها مصدر إزعاج كبير لمعالجة اللغات الطبيعية (a pain in the neck for NLP)، ويلاحظ Jurafsky وMartin أن تقطيعها يحتاج إلى قاموس ومرتبط بالتعرف على الكيانات المسماة (named entity recognition).
The consequence is that out-of-vocabulary words are unavoidable under any word-level policy. However large the training corpus, tomorrow's text contains a name or a typo that is not in V. That is the problem subword tokenization solves later in this lecture, by building rare words out of pieces that are in the vocabulary.
والنتيجة أن الكلمات خارج المفردات (out-of-vocabulary) أمر لا مفر منه في أي سياسة على مستوى الكلمة. فمهما كبرت مدونة التدريب، سيحتوي نص الغد على اسم أو خطأ إملائي غير موجود في V. وهذه هي المشكلة التي يحلها التقطيع إلى أجزاء الكلمات (subword) لاحقًا في هذه المحاضرة، ببناء الكلمات النادرة من قطع موجودة في المفردات.
Recall
Define token and type, then give N and |V| for 'to be or not to be'.عرّف الوحدة النصية (token) والنوع (type)، ثم أعطِ N و|V| لعبارة 'to be or not to be'.
Recall
Why does Switchboard have fewer types than Shakespeare despite almost three times as many tokens?لماذا يحتوي Switchboard على أنواع أقل من شكسبير رغم أن وحداته النصية تقارب ثلاثة أضعاف؟
Quick checkاختبار سريع
Counting punctuation as tokens and ignoring case, what are N and |V| for 'to be, or not to be.'?إذا عددنا علامات الترقيم وحدات نصية وتجاهلنا حالة الأحرف، فما قيمتا N و|V| لعبارة 'to be, or not to be.'؟
Quick checkاختبار سريع
Switchboard has almost three times Shakespeare's tokens but fewer types. What explains this?في Switchboard ما يقارب ثلاثة أضعاف الوحدات النصية لدى شكسبير لكن أنواعًا أقل. ما الذي يفسر ذلك؟
Quick checkاختبار سريع
The vocabulary size |V| of a model is best described as a property of which of these?أفضل وصف لحجم المفردات |V| لنموذج ما أنه خاصية لأيٍّ مما يلي؟
Every policy in this part has been described in words. Here is one written down as rules and run on a real sentence. The Penn Treebank convention is the standard for parsed corpora of English, and Jurafsky and Martin use this example to show its output.
كل سياسة في هذا الجزء وُصفت بالكلمات حتى الآن. وهنا سياسة مكتوبة كقواعد ومطبقة على جملة حقيقية. اصطلاح Penn Treebank هو المعيار للمدونات الإنجليزية المحللة نحويًا، ويستخدم Jurafsky وMartin هذا المثال لعرض مخرجاته.
Worked exampleمثال محلول
Penn Treebank tokenization of one sentenceتقطيع جملة واحدة وفق Penn Treebank
Inputالمدخل
"The San Francisco-based restaurant," they said, "doesn't charge $10"."The San Francisco-based restaurant," they said, "doesn't charge $10".Separate all punctuationافصل جميع علامات الترقيم
Each quotation mark, comma and the final period becomes its own token, so restaurant," turns into restaurant, , and ".كل علامة تنصيص وكل فاصلة والنقطة الأخيرة تصبح وحدة نصية مستقلة، لذلك تتحول restaurant," إلى restaurant و, و".Keep hyphenated words togetherأبقِ الكلمات الموصولة بشرطة معًا
Francisco-based stays one token. The convention treats a hyphenated compound as a unit.تبقى Francisco-based وحدة نصية واحدة. فالاصطلاح يعامل المركب الموصول بشرطة كوحدة واحدة.Split cliticsافصل اللواحق المتصلة
doesn't becomes does and n't. Marcus and colleagues describe this in the original Treebank paper: contractions and the Anglo-Saxon genitive of nouns are automatically split into their component morphemes, so children's becomes children and 's, and won't becomes the odd pair wo and n't.تصبح doesn't وحدتين: does وn't. ويصف Marcus وزملاؤه ذلك في ورقة Treebank الأصلية: صيغ الاختصار وحالة الملكية الأنجلوساكسونية للأسماء (Anglo-Saxon genitive) تُفصل تلقائيًا إلى مورفيماتها المكوّنة، لذلك تصبح children's وحدتين: children و's، وتصبح won't الزوج الغريب wo وn't.Separate the currency signافصل رمز العملة
$10 becomes $ and 10.تصبح $10 وحدتين: $ و10.Outputالمخرج
" The San Francisco-based restaurant , " they said , " does n't charge $ 10 " . That is N = 18 tokens and |V| = 14 types, because the four quotation marks are one type and the two commas are one type." The San Francisco-based restaurant , " they said , " does n't charge $ 10 " . أي N = 18 وحدة نصية و|V| = 14 نوعًا، لأن علامات التنصيص الأربع نوع واحد، والفاصلتين نوع واحد.
The four decisionsالقرارات الأربعة
The worked example silently made four decisions, and slide 9 names them. Each has options, each helps some task and each hurts another. The table is the answer to the exam question "list four preprocessing decisions and one downstream consequence of each".
اتخذ المثال المحلول أربعة قرارات بصمت، والشريحة 9 تسمّيها. لكل قرار خيارات، وكل قرار يفيد مهمة ويضر بأخرى. والجدول هو الإجابة عن سؤال الاختبار «اذكر أربعة قرارات للمعالجة المسبقة ونتيجة لاحقة واحدة لكل منها».
| Decisionالقرار | Optionsالخيارات | Helpsيفيد | Hurtsيضر |
|---|---|---|---|
| Case foldingتوحيد حالة الأحرف (case folding) | Keep case, lowercase everything, or truecaseالإبقاء على حالة الأحرف، أو تحويل كل شيء إلى أحرف صغيرة، أو استعادة الحالة الصحيحة (truecasing) | Retrieval recall: a query for apple matches Appleتحسين الاستدعاء في الاسترجاع: الاستعلام عن apple يطابق Apple | Named entity recognition: Apple, Bush, the Fed and General Motors lose their capital evidenceالتعرف على الكيانات المسماة: تفقد Apple وBush وthe Fed وGeneral Motors دليل الحرف الكبير |
| Punctuationعلامات الترقيم | Attach to the word, separate it, or drop itإلصاقها بالكلمة، أو فصلها، أو حذفها | Parsers and sentence segmenters, which read commas and periods as structureالمحللات النحوية ومقسِّمات الجمل، التي تقرأ الفواصل والنقاط على أنها بنية | Dropping loses question marks and quotes; naive splitting breaks m.p.h., Ph.D., $45.55 and 01/02/06الحذف يُضيع علامات الاستفهام والتنصيص؛ والفصل الساذج يكسر m.p.h. وPh.D. و$45.55 و01/02/06 |
| Normalizationالتطبيع (normalization) | Accents, precomposed versus decomposed letters, curly versus straight quotes, hyphen versus dashعلامات التشكيل، والحروف المركّبة مسبقًا مقابل المفككة، وعلامات التنصيص المنحنية مقابل المستقيمة، والشرطة الواصلة مقابل الشرطة الطويلة | Matching and a compact vocabulary: one quote type, not fourالمطابقة ومفردات مدمجة: نوع واحد من علامات التنصيص بدلًا من أربعة | Meaningful distinctions vanish, such as accented pairs in French or a minus sign versus a hyphenتختفي فروق ذات معنى، مثل أزواج الحروف المشكّلة في الفرنسية أو علامة الطرح مقابل الشرطة الواصلة |
| Numbersالأرقام | Keep raw, map to <NUM>, or segment into digit chunksالإبقاء عليها خامًا، أو استبدالها بـ <NUM>، أو تقسيمها إلى مجموعات من الأرقام | <NUM> shrinks |V|; digit chunks let a model generalize arithmetic<NUM> يقلص |V|؛ ومجموعات الأرقام تتيح للنموذج تعميم الحساب | Raw numbers make every price a new type; <NUM> throws away magnitudeالأرقام الخام تجعل كل سعر نوعًا جديدًا؛ و<NUM> يُضيع المقدار |
Case folding is the most tempting shortcut. Manning, Raghavan and Schütze observe that for information retrieval, lowercasing everything often remains the most practical solution, and in the same breath list what it destroys: proper nouns distinguished only by case, such as General Motors, the Fed against fed, and Bush against bush. Their alternative is truecasing, restoring the likely original case with a classifier. Jurafsky and Martin add that for other tasks capitalization is a useful feature and is retained, so some teams keep a cased and an uncased model side by side.
توحيد حالة الأحرف (Case folding) هو الاختصار الأكثر إغراءً. ويلاحظ Manning وRaghavan وSchütze أن تحويل كل شيء إلى أحرف صغيرة يظل في الغالب الحل الأكثر عملية لاسترجاع المعلومات، ويذكرون في الوقت نفسه ما يدمّره: أسماء العلم التي لا يميزها إلا حالة الأحرف، مثل General Motors، وthe Fed مقابل fed، وBush مقابل bush. والبديل عندهم هو استعادة الحالة الصحيحة (truecasing)، أي استرجاع حالة الأحرف الأصلية المرجحة باستخدام مصنِّف. ويضيف Jurafsky وMartin أن حالة الأحرف في مهام أخرى سمة مفيدة فيُحتفظ بها، لذلك تحتفظ بعض الفرق بنموذج يراعي حالة الأحرف (cased) وآخر لا يراعيها (uncased) جنبًا إلى جنب.
Normalization is the quiet one. A Unicode normalization form decides whether the precomposed letter Ç at U+00C7 and the sequence C plus combining cedilla are the same type. Unicode Standard Annex 15 defines four forms, NFC, NFD, NFKC and NFKD, and the same logic applies to four kinds of quotation mark and three kinds of dash that a keyboard and a word processor scatter through any corpus. Skip it and your vocabulary silently holds several copies of the same word.
التطبيع هو القرار الصامت. فصيغة تطبيع يونيكود (Unicode normalization) تقرر هل الحرف المركّب مسبقًا Ç عند U+00C7 والتسلسل C مع علامة السيديا المركِّبة (combining cedilla) نوع واحد أم لا. ويعرّف الملحق القياسي 15 ليونيكود (Unicode Standard Annex 15) أربع صيغ هي NFC وNFD وNFKC وNFKD، والمنطق نفسه ينطبق على أربعة أشكال من علامات التنصيص وثلاثة أشكال من الشرطات تنثرها لوحة المفاتيح ومعالج النصوص في أي مدونة. تجاهله، وستحمل مفرداتك بصمت عدة نسخ من الكلمة نفسها.
Numbers show the trade-off most sharply. Kept raw, every price and every year is a new type and |V| explodes. Mapped to a single <NUM> placeholder, the vocabulary shrinks but the model can no longer tell 12 from 12,000. Modern tokenizers pick a middle path: Jurafsky and Martin describe the GPT-4o tokenizer chunking numbers into groups of up to three digits, so magnitude survives as a sequence of small pieces.
الأرقام تُظهر المفاضلة بأوضح صورة. إذا أُبقيت خامًا، يصبح كل سعر وكل سنة نوعًا جديدًا ويتضخم |V|. وإذا استُبدلت كلها بعنصر نائب واحد <NUM>، تتقلص المفردات لكن النموذج لا يعود قادرًا على التمييز بين 12 و12,000. والمقطِّعات الحديثة تختار طريقًا وسطًا: يصف Jurafsky وMartin مقطِّع GPT-4o الذي يقسم الأرقام إلى مجموعات من ثلاثة أرقام كحد أقصى، فيبقى المقدار محفوظًا كتسلسل من القطع الصغيرة.
The four ambiguous boundariesالحدود الملتبسة الأربعة
Even after the four decisions are made, some characters refuse to settle. Slide 10 collects them. In each case the same character is a boundary in one context and part of a unit in another, and a tokenizer has to pick a default and accept the errors it causes.
حتى بعد اتخاذ القرارات الأربعة، تبقى بعض الحروف عصيّة على الحسم. والشريحة 10 تجمعها. في كل حالة يكون الحرف نفسه حدًا في سياق وجزءًا من وحدة في سياق آخر، وعلى المقطِّع أن يختار افتراضًا ويتقبل الأخطاء التي يسببها.
| Boundaryالحد | Exampleمثال | Treebank defaultافتراض Treebank | Alternativeالبديل |
|---|---|---|---|
| Hyphensالشرطات الواصلة | state-of-the-artstate-of-the-art | Keep the hyphenated word together as one tokenإبقاء الكلمة الموصولة بشرطة معًا كوحدة نصية واحدة | Split into state, of, the, art so each piece is a known typeتقسيمها إلى state وof وthe وart حتى تكون كل قطعة نوعًا معروفًا |
| Abbreviationsالاختصارات | U.S., Dr., e.g.U.S., Dr., e.g. | Keep the internal periods; the trailing period is ambiguous with a sentence endالإبقاء على النقاط الداخلية؛ أما النقطة الأخيرة فملتبسة مع نهاية الجملة | Strip periods entirely, at the cost of merging US the country with us the pronounحذف النقاط كليًا، على حساب دمج US (الدولة) مع us (الضمير) |
| Cliticsاللواحق المتصلة (clitics) | we'll, I'm, possessive 'swe'll، I'm، علامة الملكية 's | Split off the clitic: we 'll, I 'm, children 's, does n't, wo n'tفصل اللاحقة المتصلة: we 'll، I 'm، children 's، does n't، wo n't | Keep the contraction whole, so doesn't and does not are unrelated typesإبقاء الاختصار كاملًا، فتصبح doesn't وdoes not نوعين لا علاقة بينهما |
| Social mediaوسائل التواصل الاجتماعي | #NLP, @user, URLs#NLP، @user، الروابط (URLs) | Splits # and @ off their word and breaks a URL at its colon, slashes and question markيفصل # و@ عن كلمتيهما ويقسم الرابط عند النقطتين الرأسيتين والشرطات المائلة وعلامة الاستفهام | A social-media tokenizer keeps hashtags, handles and URLs whole with dedicated patternsمقطِّع وسائل التواصل الاجتماعي يُبقي الوسوم وأسماء المستخدمين والروابط كاملة بأنماط مخصصة |
A Clitic is the trickiest of the four because the apostrophe is three-way ambiguous. Jurafsky and Martin point out that it marks the genitive (the book's cover), quotation ('The other class', she said) and the contracted clitic (we'll, I'm). Hyphens run from co-education, where the pieces are meaningless alone, to Hewlett-Packard, where each is a name, and Manning and colleagues show there is no rule that suits both. Abbreviation periods will return as the central problem of Sentence segmentation later in the lecture. Social media adds hashtags, handles and URLs that should be kept whole, since #NLP or a web address split at its punctuation is worthless. A Treebank-style tokenizer will not do this by itself: it pads # and @ with spaces and breaks a URL at its colon, so a social-media pipeline adds hashtag, handle and URL patterns in front of it.
اللاحقة المتصلة (clitic) هي الأصعب بين الأربعة لأن الفاصلة العليا (apostrophe) ملتبسة على ثلاثة أوجه. يشير Jurafsky وMartin إلى أنها تدل على الملكية (the book's cover)، وعلى الاقتباس ('The other class', she said)، وعلى اللاحقة المتصلة المختصرة (we'll، I'm). والشرطات الواصلة تتراوح من co-education، حيث لا معنى للقطع منفردة، إلى Hewlett-Packard، حيث كل قطعة اسم، ويبيّن Manning وزملاؤه أنه لا توجد قاعدة تناسب الحالتين. ونقاط الاختصارات ستعود كمشكلة محورية في تقسيم الجمل (sentence segmentation) لاحقًا في المحاضرة. وتضيف وسائل التواصل الاجتماعي الوسوم (hashtags) وأسماء المستخدمين (handles) والروابط (URLs) التي يجب الإبقاء عليها كاملة، لأن #NLP أو عنوان الويب إذا قُسّم عند علامات ترقيمه يصبح بلا قيمة. والمقطِّع على نمط Treebank لن يفعل ذلك من تلقاء نفسه: فهو يحيط # و@ بمسافات ويقسم الرابط عند النقطتين الرأسيتين، لذلك تضيف سلسلة معالجة وسائل التواصل الاجتماعي أنماطًا للوسوم وأسماء المستخدمين والروابط قبله.
Recall
Under the Penn Treebank convention, tokenize 'doesn't' and 'children's'.وفق اصطلاح Penn Treebank، قطّع 'doesn't' و'children's'.
Quick checkاختبار سريع
Which preprocessing decision helps information retrieval but hurts named entity recognition?أي قرار من قرارات المعالجة المسبقة يفيد استرجاع المعلومات لكنه يضر بالتعرف على الكيانات المسماة؟
Recapالخلاصة
If you remember nothing elseإن لم تتذكر شيئاً آخر فتذكّر هذا
- A word is not a natural unit: the picnic sentence has 16 or 18 tokens and 14 or 16 types depending on the punctuation policy.الكلمة ليست وحدة طبيعية: جملة النزهة فيها 16 أو 18 وحدة نصية (token) و14 أو 16 نوعًا (type) بحسب سياسة التعامل مع علامات الترقيم.
- Token = one occurrence (N); type = one distinct item (|V|); 'to be or not to be' is N = 6, |V| = 4.الوحدة النصية (token) = ظهور واحد (N)؛ النوع (type) = عنصر مميز واحد (|V|)؛ عبارة 'to be or not to be' فيها N = 6 و|V| = 4.
- Speech adds fragments (main-) and filled pauses (uh, um); speech recognizers keep them, parsers drop them.يضيف الكلام المنطوق أجزاء كلمات مبتورة (main-) ووقفات مملوءة (uh وum)؛ أنظمة التعرف على الكلام تُبقيها، والمحللات النحوية (parsers) تحذفها.
- Chinese, Japanese and Thai have no orthographic words; the same Chinese sentence can be 3, 5 or 7 units.الصينية واليابانية والتايلاندية لا توجد فيها كلمات إملائية مفصولة بمسافات؛ فالجملة الصينية نفسها قد تُعدّ 3 أو 5 أو 7 وحدات.
- Types grow with tokens but sublinearly (Heaps: |V| = k N^beta, beta about 0.5); the type to token ratio falls from 3.5% (Shakespeare) to 0.0013% (Google n-grams).تنمو الأنواع مع نمو الوحدات النصية لكن بمعدل أبطأ من الخطي (قانون Heaps: |V| = k N^beta، وbeta تقارب 0.5)؛ وتنخفض نسبة الأنواع إلى الوحدات من 3.5% (شكسبير) إلى 0.0013% (Google n-grams).
- Genre matters as much as size: Switchboard has 2.4 million tokens but only 20 thousand types.النوع الأدبي مهم بقدر الحجم: Switchboard فيه 2.4 مليون وحدة نصية لكن 20 ألف نوع فقط.
- Vocabulary is hard because of names, new products, typos, code-switching, morphology and multiword expressions; OOV is unavoidable.المفردات صعبة بسبب أسماء العلم، والمنتجات الجديدة، والأخطاء الإملائية، والتناوب اللغوي (code-switching)، والصرف، والتعبيرات متعددة الكلمات؛ لذلك فالكلمات خارج المفردات (OOV) أمر لا مفر منه.
- Four preprocessing decisions: case folding, punctuation, normalization, numbers. Four ambiguous boundaries: hyphens, abbreviations, clitics, social media.قرارات المعالجة المسبقة الأربعة: توحيد حالة الأحرف (case folding)، وعلامات الترقيم، والتطبيع (normalization)، والأرقام. والحدود الملتبسة الأربعة: الشرطات الواصلة، والاختصارات، واللواحق المتصلة (clitics)، ووسائل التواصل الاجتماعي.
- Penn Treebank convention: separate punctuation, keep hyphenated words, split clitics and possessives (doesn't -> does n't, children's -> children 's).اصطلاح Penn Treebank: افصل علامات الترقيم، وأبقِ الكلمات الموصولة بشرطة معًا، وافصل اللواحق المتصلة وعلامة الملكية (doesn't -> does n't، وchildren's -> children 's).
- |V| is a property of the corpus plus the tokenization policy, never of the language alone.|V| خاصية للمدونة مع سياسة التقطيع (tokenization)، وليست أبدًا خاصية للغة وحدها.
Sourcesالمصادر
- Speech and Language Processing, 3rd edition draft, chapter 2: Words and TokensBookJurafsky and Martin, StanfordDraft of August 19, 2026. Sections 2.1 (words, types, Fig. 2.1, Heaps), 2.5 (corpora), 2.8 (Penn Treebank tokenization)مسودة 19 أغسطس 2026. الأقسام 2.1 (الكلمات، والأنواع، والشكل 2.1، وقانون Heaps)، و2.5 (المدونات)، و2.8 (التقطيع وفق Penn Treebank)(opens in a new tab)(يفتح في تبويب جديد)
- Words and Tokens lecture slidesDocsJurafsky and Martin, StanfordSource of the 31 thousand Shakespeare figure reproduced on slide 7مصدر رقم 31 ألف نوع لشكسبير المعروض في الشريحة 7(opens in a new tab)(يفتح في تبويب جديد)
- Building a Large Annotated Corpus of English: The Penn TreebankPaperComputational Linguistics 19(2), 1993, Marcus, Santorini and MarcinkiewiczFootnote 8: contractions and the genitive split into component morphemesالحاشية 8: صيغ الاختصار وحالة الملكية تُفصل إلى مورفيماتها المكوّنة(opens in a new tab)(يفتح في تبويب جديد)
- nltk.tokenize.treebank: TreebankWordTokenizerDocsNLTK Projectdon't becomes do n't, punctuation separatedتصبح don't وحدتين do وn't، وتُفصل علامات الترقيم(opens in a new tab)(يفتح في تبويب جديد)
- Introduction to Information Retrieval, section 2.2.1: TokenizationBookManning, Raghavan and Schütze, Cambridge University PressToken and type definitions, O'Neill, hyphens from co-education to Hewlett-Packardتعريفا الوحدة النصية والنوع، ومثال O'Neill، والشرطات الواصلة من co-education إلى Hewlett-Packard(opens in a new tab)(يفتح في تبويب جديد)
- Introduction to Information Retrieval, section 2.2.3: Capitalization and case-foldingBookManning, Raghavan and Schütze, Cambridge University PressGeneral Motors, the Fed, Bush; truecasing; lowercasing remains the most practical solution for IRGeneral Motors وthe Fed وBush؛ واستعادة الحالة الصحيحة (truecasing)؛ والتحويل إلى أحرف صغيرة يظل الحل الأكثر عملية لاسترجاع المعلومات(opens in a new tab)(يفتح في تبويب جديد)
- Using uh and um in spontaneous speakingPaperCognition 84(1), 2002, Clark and Fox Treeuh signals a minor delay, um a major one; both are conventional English wordsuh تشير إلى تأخير بسيط وum إلى تأخير كبير؛ وكلتاهما كلمة إنجليزية متعارف عليها(opens in a new tab)(يفتح في تبويب جديد)
- Multiword Expressions: A Pain in the Neck for NLPPaperCICLing 2002, Sag, Baldwin, Bond, Copestake and FlickingerWords with spaces such as San Francisco as one analysis of multiword expressionsالكلمات التي تحتوي مسافات مثل San Francisco بوصفها أحد أساليب تحليل التعبيرات متعددة الكلمات(opens in a new tab)(يفتح في تبويب جديد)
- Switchboard-1 Release 2DocsLinguistic Data Consortium, LDC97S62About 2,400 two-sided telephone conversations, 543 speakers, about 70 topicsنحو 2,400 محادثة هاتفية ثنائية الطرف، و543 متحدثًا، ونحو 70 موضوعًا(opens in a new tab)(يفتح في تبويب جديد)
- Treebank-3DocsLinguistic Data Consortium, LDC99T42The Switchboard portion is dysfluency-annotatedالجزء الخاص بـ Switchboard موسوم بتعثرات الكلام(opens in a new tab)(يفتح في تبويب جديد)
- Web 1T 5-gram Version 1, readmeDocsLinguistic Data Consortium, LDC2006T131,024,908,267,229 tokens, 13,588,391 unigrams; unigram cutoff 200, n-gram cutoff 401,024,908,267,229 وحدة نصية، و13,588,391 كلمة مفردة (unigram)؛ حد القطع للكلمات المفردة 200، وللـ n-grams 40(opens in a new tab)(يفتح في تبويب جديد)
- Natural Language Processing with Python, chapter 2: Accessing Text CorporaBookBird, Klein and Loper, NLTK ProjectBrown corpus: 1961, 500 sources, 15 genres, the first million-word electronic corpusمدونة Brown: عام 1961، و500 مصدر، و15 نوعًا أدبيًا، وهي أول مدونة إلكترونية بحجم مليون كلمة(opens in a new tab)(يفتح في تبويب جديد)
- Unicode Standard Annex #15: Unicode Normalization FormsDocsUnicode ConsortiumNFC, NFD, NFKC, NFKD; canonical equivalence of U+00C7 and C plus combining cedillaNFC وNFD وNFKC وNFKD؛ والتكافؤ القانوني (canonical equivalence) بين U+00C7 والحرف C مع علامة السيديا المركِّبة(opens in a new tab)(يفتح في تبويب جديد)
- Corpus of Contemporary American English (COCA)DocsEnglish-Corpora.orgThe 440 million figure is the older size SLP3 uses; the current corpus is about 1 billion words, 1990 to 2019رقم 440 مليونًا هو الحجم الأقدم الذي يستخدمه SLP3؛ أما المدونة الحالية فنحو مليار كلمة، من 1990 إلى 2019(opens in a new tab)(يفتح في تبويب جديد)
Part 02: Zipf and Heaps: the shape of vocabularyZipf وHeaps: شكل المفردات
Two empirical laws that explain why a few words are everywhere, most words are rare, and vocabulary never stops growing, and why that pushes NLP toward subword units.قانونان تجريبيان يفسران لماذا تنتشر كلمات قليلة في كل مكان بينما معظم الكلمات نادرة، ولماذا لا يتوقف نمو المفردات أبدا، ولماذا يدفع ذلك NLP نحو الوحدات الجزئية (subword units).
4 concepts4 مفاهيم, ، slides 11-16الشرائح 11-16
Why this part mattersلماذا يهمّ هذا الجزء
Every tokenizer, every n-gram smoother and every embedding table you will build for Arabic NLP is a response to two curves. One says that a handful of words carry most of any text while almost everything else is rare. The other says that no matter how much text you read, new words keep arriving.
Part 01 defined types and tokens and showed that corpora vary wildly in size. This part asks what the relationship between the two looks like, and the answer turns out to be the same for English, Arabic and undotted Arabic Wikipedia, with only the constants changing. Those constants are numbers you can quote in your own research on Arabic text, and the two formulas behind them are the kind of thing an exam asks you to compute with. By the end you should be able to look at a vocabulary size and say whether it is surprising, and to explain in one sentence why subword units exist.
كل tokenizer، وكل طريقة smoothing لنماذج الـ n-gram، وكل جدول embeddings ستبنيه لمعالجة اللغة العربية (Arabic NLP) هو استجابة لمنحنيين. الأول يقول إن حفنة من الكلمات تحمل معظم أي نص، بينما كل ما عداها تقريبًا نادر. والثاني يقول إنه مهما قرأت من نصوص فإن كلمات جديدة تستمر في الظهور.
عرّف الجزء 01 الأنواع (types) والـ tokens، وبيّن أن أحجام الـ corpora تتفاوت تفاوتًا كبيرًا. يسأل هذا الجزء كيف تبدو العلاقة بين الاثنين، ويتبيّن أن الجواب واحد لـ Wikipedia الإنجليزية والعربية والعربية غير المنقوطة، ولا يتغير إلا الثوابت. هذه الثوابت أرقام يمكنك الاستشهاد بها في بحثك الخاص على النصوص العربية، والصيغتان اللتان تقفان خلفها من النوع الذي يطلب منك الامتحان الحساب بهما. وفي النهاية يجب أن تستطيع النظر إلى حجم مفردات ما والحكم إن كان مفاجئًا، وأن تشرح في جملة واحدة لماذا توجد الوحدات الجزئية (subword units).
By the end you canفي نهاية هذا الجزء ستستطيع
- State Zipf's law and compute f(R) from f(1) and α.أن تذكر قانون Zipf وتحسب f(R) من f(1) و α.
- Explain why a power law is a straight line on log-log axes, and diagnose the head and tail deviations on a real corpus.أن تشرح لماذا يظهر قانون القوة (power law) خطًا مستقيمًا على محورين لوغاريتميين (log-log)، وأن تشخّص انحرافات الرأس والذيل في corpus حقيقي.
- State Heaps' law, compute |V| for given k, β and N, and compare the English and Arabic Wikipedia fits.أن تذكر قانون Heaps، وتحسب |V| لقيم معطاة من k و β و N، وتقارن بين ملاءمتي Wikipedia الإنجليزية والعربية.
- Argue from Heaps' law why OOV words are unavoidable and why about half of all types are hapax legomena.أن تستنتج من قانون Heaps لماذا لا يمكن تجنّب الكلمات خارج المفردات (OOV)، ولماذا يكون نحو نصف الأنواع (types) من الـ hapax legomena.
- Connect sparsity and OOV to smoothing, backoff and subword tokenization.أن تربط الندرة (sparsity) والـ OOV بالـ smoothing والـ backoff والـ subword tokenization.
Take a novel, count every word, and sort the counts from largest to smallest. Manning and Schütze did exactly this for Mark Twain's Tom Sawyer: 71,370 tokens and 8,018 distinct types. The most frequent type is "the" with 3,332 occurrences, then "and" with 2,972, then "a" with 1,775. At the other end sit thousands of words like "applausive" that appear exactly once. The hundred most common types alone cover 50.9% of every token in the book.
خذ رواية، واحسب عدد مرات ظهور كل كلمة، ثم رتّب الأعداد من الأكبر إلى الأصغر. فعل Manning وSchütze ذلك بالضبط مع رواية Tom Sawyer لـ Mark Twain: 71,370 tokens و8,018 types مختلفة. أكثر الأنواع تكرارًا هو "the" بـ 3,332 مرة، ثم "and" بـ 2,972، ثم "a" بـ 1,775. وفي الطرف الآخر تقبع آلاف الكلمات مثل "applausive" التي تظهر مرة واحدة فقط. والأنواع المئة الأكثر شيوعًا وحدها تغطي 50.9% من كل الـ tokens في الكتاب.
Give each type a rank R, with R = 1 for the most frequent word. Now multiply frequency by rank. For most of the list the product hovers around a constant, roughly 8,000 to 10,000, a relationship Estoup noticed in 1916 and George Kingsley Zipf made famous in the 1930s and 1940s, so it carries Zipf's name. Zipf's law says that frequency falls off as a power of rank.
أعطِ كل نوع رتبة R، حيث R = 1 للكلمة الأكثر تكرارًا. ثم اضرب التكرار في الرتبة. في معظم القائمة يحوم حاصل الضرب حول قيمة ثابتة، تقريبًا من 8,000 إلى 10,000، وهي علاقة لاحظها Estoup عام 1916 وجعلها George Kingsley Zipf مشهورة في ثلاثينيات القرن العشرين وأربعينياته، فحملت اسم Zipf. ينص Zipf's law على أن التكرار يتناقص كقوة (power) للرتبة.
| Wordالكلمة | Frequency fالتكرار f | Rank Rالرتبة R | f × Rf × R |
|---|---|---|---|
| thethe | 3,3323,332 | 11 | 3,3323,332 |
| andand | 2,9722,972 | 22 | 5,9445,944 |
| aa | 1,7751,775 | 33 | 5,3255,325 |
| hehe | 877877 | 1010 | 8,7708,770 |
| turnedturned | 5151 | 200200 | 10,20010,200 |
| applausiveapplausive | 11 | 8,0008,000 | 8,0008,000 |
Because the law is a proportionality, the useful working form anchors it to the top word. If you know how often the most frequent word occurs, everything else follows from the rank alone.
لأن القانون علاقة تناسب، فالصيغة العملية المفيدة تربطه بالكلمة الأولى. إذا عرفت كم مرة تظهر الكلمة الأكثر تكرارًا، فكل ما عداها يُستنتج من الرتبة وحدها.
With α = 1 the arithmetic is nothing more than division. The word at rank 10 occurs about a tenth as often as the top word, the word at rank 1,000 about a thousandth as often. Slide 12 will show that natural language has α slightly below one, so the fall is a little gentler and the rare words a little less rare than the pure 1 / R rule predicts.
مع α = 1 لا يتعدى الحساب مجرد القسمة. الكلمة في الرتبة 10 تظهر بنحو عُشر تكرار الكلمة الأولى، والكلمة في الرتبة 1,000 بنحو جزء من ألف منه. وستبيّن الشريحة 12 أن اللغة الطبيعية لها α أقل من الواحد بقليل، فيكون الهبوط ألطف قليلًا والكلمات النادرة أقل ندرة قليلًا مما تتوقعه قاعدة 1 / R الصرفة.
Worked exampleمثال محلول
From f(1) to f(R)من f(1) إلى f(R)
Fix the anchorثبّت نقطة الارتكاز
Suppose the top word occurs f(1) = 1,000,000 times in a large Corpus.افترض أن الكلمة الأولى تظهر f(1) = 1,000,000 مرة في corpus كبير.Apply α = 1طبّق α = 1
f(10) = 1,000,000 / 10 = 100,000 and f(1000) = 1,000,000 / 1000 = 1,000.f(10) = 1,000,000 / 10 = 100,000 وf(1000) = 1,000,000 / 1000 = 1,000.Apply the slide's α = 0.93طبّق قيمة الشريحة α = 0.93
1000^0.93 = 10^(3 × 0.93) = 10^2.79 ≈ 617, so f(1000) ≈ 1,000,000 / 617 ≈ 1,622. At rank 10, 10^0.93 ≈ 8.51 gives f(10) ≈ 117,490.1000^0.93 = 10^(3 × 0.93) = 10^2.79 ≈ 617، لذا f(1000) ≈ 1,000,000 / 617 ≈ 1,622. وعند الرتبة 10، تعطي 10^0.93 ≈ 8.51 القيمة f(10) ≈ 117,490.Three exponents side by sideثلاثة أُسس جنبًا إلى جنب
αα f(10)f(10) f(100)f(100) f(1000)f(1000) f(100,000)f(100,000) 1.001.00 100,000100,000 10,00010,000 1,0001,000 1010 0.930.93 117,490117,490 13,80413,804 1,6221,622 2222 1.101.10 79,43379,433 6,3106,310 501501 33
Read the table across a row and you see the fall; read it down a column and you see what α does. A smaller exponent leaves more mass in the tail, which for a language model means more probability spread across rare words. A larger exponent concentrates the text in fewer types. The exponent is a property of the corpus, so it differs slightly between languages, genres and preprocessing choices such as case folding.
اقرأ الجدول عبر الصف فترى الهبوط، واقرأه نزولًا في العمود فترى أثر α. الأس الأصغر يترك كتلة أكبر في الذيل، وهذا يعني لنموذج اللغة احتمالًا أكبر موزعًا على الكلمات النادرة. والأس الأكبر يركّز النص في عدد أقل من الأنواع. الأس خاصية للـ corpus، لذا يختلف قليلًا بين اللغات والأنواع النصية (genres) وخيارات المعالجة المسبقة مثل توحيد حالة الأحرف (case folding).
Recall
The most frequent word in a corpus occurs 2,000,000 times. Under Zipf with α = 1, roughly how often does the rank 1,000 word occur? And with α = 0.9?الكلمة الأكثر تكرارًا في corpus تظهر 2,000,000 مرة. وفق Zipf مع α = 1، كم مرة تقريبًا تظهر الكلمة في الرتبة 1,000؟ وماذا لو كانت α = 0.9؟
Quick checkاختبار سريع
A corpus follows Zipf's law with α = 1 and its top word occurs 500,000 times. About how often does the word at rank 50 occur?corpus يتبع قانون Zipf مع α = 1، وكلمته الأولى تظهر 500,000 مرة. كم مرة تقريبًا تظهر الكلمة في الرتبة 50؟
Slide 12 plots rank against frequency for three corpora, English Wikipedia, Arabic Wikipedia and an undotted Arabic Wikipedia in which the dots that distinguish letters such as ب, ت and ث have been removed. Both axes are logarithmic, labelled from 10^0 to 10^6 in rank (the Arabic curve runs on to about 2 × 10^6) and to 10^7 in frequency, and two dashed straight lines, each pinned to the top word of its corpus, are drawn with α = 0.9252 for Arabic and α = 0.9290 for English. The first thing to understand is why anyone would expect a straight line at all.
ترسم الشريحة 12 الرتبة مقابل التكرار لثلاثة corpora: Wikipedia الإنجليزية، وWikipedia العربية، وWikipedia عربية غير منقوطة أُزيلت فيها النقاط التي تميّز حروفًا مثل ب وت وث. كلا المحورين لوغاريتمي، ومُعلَّمان من 10^0 إلى 10^6 في الرتبة (ويمتد المنحنى العربي إلى نحو 2 × 10^6) وحتى 10^7 في التكرار، ورُسم خطان مستقيمان متقطعان، كل منهما مثبّت عند الكلمة الأولى في الـ corpus الخاص به، بقيمة α = 0.9252 للعربية وα = 0.9290 للإنجليزية. أول ما يجب فهمه هو لماذا قد يتوقع أحد خطًا مستقيمًا أصلًا.
Write Zipf's law as an equation with a constant, f(R) = C · R^−α, and take the logarithm of both sides. A product becomes a sum and a power becomes a multiplier, which is the whole trick.
اكتب قانون Zipf كمعادلة فيها ثابت، f(R) = C · R^−α، وخذ اللوغاريتم للطرفين. يصبح الضرب جمعًا وتصبح القوة معاملًا مضروبًا، وهذه هي الحيلة كلها.
On axes that show log R and log f, this is the equation of a straight line with slope −α and intercept log C, which is log f(1) since log 1 = 0. The Stanford IR book states the special case directly: log cf_i = log c + k log i with k = −1. So the two fitted slopes on the slide, −0.9252 and −0.9290, are the exponents of the two Zipf fits, and the fact that they are nearly parallel says Arabic and English share the same kind of head-and-tail shape.
على محاور تعرض log R وlog f، هذه معادلة خط مستقيم ميله −α ومقطعه log C، وهو يساوي log f(1) لأن log 1 = 0. ويذكر كتاب Stanford IR الحالة الخاصة مباشرة: log cf_i = log c + k log i مع k = −1. إذن الميلان الملائمان في الشريحة، −0.9252 و−0.9290، هما أسّا ملاءمتي Zipf، وكونهما متوازيين تقريبًا يعني أن العربية والإنجليزية تشتركان في النوع نفسه من شكل الرأس والذيل.
Two places where the real curve leaves the lineموضعان يبتعد فيهما المنحنى الحقيقي عن الخط
Look at the slide again and the solid curves do not follow the dashed lines everywhere. They deviate in two characteristic ways, and both are diagnostic rather than noise. At the head, the curve is flatter than the power law: the top few words are common, but the drop from rank 1 to rank 10 is smaller than R^−α demands. This is the same shortfall the Tom Sawyer table showed: f × R was 3,332 for "the" against 8,000 to 10,000 further down, and it is why Mandelbrot added the shift term (R + ρ).
انظر إلى الشريحة مرة أخرى وستجد أن المنحنيات المتصلة لا تتبع الخطوط المتقطعة في كل مكان. فهي تنحرف بطريقتين مميزتين، وكلتاهما تشخيصية وليست ضجيجًا. عند الرأس يكون المنحنى أكثر انبساطًا من قانون القوة: الكلمات القليلة الأولى شائعة، لكن الهبوط من الرتبة 1 إلى الرتبة 10 أصغر مما يتطلبه R^−α. وهذا هو النقص نفسه الذي أظهره جدول Tom Sawyer: كان f × R يساوي 3,332 لـ "the" مقابل 8,000 إلى 10,000 في أسفل القائمة، وهذا سبب إضافة Mandelbrot لحد الإزاحة (R + ρ).
How that flat head looks on a plot depends on where the line is anchored. On slide 12 both fits pass through f(1). The blue English curve bulges slightly above the purple line only for ranks 2 to about 15, then runs just under it. The Arabic curves behave differently: they dip below the red line for ranks 3 to about 50 and cross back above it. At Wikipedia scale the head deviation is small, and the head is not uniformly flatter. The flat head is clearest in small texts such as Tom Sawyer and the explorer's sample; on slide 12 the dominant departure is the tail.
يتوقف شكل هذا الرأس المنبسط على الرسم على مكان تثبيت الخط. في الشريحة 12 تمر الملاءمتان كلتاهما عبر f(1). ينتفخ المنحنى الإنجليزي الأزرق قليلًا فوق الخط البنفسجي في الرتب من 2 إلى نحو 15 فقط، ثم يسير تحته مباشرة. أما المنحنيات العربية فتتصرف بشكل مختلف: تنخفض تحت الخط الأحمر في الرتب من 3 إلى نحو 50 ثم تعبر عائدة فوقه. على مقياس Wikipedia يكون انحراف الرأس صغيرًا، والرأس ليس أكثر انبساطًا بشكل منتظم. ويظهر الرأس المنبسط بأوضح صورة في النصوص الصغيرة مثل Tom Sawyer وعينة المستكشف (explorer)؛ أما في الشريحة 12 فالانحراف الغالب هو الذيل.
At the tail, beyond about rank 10^4, the curves steepen sharply below both lines and then turn into a staircase with horizontal steps at frequencies 3, 2 and 1, stretching out to about rank 2 × 10^6 for Arabic. The reason is that a frequency is a count, and counts are integers. There is no word that occurs 1.5 times. If 400,000 types each occur exactly once, they occupy 400,000 consecutive ranks at height f = 1, which draws as one long flat step. The step at f = 2 is shorter because fewer types occur exactly twice, and so on upward until the counts are large enough that adjacent ranks rarely share a value and the curve looks smooth. The bottom step is the longest because types seen once are the largest single group, the hapax legomena that concept four returns to.
عند الذيل، بعد الرتبة 10^4 تقريبًا، تنحدر المنحنيات بحدة تحت الخطين كليهما ثم تتحول إلى درج له درجات أفقية عند التكرارات 3 و2 و1، ممتدة حتى الرتبة 2 × 10^6 تقريبًا في العربية. والسبب أن التكرار عدد، والأعداد صحيحة. لا توجد كلمة تظهر 1.5 مرة. فإذا ظهر 400,000 نوع كل منها مرة واحدة بالضبط، فإنها تحتل 400,000 رتبة متتالية على الارتفاع f = 1، فتُرسم كدرجة مسطحة طويلة واحدة. والدرجة عند f = 2 أقصر لأن الأنواع التي تظهر مرتين بالضبط أقل عددًا، وهكذا صعودًا حتى تصبح الأعداد كبيرة بما يكفي فلا تتشارك الرتب المتجاورة القيمة نفسها إلا نادرًا، فيبدو المنحنى ناعمًا. والدرجة السفلى هي الأطول لأن الأنواع التي ظهرت مرة واحدة هي أكبر مجموعة منفردة، وهي الـ hapax legomena التي يعود إليها المفهوم الرابع.
What to read off a log-log rank-frequency plotما الذي تقرؤه من مخطط الرتبة والتكرار على محورين لوغاريتميين
- Slope of the fitted lineميل الخط الملائم
- −α, the Zipf exponent−α، أي سالب أس Zipf
- Intercept at log R = 0المقطع عند log R = 0
- log f(1), the frequency of the top wordlog f(1)، أي لوغاريتم تكرار الكلمة الأولى
- Rightmost rank on the curveأقصى رتبة على يمين المنحنى
- |V|, the number of types in the corpus|V|، أي عدد الأنواع (types) في الـ corpus
- Length of the bottom stepطول الدرجة السفلى
- The number of hapax legomenaعدد الـ hapax legomena
- Bend at the head relative to the lineانحناء الرأس مقارنة بالخط
- How much flatter the top few words are than the law; above a line pinned to f(1), below a line fitted through the bulkمقدار انبساط الكلمات القليلة الأولى مقارنة بالقانون؛ فوق خط مثبّت عند f(1)، وتحت خط ملائم لمعظم البيانات
One more thing the slide shows without saying it. In the tail, the Arabic curves sit above the English one: at any low count, Arabic has more types occurring at least that often. Templatic morphology and attached clitics mean that a single Arabic lexeme surfaces as many distinct spelled forms, each of which is a separate type for a whitespace tokenizer. That is a preview of the next concept, where the same fact shows up as a larger k in Heaps' law.
شيء آخر تُظهره الشريحة دون أن تقوله. في الذيل تقع المنحنيات العربية فوق المنحنى الإنجليزي: عند أي عدد منخفض، يكون لدى العربية أنواع أكثر تظهر بذلك العدد على الأقل. فالصرف القالبي (templatic morphology) واللواحق المتصلة (clitics) تجعل الوحدة المعجمية (lexeme) العربية الواحدة تظهر بأشكال إملائية كثيرة مختلفة، وكل منها نوع مستقل بالنسبة لـ tokenizer يقسّم على المسافات. وهذا تمهيد للمفهوم التالي، حيث تظهر الحقيقة نفسها كقيمة k أكبر في قانون Heaps.
Rank against frequencyالرتبة مقابل التكرار
The teal curve is the real count of every type in Pride and Prejudice, chapters 1 to 3 (3,438 tokens, 845 types). The dashed line is f(R) = C / R^α for the α you choose. With the best fit, C is the least-squares intercept over the top 200 ranks, currently 3.5× the top count f(1) = 125, so the head falls short of the line and the tail steps run under it.المنحنى الأخضر المزرق هو العدد الفعلي لتكرار كل نوع في Pride and Prejudice, chapters 1 to 3 (3,438 رمزًا و845 نوعًا). والخط المتقطع هو f(R) = C / R^α بقيمة α التي تختارها. مع أفضل ملاءمة، تكون C هي نقطة التقاطع بطريقة المربعات الصغرى على أعلى 200 رتبة، وهي حاليًا 3.5× من أعلى تكرار f(1) = 125، لذلك يقصر الرأس عن الخط وتقع درجات الذيل تحته.
| rankالرتبة | predictedالمتوقع | observedالمرصود |
|---|---|---|
| 10 | 51.8 | 48 |
| 100 | 6.1 | 6 |
| 500 | 1.4 | 1 |
The tail is a staircase because counts are integers: 475 types share the step at f = 1, 129 share f = 2, and 63 share f = 3.يبدو الذيل على شكل درج لأن التكرارات أعداد صحيحة: 475 نوعًا تشترك في الدرجة عند f = 1، و129 تشترك في f = 2، و63 تشترك في f = 3.
Recall
Why is a power law a straight line on log-log axes, and what does the slope tell you?لماذا يكون قانون القوة خطًا مستقيمًا على محورين لوغاريتميين، وماذا يخبرك الميل؟
Recall
Name the two visible departures from a Zipf line on a real corpus and give the cause of each.سمِّ الانحرافين الظاهرين عن خط Zipf في corpus حقيقي، واذكر سبب كل منهما.
Quick checkاختبار سريع
On a log-log rank-frequency plot, what does the slope of the fitted straight line equal?على مخطط الرتبة والتكرار بمحورين لوغاريتميين، بماذا يساوي ميل الخط المستقيم الملائم؟
Zipf describes a Corpus frozen at one size. Now let the corpus grow. Read the first thousand words of Pride and Prejudice and you meet 361 distinct types. After ten thousand words the count is 1,698; after fifty thousand, 4,304; at the end of the novel, 123,627 tokens have produced 6,298 types. Each new stretch of text adds fewer new words than the last, but it never adds none. The same pattern holds across corpora of every size.
يصف Zipf corpus مجمّدًا عند حجم واحد. الآن دع الـ corpus ينمو. اقرأ أول ألف كلمة من Pride and Prejudice فتصادف 361 types مختلفة. بعد عشرة آلاف كلمة يصبح العدد 1,698، وبعد خمسين ألفًا 4,304، وفي نهاية الرواية تكون 123,627 tokens قد أنتجت 6,298 نوعًا. كل مقطع جديد من النص يضيف كلمات جديدة أقل مما أضافه سابقه، لكنه لا يتوقف عن الإضافة أبدًا. والنمط نفسه يتكرر في corpora من كل الأحجام.
| Corpusالـ corpus | Instances Nعدد الـ tokens N | Types |V|عدد الأنواع |V| |
|---|---|---|
| Shakespeareأعمال Shakespeare | 884 thousand884 ألف | 29 thousand29 ألف |
| Brown corpusBrown corpus | 1 million1 مليون | 38 thousand38 ألف |
| Switchboard telephone speechالكلام الهاتفي في Switchboard | 2.4 million2.4 مليون | 20 thousand20 ألف |
| COCACOCA | 440 million440 مليون | 2 million2 مليون |
| Google n-gramsGoogle n-grams | 1 trillion1 تريليون | 13 million13 مليون |
The rule behind these numbers is Heaps' law, also called Herdan's law after the linguist who described it in 1960, nearly two decades before Heaps (1978). The Vocabulary size is a power of the token count, with an exponent strictly between zero and one.
القاعدة خلف هذه الأرقام هي Heaps' law، ويُسمى أيضًا قانون Herdan نسبة إلى اللغوي الذي وصفه عام 1960، قبل Heaps (1978) بنحو عقدين. حجم المفردات (vocabulary) قوة لعدد الـ tokens، بأس يقع بين الصفر والواحد حصرًا.
The two halves of the constraint on β say two different things. Because β < 1, growth is sublinear: doubling the corpus does not double the vocabulary. Because β > 0, growth is unbounded: the derivative d|V| / dN = k β N^(β − 1) is positive for every N, so the curve keeps rising however far you extend it. SLP3 phrases the second half bluntly: no matter how big our vocabulary, we will never have a vocabulary that captures all the possible words that might occur.
نصفا القيد على β يقولان شيئين مختلفين. لأن β < 1، يكون النمو أبطأ من الخطي (sublinear): مضاعفة الـ corpus لا تضاعف المفردات. ولأن β > 0، يكون النمو غير محدود: المشتقة d|V| / dN = k β N^(β − 1) موجبة لكل N، فيستمر المنحنى في الصعود مهما مددته. ويصوغ SLP3 النصف الثاني بصراحة: مهما كبرت مفرداتنا، فلن نحصل أبدًا على مفردات تلتقط كل الكلمات الممكنة التي قد تظهر.
The slide's three fits, and what the constants meanملاءمات الشريحة الثلاث، وماذا تعني الثوابت
Slide 14 fits the law to the same three corpora as before and reports k and β for each. The constants are worth reading as a pair. k is a multiplicative scale (the predicted |V| at N = 1) that shifts the whole curve up, and β sets the slope on log-log axes: the ratio between two corpus sizes, (N2 / N1)^β, depends on β alone. Plugging in three corpus sizes makes the comparison concrete.
تلائم الشريحة 14 القانون على الـ corpora الثلاثة نفسها كما سبق، وتذكر k وβ لكل منها. ويستحق الثابتان أن يُقرآ كزوج. k معامل قياس ضربي (قيمة |V| المتوقعة عند N = 1) يرفع المنحنى كله، وβ يحدد الميل على المحورين اللوغاريتميين: النسبة بين حجمين للـ corpus، (N2 / N1)^β، تعتمد على β وحدها. والتعويض بثلاثة أحجام للـ corpus يجعل المقارنة ملموسة.
| Corpusالـ corpus | kk | ββ | |V| at 10⁴|V| عند 10⁴ | |V| at 10⁶|V| عند 10⁶ | |V| at 10⁸|V| عند 10⁸ | New types per 1,000 tokensالأنواع الجديدة لكل 1,000 token |
|---|---|---|---|---|---|---|
| English WikipediaWikipedia الإنجليزية | 14.94714.947 | 0.5830.583 | 3,2103,210 | 47,04947,049 | 689,531689,531 | 187 at N = 10⁴187 عند N = 10⁴ |
| Arabic WikipediaWikipedia العربية | 73.32173.321 | 0.5330.533 | 9,9369,936 | 115,672115,672 | 1,346,5681,346,568 | 49 at N = 2.5 × 10⁵49 عند N = 2.5 × 10⁵ |
| Undotted Arabic WikipediaWikipedia العربية غير المنقوطة | 90.49190.491 | 0.5060.506 | 9,5639,563 | 98,31298,312 | 1,010,6611,010,661 | not reportedغير مذكور |
Worked exampleمثال محلول
English fit at one million tokensملاءمة الإنجليزية عند مليون token
Exponentالأس
N^β = (10^6)^0.583 = 10^(6 × 0.583) = 10^3.498.N^β = (10^6)^0.583 = 10^(6 × 0.583) = 10^3.498.Evaluate the powerاحسب القوة
10^3.498 ≈ 3,147.8.10^3.498 ≈ 3,147.8.Multiply by kاضرب في k
|V| ≈ 14.947 × 3,147.8 ≈ 47,049.|V| ≈ 14.947 × 3,147.8 ≈ 47,049.Resultالنتيجة
About 47 thousand types. For comparison, the Brown corpus has 38 thousand types at one million tokens (SLP3 Figure 2.1), and the IR book's Reuters fit, 44 × 1,000,020^0.49, gives 38,323 against an actual 38,365. Same ballpark, different corpus.نحو 47 ألف نوع. وللمقارنة، لدى Brown corpus 38 ألف نوع عند مليون token (SLP3 Figure 2.1)، وملاءمة Reuters في كتاب IR، 44 × 1,000,020^0.49، تعطي 38,323 مقابل قيمة فعلية 38,365. الحجم نفسه تقريبًا، لكن الـ corpus مختلف.
Vocabulary against corpus sizeحجم المفردات مقابل حجم المدونة
| N | |V| | new types per 1,000أنواع جديدة لكل 1,000 |
|---|---|---|
| 10⁴ | 3,210 | 187.2 |
| 10⁶ | 47,049 | 27.4 |
| 10⁸ | 689,531 | 4 |
Now compare languages. At a million tokens Arabic Wikipedia reaches 115,672 types, about two and a half times the English figure, and undotted Arabic reaches 98,312. Arabic gets there because of its k, 73 against 15: templatic morphology and attached clitics such as wa-, bi- and -hu multiply the surface forms of every lexeme, so the vocabulary is large from the very first pages. Its β is lower, though, so the curve bends sooner: a hundredfold larger corpus multiplies the English vocabulary by 100^0.583 ≈ 14.7 but the Arabic vocabulary by only 100^0.533 ≈ 11.6. Removing the dots collapses distinct letters into one shape, and the fit agrees that this shrinks the vocabulary: undotted Arabic is below dotted Arabic at every size in the table. Its larger k (90 against 73) is offset by its smaller β, and the two curves cross below about 2,400 tokens, so k alone never tells you which vocabulary is bigger; evaluate k N^β at the N you care about. Parts 03 and 04 explain the morphology.
قارن الآن بين اللغات. عند مليون token تصل Wikipedia العربية إلى 115,672 نوعًا، أي نحو مرتين ونصف قيمة الإنجليزية، وتصل العربية غير المنقوطة إلى 98,312. وتصل العربية إلى ذلك بسبب قيمة k لديها، 73 مقابل 15: فـ الصرف القالبي (templatic morphology) واللواحق المتصلة (clitics) مثل wa- وbi- و-hu تضاعف الأشكال السطحية لكل وحدة معجمية، فتكون المفردات كبيرة منذ الصفحات الأولى. لكن β لديها أقل، فينحني المنحنى أبكر: corpus أكبر بمئة مرة يضرب المفردات الإنجليزية في 100^0.583 ≈ 14.7 لكنه يضرب المفردات العربية في 100^0.533 ≈ 11.6 فقط. وإزالة النقاط تدمج حروفًا مختلفة في شكل واحد، والملاءمة تؤكد أن هذا يقلّص المفردات: العربية غير المنقوطة أدنى من العربية المنقوطة عند كل حجم في الجدول. وقيمة k الأكبر لديها (90 مقابل 73) يعوّضها β الأصغر، ويتقاطع المنحنيان تحت 2,400 token تقريبًا، لذا فإن k وحدها لا تخبرك أبدًا أي المفردات أكبر؛ احسب k N^β عند قيمة N التي تهمك. ويشرح الجزءان 03 و04 الصرف.
Typical values, and how the slide comparesالقيم المعتادة، وأين تقع منها قيم الشريحة
The constants reported across five reference points are easiest to read side by side.
الثوابت المذكورة عبر خمس نقاط مرجعية أسهل قراءة عندما توضع جنبًا إلى جنب.
| Sourceالمصدر | kk | ββ |
|---|---|---|
| SLP3, current draftSLP3، المسودة الحالية | not givenغير مذكورة | 0.44 to 0.560.44 إلى 0.56 |
| IR book, typicalكتاب IR، القيم المعتادة | 30 to 10030 إلى 100 | ≈ 0.5≈ 0.5 |
| Reuters-RCV1 (IR book)Reuters-RCV1 (كتاب IR) | 4444 | 0.490.49 |
| Earlier SLP3 drafts, larger corporaمسودات SLP3 السابقة، corpora أكبر | not givenغير مذكورة | 0.67 to 0.750.67 إلى 0.75 |
| Slide 14 fitsملاءمات الشريحة 14 | 14.9 to 90.514.9 إلى 90.5 | 0.506 to 0.5830.506 إلى 0.583 |
SLP3 summarizes the law as vocabulary growing a little faster than the square root of the corpus length in words, with β depending on corpus size and genre. The Arabic exponents, 0.533 and 0.506, fall inside SLP3's 0.44 to 0.56 band; the English 0.583 is just above it, which SLP3's "or even higher" allows. The English k of 14.9 is on the low side, which is what you get when a fit trades a smaller k for a larger β; the two constants are not independent estimates.
يلخّص SLP3 القانون بأن المفردات تنمو أسرع قليلًا من الجذر التربيعي لطول الـ corpus بالكلمات، مع اعتماد β على حجم الـ corpus ونوعه (genre). الأسّان العربيان، 0.533 و0.506، يقعان داخل نطاق SLP3 من 0.44 إلى 0.56؛ أما الأس الإنجليزي 0.583 فهو فوقه بقليل، وهو ما تسمح به عبارة SLP3 "or even higher" (أو حتى أعلى). وقيمة k الإنجليزية 14.9 في الجانب المنخفض، وهذا ما تحصل عليه عندما تقايض الملاءمة k أصغر بـ β أكبر؛ فالثابتان ليسا تقديرين مستقلين.
Recall
Using the English Wikipedia fit (k = 14.947, β = 0.583), how many types would you expect at 10^4 tokens and at 10^6 tokens?باستخدام ملاءمة Wikipedia الإنجليزية (k = 14.947، β = 0.583)، كم نوعًا تتوقع عند 10^4 token وعند 10^6 token؟
Quick checkاختبار سريع
With k = 73.321 and β = 0.533, roughly how many types does a one-million-token Arabic corpus have under the slide's Heaps fit?مع k = 73.321 و β = 0.533، كم نوعًا تقريبًا يحتوي corpus عربي من مليون token وفق ملاءمة Heaps في الشريحة؟
Quick checkاختبار سريع
Which statement about vocabulary growth under Heaps' law is correct?أي عبارة عن نمو المفردات وفق قانون Heaps صحيحة؟
Put the two laws together and a design problem falls out. In Tom Sawyer, 3,993 of the 8,018 types occur exactly once, which is 49.8%. In the three chapters of Pride and Prejudice inside the explorer, 475 of 845 types occur once, or 56%. A type seen exactly once is a Hapax legomenon, from the Greek for "read only once", and in corpus after corpus these are about half of everything a model must store.
اجمع القانونين معًا فتبرز مشكلة تصميمية. في Tom Sawyer، 3,993 من أصل 8,018 نوعًا تظهر مرة واحدة بالضبط، أي 49.8%. وفي الفصول الثلاثة من Pride and Prejudice داخل المستكشف، 475 من 845 نوعًا تظهر مرة واحدة، أي 56%. النوع الذي يُرى مرة واحدة بالضبط هو hapax legomenon، من اليونانية بمعنى "قُرئ مرة واحدة فقط"، وفي corpus تلو الآخر تشكّل هذه الأنواع نحو نصف كل ما يجب أن يخزّنه النموذج.
That one half is not a coincidence; it falls out of Zipf's law. With α = 1, the type at rank R has count C / R, so the number of types with count at least m is the rank at which the count drops to m, namely C / m. The types with count exactly m are then C / m − C / (m + 1) = C / (m (m + 1)), and dividing by the total C gives a share of 1 / (m (m + 1)): one half seen once, one sixth seen twice, one twelfth seen three times.
هذا النصف ليس مصادفة، فهو ينتج من قانون Zipf. مع α = 1، يكون عدد مرات ظهور النوع في الرتبة R هو C / R، لذا فعدد الأنواع التي يبلغ عددها m على الأقل هو الرتبة التي ينخفض عندها العدد إلى m، أي C / m. والأنواع التي عددها m بالضبط تكون إذن C / m − C / (m + 1) = C / (m (m + 1))، والقسمة على المجموع C تعطي حصة 1 / (m (m + 1)): النصف يُرى مرة واحدة، والسدس مرتين، وواحد من اثني عشر ثلاث مرات.
| Countالعدد | Zipf predictionتنبؤ Zipf | Tom SawyerTom Sawyer | Sample corpusالـ corpus التجريبي |
|---|---|---|---|
| Exactly onceمرة واحدة بالضبط | 50%50% | 49.8%49.8% | 56%56% |
| Exactly twiceمرتان بالضبط | 16.7%16.7% | 16.1%16.1% | 15%15% |
Baayen (2001) develops this connection between the frequency spectrum and vocabulary growth in full, and it is why the bottom step of the staircase on slide 12 is the longest.
يطوّر Baayen (2001) هذه الصلة بين طيف التكرار (frequency spectrum) ونمو المفردات بالتفصيل، وهي السبب في أن الدرجة السفلى من الدرج في الشريحة 12 هي الأطول.
Slides 15 and 16 list the consequences, and they form a chain rather than a list. Start with size. Heaps' law says a word-level Vocabulary on a large corpus runs to hundreds of thousands or millions of types, and every one of them needs a row in an embedding matrix and a column in the output softmax. Memory grows with |V| × d, where d is the embedding width. Then comes sparsity, which is Zipf's contribution: since half of those types belong to hapax legomena, half of the parameters in that matrix have been trained on a single example. Whatever the model learned about "applausive" it learned from one sentence.
تسرد الشريحتان 15 و16 العواقب، وهي تشكّل سلسلة لا قائمة. ابدأ بالحجم. يقول قانون Heaps إن المفردات (vocabulary) على مستوى الكلمة لـ corpus كبير تبلغ مئات الآلاف أو ملايين الأنواع، وكل منها يحتاج صفًا في مصفوفة الـ embeddings وعمودًا في الـ softmax الخاص بالمخرجات. تنمو الذاكرة مع |V| × d، حيث d عرض الـ embedding. ثم تأتي الندرة (sparsity)، وهي إسهام Zipf: بما أن نصف تلك الـ types من الـ hapax legomena، فنصف المعاملات في تلك المصفوفة دُرّبت على مثال واحد. فكل ما تعلمه النموذج عن "applausive" تعلّمه من جملة واحدة.
Next comes the guarantee. Because Heaps' law has a positive derivative at every N, any finite training corpus stops somewhere on a curve that is still rising. New text therefore always contains types that were never seen, and those types are out-of-vocabulary. This is not a defect of a small corpus that a bigger one would cure; a bigger corpus only pushes the OOV rate down along the same curve, never to zero. Finally, evaluation inherits the problem. Earlier SLP3 drafts warned that mapping unseen words to an <UNK> special token lets a model buy a lower perplexity simply by choosing a smaller vocabulary, since more of the test set collapses onto one easy symbol. The current chapter 3 sidesteps the issue by making the vocabulary subword tokens, so that, in its words, the test set can never contain unseen tokens.
ثم يأتي الضمان. لأن قانون Heaps له مشتقة موجبة عند كل N، فإن أي corpus تدريب محدود يتوقف عند نقطة ما على منحنى ما زال صاعدًا. لذلك يحتوي النص الجديد دائمًا على أنواع لم تُرَ من قبل، وتكون هذه الأنواع خارج المفردات (out-of-vocabulary). وهذا ليس عيبًا في corpus صغير يعالجه corpus أكبر؛ فالـ corpus الأكبر لا يفعل سوى دفع معدل الـ OOV إلى الأسفل على المنحنى نفسه، دون أن يوصله إلى الصفر أبدًا. وأخيرًا، يرث التقييم المشكلة. حذّرت مسودات SLP3 السابقة من أن ربط الكلمات غير المرئية بـ <UNK> بوصفه special token يسمح للنموذج بشراء perplexity أقل بمجرد اختيار مفردات أصغر، لأن جزءًا أكبر من مجموعة الاختبار ينهار على رمز واحد سهل. ويتجنب الفصل 3 الحالي المسألة بجعل المفردات subword tokens، بحيث لا يمكن لمجموعة الاختبار، بحسب عبارته، أن تحتوي أبدًا على tokens غير مرئية.
- Huge word-level vocabularies: memory in the embedding and output layers scales with |V|.مفردات ضخمة على مستوى الكلمة: الذاكرة في طبقتي الـ embedding والمخرجات تتناسب مع |V|.
- Sparsity: about half of all types are hapax legomena, so about half of the rows have one training example.الندرة (sparsity): نحو نصف الأنواع hapax legomena، لذا فنحو نصف الصفوف لها مثال تدريبي واحد.
- Guaranteed OOV: Heaps' law keeps rising, so new text always brings unseen types.OOV مضمون: منحنى قانون Heaps يظل صاعدًا، فالنص الجديد يأتي دائمًا بأنواع غير مرئية.
- Evaluation sensitivity: mapping unseen words to <UNK> changes what a perplexity number means.حساسية التقييم: ربط الكلمات غير المرئية بـ <UNK> يغيّر معنى رقم الـ perplexity.
Two answers to the same problemإجابتان عن المشكلة نفسها
The two families of language model respond to the chain at different points. N-gram models keep the word as the unit and repair the probability estimate: smoothing moves a little probability mass from seen events to unseen ones, and backoff falls back to a shorter context when the longer one was never observed. Lecture 3 and SLP3 chapter 3 develop both. Neural models change the unit instead. With Subword tokenization, learned by byte-pair encoding as Sennrich, Haddow and Birch showed for machine translation in 2016, a word never seen in training is spelled out of pieces that were, and with byte-level fallback there is nothing left that cannot be represented. The vocabulary becomes a design choice of tens of thousands of units rather than a fact about the corpus, which is exactly the trade part 6 examines.
تستجيب عائلتا نماذج اللغة للسلسلة عند نقطتين مختلفتين. نماذج الـ n-gram تُبقي الكلمة وحدةً وتُصلح تقدير الاحتمال: الـ smoothing ينقل قليلًا من كتلة الاحتمال من الأحداث المرئية إلى غير المرئية، والـ backoff يرجع إلى سياق أقصر عندما لا يكون السياق الأطول قد شوهد. وتطوّر المحاضرة 3 والفصل 3 من SLP3 كليهما. أما النماذج العصبية فتغيّر الوحدة نفسها. مع subword tokenization، المتعلَّم عبر byte-pair encoding كما بيّن Sennrich وHaddow وBirch للترجمة الآلية عام 2016، تُهجّى الكلمة التي لم تُرَ في التدريب من قطع رُئيت فيه، ومع الرجوع إلى مستوى البايت (byte-level fallback) لا يبقى شيء لا يمكن تمثيله. وتصبح المفردات خيارًا تصميميًا من عشرات الآلاف من الوحدات بدلًا من أن تكون حقيقة مفروضة من الـ corpus، وهذه بالضبط المقايضة التي يدرسها الجزء 6.
| N-gram, word unitsN-gram، وحدات كلمات | Neural, subword unitsعصبي، وحدات subword | |
|---|---|---|
| Unit of the vocabularyوحدة المفردات | Whole wordsكلمات كاملة | Subword pieces, or bytes as the floorقطع subword، أو البايتات (bytes) كحد أدنى |
| What happens to an unseen wordماذا يحدث لكلمة غير مرئية | Mapped to <UNK> or given smoothed massتُربط بـ <UNK> أو تُعطى كتلة احتمال عبر الـ smoothing | Composed from known pieces, so never unknownتُركَّب من قطع معروفة، فلا تكون مجهولة أبدًا |
| Where the fix livesأين يقع الإصلاح | In the probability estimate: smoothing, backoff, interpolationفي تقدير الاحتمال: smoothing وbackoff وinterpolation | In the tokenizer: BPE, WordPiece, byte fallbackفي الـ tokenizer: BPE وWordPiece والرجوع إلى مستوى البايت (byte fallback) |
| Costالكلفة | Probability mass spent on events never seenكتلة احتمال تُنفق على أحداث لم تُرَ قط | Longer token sequences, less interpretable unitsتسلسلات tokens أطول، ووحدات أقل قابلية للتفسير |
| Covered inأين يُشرح | Lecture 3 and SLP3 chapter 3المحاضرة 3 والفصل 3 من SLP3 | Part 6 of this lectureالجزء 6 من هذه المحاضرة |
Recall
In one sentence, why does Heaps' law guarantee OOV words?في جملة واحدة، لماذا يضمن قانون Heaps وجود كلمات OOV؟
Recall
Define hapax legomenon and give the typical share of types it accounts for.عرّف الـ hapax legomenon واذكر الحصة المعتادة التي يمثّلها من الأنواع.
Quick checkاختبار سريع
A model trained on 10 million tokens meets a word absent from its training data. Which mechanism lets a modern neural model represent it anyway?نموذج دُرّب على 10 ملايين token يصادف كلمة غائبة عن بيانات تدريبه. أي آلية تسمح لنموذج عصبي حديث بتمثيلها رغم ذلك؟
Recapالخلاصة
If you remember nothing elseإن لم تتذكر شيئاً آخر فتذكّر هذا
- Rank types by count. Zipf: f(R) is proportional to 1 / R^α with α near 1 (0.9252 for Arabic and 0.9290 for English Wikipedia on slide 12).رتّب الأنواع (types) حسب عددها. ينص Zipf على أن f(R) تتناسب مع 1 / R^α حيث α قريبة من 1 (0.9252 لـ Wikipedia العربية و0.9290 للإنجليزية في الشريحة 12).
- log f = log C − α log R is a line with slope −α. Real corpora flatten at the head (above a line pinned to f(1), below a line fitted through the bulk) and form integer steps at the tail.المعادلة log f = log C − α log R خط ميله −α. وتنبسط الـ corpora الحقيقية عند الرأس (فوق خط مثبّت عند f(1)، وتحت خط ملائم لمعظم البيانات) وتشكّل درجات من أعداد صحيحة عند الذيل.
- Heaps: |V| = k N^β with 0 < β < 1, sublinear but unbounded. The English fit 14.947 N^0.583 gives 47,049 types at one million tokens; Arabic 115,672; undotted Arabic 98,312.Heaps: |V| = k N^β حيث 0 < β < 1، أي نمو أبطأ من الخطي (sublinear) لكنه غير محدود. ملاءمة الإنجليزية 14.947 N^0.583 تعطي 47,049 نوعًا عند مليون token، والعربية 115,672، والعربية غير المنقوطة 98,312.
- The larger k for Arabic reflects templatic morphology and clitics. Typical β is 0.44 to 0.56 in the current SLP3 draft, and b ≈ 0.5 with 30 ≤ k ≤ 100 in the IR book.قيمة k الأكبر للعربية تعكس الصرف القالبي (templatic morphology) واللواحق المتصلة (clitics). القيمة المعتادة لـ β بين 0.44 و0.56 في مسودة SLP3 الحالية، وفي كتاب IR تكون b ≈ 0.5 مع 30 ≤ k ≤ 100.
- Slide 14 plots the fitted formula out to 10^19 tokens. That is an extrapolation, not data.ترسم الشريحة 14 الصيغة الملائمة حتى 10^19 token. هذا استقراء (extrapolation) وليس بيانات.
- About half of all types are hapax legomena (49.8% in Tom Sawyer, 56% in the sample corpus). Word vocabularies are huge and sparse, and OOV words are guaranteed.نحو نصف الأنواع hapax legomena (49.8% في Tom Sawyer و56% في الـ corpus التجريبي). مفردات الكلمات ضخمة ومتناثرة (sparse)، وظهور كلمات OOV مضمون.
- N-gram models respond with smoothing and backoff. Neural models respond with subwords (BPE, part 6). Evaluation depends on how unseen items are treated.تستجيب نماذج الـ n-gram بالـ smoothing والـ backoff، وتستجيب النماذج العصبية بالـ subwords (BPE، الجزء 6). ويتوقف التقييم على طريقة معاملة العناصر غير المرئية.
- Heaps' law is a consequence of Zipf's law (Lü, Zhang and Zhou 2010), not an independent law.قانون Heaps نتيجة لقانون Zipf (Lü وZhang وZhou 2010)، وليس قانونًا مستقلًا.
Sourcesالمصادر
- Speech and Language Processing, 3rd edition draft, chapter 2: Words and TokensBookJurafsky and Martin, Stanford UniversityCorpus size table (Figure 2.1), Heaps' law (Equation 2.5), β range 0.44 to 0.56, two-regime growth (Figure 2.2)جدول أحجام الـ corpora (الشكل 2.1)، وقانون Heaps (المعادلة 2.5)، ونطاق β من 0.44 إلى 0.56، والنمو ذو النظامين (الشكل 2.2)(opens in a new tab)(يفتح في تبويب جديد)
- Speech and Language Processing, 3rd edition draft, chapter 3: N-gram Language ModelsBookJurafsky and Martin, Stanford UniversitySmoothing, interpolation and backoff; the current draft notes that subword vocabularies mean the test set can never contain unseen tokens (the <UNK> discussion is from earlier drafts)الـ smoothing والـ interpolation والـ backoff؛ وتشير المسودة الحالية إلى أن مفردات الـ subword تعني أن مجموعة الاختبار لا يمكن أبدًا أن تحتوي على tokens غير مرئية (نقاش <UNK> من مسودات سابقة)(opens in a new tab)(يفتح في تبويب جديد)
- Foundations of Statistical Natural Language Processing, chapter 1 excerptBookManning and Schütze, MIT PressTom Sawyer counts, 49.8% hapax legomena, Table 1.3 f × R products, Zipf and Mandelbrotأعداد Tom Sawyer، ونسبة 49.8% من الـ hapax legomena، وحواصل ضرب f × R في الجدول 1.3، وقانونا Zipf و Mandelbrot(opens in a new tab)(يفتح في تبويب جديد)
- Introduction to Information Retrieval: Heaps' law, estimating the number of termsBookManning, Raghavan and Schütze, Cambridge University Press30 ≤ k ≤ 100 and b ≈ 0.5; Reuters-RCV1 fit k = 44, b = 0.4930 ≤ k ≤ 100 و b ≈ 0.5؛ وملاءمة Reuters-RCV1 بقيمة k = 44 و b = 0.49(opens in a new tab)(يفتح في تبويب جديد)
- Introduction to Information Retrieval: Zipf's law, modeling the distribution of termsBookManning, Raghavan and Schütze, Cambridge University Presslog cf_i = log c + k log i with k = −1; the fit is 'not particularly good, but good enough'log cf_i = log c + k log i مع k = −1؛ والملاءمة 'not particularly good, but good enough' (ليست جيدة بشكل خاص، لكنها جيدة بما يكفي)(opens in a new tab)(يفتح في تبويب جديد)
- Human Behavior and the Principle of Least EffortBookZipf, Addison-Wesley, 1949Zipf's own account of the rank-frequency law and its proposed causeعرض Zipf نفسه لقانون الرتبة والتكرار والسبب الذي اقترحه له(opens in a new tab)(يفتح في تبويب جديد)
- Information Retrieval: Computational and Theoretical AspectsBookHeaps, Academic Press, 1978The original statement of the vocabulary growth lawالصياغة الأصلية لقانون نمو المفردات(opens in a new tab)(يفتح في تبويب جديد)
- Word Frequency DistributionsBookBaayen, Kluwer, 2001LNRE models and the derivation of vocabulary growth from frequency distributionsنماذج LNRE واشتقاق نمو المفردات من توزيعات التكرار(opens in a new tab)(يفتح في تبويب جديد)
- Zipf's Law Leads to Heaps' Law: Analyzing Their Relation in Finite-Size SystemsPaperLü, Zhang and Zhou, PLoS ONE, 2010Heaps as a derivative of Zipf; asymptotic β = 1 / α and the finite-size caveatقانون Heaps كنتيجة مشتقة من Zipf؛ والعلاقة التقاربية β = 1 / α وتحفّظ الحجم المحدود(opens in a new tab)(يفتح في تبويب جديد)
- Zipf's word frequency law in natural language: A critical review and future directionsPaperPiantadosi, Psychonomic Bulletin and Review, 2014Zipf-Mandelbrot form and competing explanationsصيغة Zipf-Mandelbrot والتفسيرات المتنافسة(opens in a new tab)(يفتح في تبويب جديد)
- Zipf's, Heaps' and Taylor's Laws are Determined by the Expansion into the Adjacent PossiblePaperTria, Loreto and Servedio, Entropy, 2018Two-regime Heaps' law figure cited by SLP3شكل قانون Heaps ذي النظامين الذي يستشهد به SLP3(opens in a new tab)(يفتح في تبويب جديد)
- Neural Machine Translation of Rare Words with Subword UnitsPaperSennrich, Haddow and Birch, ACL 2016Byte-pair encoding as the subword answer to rare and unseen wordsالـ byte-pair encoding بوصفه حل الـ subword للكلمات النادرة وغير المرئية(opens in a new tab)(يفتح في تبويب جديد)
- Wikipedia: Size of WikipediaArticleWikipediaEnglish Wikipedia at about 5.27 billion words, used to scale the slide 14 axesحجم Wikipedia الإنجليزية نحو 5.27 مليار كلمة، ويُستخدم لتقدير مقياس محاور الشريحة 14(opens in a new tab)(يفتح في تبويب جديد)
- Pride and Prejudice, plain text (eBook 1342)DocsProject GutenbergPublic domain text behind the explorer's built-in corpus and the growth figuresنص في الملك العام يقوم عليه الـ corpus المدمج في المستكشف وأرقام النمو(opens in a new tab)(يفتح في تبويب جديد)
Part 03: Morphemes: the parts of wordsالمورفيمات: أجزاء الكلمات
The smallest meaning-bearing units, roots and affixes, inflection versus derivation, and how English concatenation differs from Arabic root-and-pattern morphology.أصغر الوحدات الحاملة للمعنى، والجذور والزوائد (affixes)، والتصريف (inflection) مقابل الاشتقاق (derivation)، وكيف يختلف الإلصاق المتسلسل في الإنجليزية عن صرف الجذر والوزن في العربية.
3 concepts3 مفاهيم, ، slides 17-21الشرائح 17-21
Why this part mattersلماذا يهمّ هذا الجزء
Everything a tokenizer, a lemmatizer or a morphological analyzer does rests on the vocabulary in this part. The words you meet in Arabic and English text are not atoms. They are built from smaller meaning-bearing pieces, and the way those pieces combine differs sharply between the two languages you work with.
This part gives you three tools. First, the morpheme itself, with its split into roots and affixes, free and bound. Second, a function test: does a piece keep the dictionary word or make a new one? Third, a form test: are the pieces strung in a line, or is the change inside the word? The Arabic root-and-pattern system is the textbook example of what a contiguous subword tokenizer cannot capture, which is why it matters for your research and not only for the exam. Exam questions ask for segmentation with labels, the inflection versus derivation judgement with reasons, and a morpheme-by-morpheme gloss.
كل ما يفعله الـ tokenizer أو الـ lemmatizer أو المحلّل الصرفي (morphological analyzer) يقوم على المصطلحات التي في هذا الجزء. الكلمات التي تقابلها في النصوص العربية والإنجليزية ليست ذرّات لا تنقسم. إنها مبنية من قطع أصغر تحمل المعنى، وطريقة اتحاد هذه القطع تختلف اختلافًا حادًا بين اللغتين اللتين تعمل عليهما.
يعطيك هذا الجزء ثلاث أدوات. الأولى هي المورفيم (morpheme) نفسه، وتقسيمه إلى جذور ولواصق، وإلى حرّ ومقيّد. الثانية اختبار للوظيفة: هل تُبقي القطعة الكلمة المعجمية نفسها أم تصنع كلمة جديدة؟ الثالثة اختبار للشكل: هل القطع مصفوفة في خط واحد، أم أن التغيير يحدث داخل الكلمة؟ نظام الجذر والوزن (root-and-pattern) في العربية هو المثال النموذجي على ما لا يستطيع الـ subword tokenizer الذي يقطع سلاسل متصلة أن يلتقطه، ولهذا يهمّ بحثك وليس الامتحان فقط. أسئلة الامتحان تطلب التقسيم مع التسميات، والحكم بين التصريف (inflection) والاشتقاق (derivation) مع التعليل، وتحليلًا مورفيمًا بمورفيم (gloss).
By the end you canفي نهاية هذا الجزء ستستطيع
- Segment a word into morphemes and label each one as root or affix, free or bound.تقسيم الكلمة إلى مورفيمات (morphemes) وتصنيف كل واحد منها: جذر (root) أم لاصقة (affix)، وحرّ (free) أم مقيّد (bound).
- Tell a root from a stem, and name the affix positions (prefix, suffix, infix, circumfix) plus compounding.التمييز بين الجذر (root) والساق (stem)، وتسمية مواضع اللواصق (prefix وsuffix وinfix وcircumfix) إضافةً إلى التركيب (compounding).
- Decide whether a process is inflection or derivation using lexeme identity, part of speech and productivity, including conversion.الحكم على عملية ما هل هي تصريف (inflection) أم اشتقاق (derivation) اعتمادًا على هوية المفردة المعجمية (lexeme) وقسم الكلام (part of speech) والإنتاجية (productivity)، بما في ذلك التحويل (conversion).
- Tell concatenative from non-concatenative form, with English, Turkish and Arabic examples.التمييز بين البنية التسلسلية (concatenative) والبنية غير التسلسلية (non-concatenative)، مع أمثلة من الإنجليزية والتركية والعربية.
- Read and write a Leipzig-style morpheme gloss such as house-PL-1SG.POSS-ABL.قراءة وكتابة تحليل مورفيمي (gloss) على طريقة Leipzig، مثل house-PL-1SG.POSS-ABL.
The word cats has four letters but only two units of meaning: cat, the animal, and -s, the signal that there is more than one. The word unhappiness has three: un- for negation, happy for the core idea, and -ness to turn the adjective into a noun. Each of those units is a Morpheme: the smallest unit that carries meaning or a grammatical function. Jurafsky and Martin put it in one line: a morpheme is a minimal meaning-bearing unit in a language, so fox is one morpheme while cats is two (SLP3, section 2.2).
كلمة cats فيها أربعة أحرف لكن فيها وحدتي معنى فقط: cat، أي الحيوان، و-s، العلامة التي تدل على أن العدد أكثر من واحد. وكلمة unhappiness فيها ثلاث وحدات: un- للنفي، وhappy للفكرة الأساسية، و-ness لتحويل الصفة إلى اسم. كل وحدة من هذه الوحدات هي morpheme (مورفيم): أصغر وحدة تحمل معنى أو وظيفة نحوية. يلخصها Jurafsky وMartin في سطر واحد: المورفيم هو أصغر وحدة حاملة للمعنى في اللغة، فكلمة fox مورفيم واحد بينما cats مورفيمان (SLP3، القسم 2.2).
Try the segmentation before the theory. In SLP3 the sentence Doc worked carefully washing the glasses is cut as Doc work-ed care-ful-ly wash-ing the glass-es. Every hyphen marks a boundary where one meaning stops and another begins. Doc and the are single morphemes; carefully is three. Notice what the cuts are not: they are not syllables, and they are not places where the spelling changes. They are places where meaning changes.
جرّب التقسيم قبل النظرية. في SLP3 تُقطَّع الجملة Doc worked carefully washing the glasses هكذا: Doc work-ed care-ful-ly wash-ing the glass-es. كل شرطة تحدد حدًّا ينتهي عنده معنى ويبدأ معنى آخر. Doc وthe كل منهما مورفيم واحد، أما carefully فثلاثة. لاحظ ما ليست عليه هذه القطوع: ليست مقاطع صوتية (syllables)، وليست مواضع يتغير فيها الإملاء. إنها مواضع يتغير فيها المعنى.
The three morphemes of unhappinessالمورفيمات الثلاثة في unhappiness
- un-
- Prefix, bound. Adds negation and keeps the word an adjective.سابقة (prefix)، مقيّدة. تضيف النفي وتُبقي الكلمة صفة.
- happy
- Root, free. Carries the core meaning. Spelled happi before -ness, which is orthography, not a new morpheme.جذر (root)، حرّ. يحمل المعنى الأساسي. يُكتب happi قبل -ness، وهذه مسألة إملائية (orthography) وليست مورفيمًا جديدًا.
- -ness
- Suffix, bound. Turns an adjective into a noun.لاحقة (suffix)، مقيّدة. تحوّل الصفة إلى اسم.
Free and boundالحرّ والمقيّد
The first sorting of morphemes is by independence. A free morpheme can occur by itself as a word: cat, walk, happy. A bound morpheme never occurs alone and is always attached to some other morpheme, the way -s in dogs is (SIL Glossary of Linguistic Terms). Bound morphemes are the affixes: every un-, -ed, -ing and -ness you will ever segment. The test is simple. Could you say it on its own and be understood? happy, yes. ness, no.
أول تصنيف للمورفيمات يكون بحسب الاستقلال. المورفيم الحرّ (free morpheme) يمكن أن يأتي وحده كلمةً: cat، walk، happy. أما المورفيم المقيّد (bound morpheme) فلا يأتي وحده أبدًا، بل يكون دائمًا ملتصقًا بمورفيم آخر، كما هو حال -s في dogs (SIL Glossary of Linguistic Terms). المورفيمات المقيّدة هي affixes (اللواصق): كل un- و-ed و-ing و-ness ستقسّمها يومًا. الاختبار بسيط: هل تستطيع أن تنطقه وحده فيُفهم؟ happy، نعم. ness، لا.
| Kindالنوع | Definitionالتعريف | Examplesأمثلة | Stands alone?يقف وحده؟ |
|---|---|---|---|
| Free morphemeمورفيم حرّ (free morpheme) | Can occur by itself as a wordيمكن أن يأتي وحده كلمةً | cat, walk, happy, snow, mancat, walk, happy, snow, man | Yesنعم |
| Bound morphemeمورفيم مقيّد (bound morpheme) | Never occurs alone, always attached to another morphemeلا يأتي وحده أبدًا، بل يلتصق دائمًا بمورفيم آخر | un-, re-, -s, -ed, -ing, -nessun-, re-, -s, -ed, -ing, -ness | Noلا |
Roots, stems and affixesالجذور والسيقان واللواصق
The second sorting is by job. SLP3 divides the morphemes of a word into roots, the central morpheme supplying the main meaning, and affixes, which add meanings of various kinds: in worked, work is the root and -ed the affix; in glasses, glass is the root and -es the affix (SLP3, section 2.2). The root is the core lexical material, and in English it is usually a free morpheme.
التصنيف الثاني يكون بحسب الوظيفة. يقسم SLP3 مورفيمات الكلمة إلى roots (جذور)، وهي المورفيم المركزي الذي يقدم المعنى الرئيسي، وإلى لواصق (affixes) تضيف معاني من أنواع مختلفة: في worked الجذر هو work واللاصقة -ed؛ وفي glasses الجذر glass واللاصقة -es (SLP3، القسم 2.2). الجذر هو المادة المعجمية الأساسية، وفي الإنجليزية يكون غالبًا مورفيمًا حرًّا.
The lecture adds a third word that students often blur into root: the Stem. A stem is the inflectable base, the thing the grammatical endings attach to. In a simple word like walk the root and the stem are the same string, which is why one slide writes them as root/stem. They come apart once a derived word is inflected. In unhappinesses the root is happy, the core of the meaning, but the plural -es attaches to the whole stem unhappiness. The root is what the word is about; the stem is what the grammar sees.
تضيف المحاضرة كلمة ثالثة كثيرًا ما يخلطها الطلاب بالجذر: الـ stem (الساق). الساق هو القاعدة القابلة للتصريف، أي الشيء الذي تلتصق به النهايات النحوية. في كلمة بسيطة مثل walk يكون الجذر والساق السلسلة نفسها، ولهذا تكتبهما إحدى الشرائح root/stem. ويفترقان عندما تُصرَّف كلمة مشتقة. في unhappinesses الجذر هو happy، لبّ المعنى، لكن علامة الجمع -es تلتصق بالساق كاملًا unhappiness. الجذر هو ما تتحدث عنه الكلمة، والساق هو ما يراه النحو.
Affixes are then named by where they sit. A prefix goes before the stem (un-). A suffix goes after it (-ed, -ing). An infix is inserted inside the stem, and a circumfix wraps around it in two parts at once. Both are rare or absent in English. The standard textbook circumfix is the German past participle, as in ge-spiel-t, played, where ge- and -t together express one meaning (Haspelmath and Sims, chapter 2), and the usual English illustration of infixation is the jokey abso-bloody-lutely. Keep these two as illustrations; the slide only says they exist and are rare. Compounding is different again: it joins two roots without any affix, so snowman is snow plus man and laptop is lap plus top, two free morphemes in one word.
ثم تُسمّى اللواصق بحسب موضعها. السابقة (prefix) تأتي قبل الساق (un-). واللاحقة (suffix) تأتي بعده (-ed، -ing). والداخلة (infix) تُدرج داخل الساق، والمحيطة (circumfix) تلتف حوله بجزأين في الوقت نفسه. وكلتاهما نادرة أو غير موجودة في الإنجليزية. المثال القياسي في الكتب على الـ circumfix هو اسم المفعول الماضي في الألمانية، كما في ge-spiel-t، أي "لُعِب"، حيث يعبّر ge- و-t معًا عن معنى واحد (Haspelmath وSims، الفصل 2)، والمثال الإنجليزي المعتاد على الـ infixation هو الكلمة المازحة abso-bloody-lutely. احتفظ بهذين على أنهما مجرد توضيح؛ فالشريحة تقول فقط إنهما موجودان ونادران. أما Compounding (التركيب) فشيء مختلف: يضم جذرين دون أي لاصقة، فـ snowman هي snow زائد man، وlaptop هي lap زائد top، أي مورفيمان حرّان في كلمة واحدة.
| Processالعملية | Positionالموضع | Exampleمثال | In Englishفي الإنجليزية |
|---|---|---|---|
| Prefixسابقة (prefix) | Before the stemقبل الساق | un-happy, re-newun-happy, re-new | Commonشائعة |
| Suffixلاحقة (suffix) | After the stemبعد الساق | walk-ed, walk-ing, cat-swalk-ed, walk-ing, cat-s | Very commonشائعة جدًا |
| Infixداخلة (infix) | Inside the stemداخل الساق | abso-bloody-lutely (expletive infixation)abso-bloody-lutely (إدخال كلمة شتم، expletive infixation) | Rare, marginalنادرة، هامشية |
| Circumfixمحيطة (circumfix) | Around the stem, two parts at onceحول الساق، بجزأين في الوقت نفسه | German ge-spiel-t, playedالألمانية ge-spiel-t، أي "لُعِب" | Rare; en-light-en is sometimes analysed as oneنادرة؛ وتُحلَّل en-light-en أحيانًا على أنها مثال عليها |
| Compoundingالتركيب (compounding) | Two roots joined, no affix at allضمّ جذرين، دون أي لاصقة | snow-man, lap-topsnow-man, lap-top | Commonشائع |
Worked exampleمثال محلول
Segment carefully and label every pieceقسّم carefully وسمِّ كل قطعة
Find the rootجد الجذر
care is a free morpheme that carries the meaning. It can be a word on its own.care مورفيم حرّ يحمل المعنى، ويمكن أن يكون كلمة وحده.Peel the first affixانزع اللاصقة الأولى
-ful is a bound suffix that turns the noun care into the adjective careful.-ful لاحقة مقيّدة تحوّل الاسم care إلى الصفة careful.Peel the second affixانزع اللاصقة الثانية
-ly is a bound suffix that turns the adjective into the adverb carefully.-ly لاحقة مقيّدة تحوّل الصفة إلى الظرف carefully.Resultالنتيجة
care-ful-ly: root (free) + suffix (bound) + suffix (bound). Three morphemes, each with its own job, exactly as SLP3 segments it.care-ful-ly: جذر (حرّ) + لاحقة (مقيّدة) + لاحقة (مقيّدة). ثلاثة مورفيمات، لكل منها وظيفته، تمامًا كما يقسّمها SLP3.
Click the gap between two letters to place a morpheme boundary. Click again to remove it. Then check your cuts against the answer key.انقر على الفراغ بين حرفين لتضع حدًا بين مورفيمين، وانقر مرة أخرى لإزالته. ثم قارن تقسيمك بمفتاح الإجابة.
After checking, a solid accent bar is a correct cut, a hollow teal bar is a boundary you missed, and a filled teal bar is a cut that falls inside a morpheme.بعد التحقق، يدل الشريط المصمت باللون المميز على قطع صحيح، ويدل الشريط الأخضر المزرق المجوف على حد فاتك، ويدل الشريط الأخضر المزرق الممتلئ على قطع يقع داخل مورفيم.
Arabic roots: a skeleton, not a stringالجذور العربية: هيكل، لا سلسلة متصلة
Everything above assumed the root is a contiguous piece of the word. Arabic breaks that assumption, and it is the reason this part matters so much for your work. The Arabic root for writing is K-T-B, the three consonants ك ت ب. Those three letters never appear next to each other as a word. Instead they are slots, and a pattern of vowels and sometimes extra consonants is threaded between them. The same root with three patterns gives kataba كَتَبَ he wrote, kitāb كِتَاب book, and kātib كَاتِب writer. Look at the Arabic script, where the radicals are highlighted: ك, ت, ب keep their order in every form, and only the short-vowel marks and the long vowel ا between them change.
كل ما سبق افترض أن الجذر قطعة متصلة من الكلمة. العربية تكسر هذا الافتراض، وهذا هو السبب في أن هذا الجزء مهم جدًا لعملك. جذر الكتابة في العربية هو K-T-B، أي الحروف الصامتة الثلاثة ك ت ب. هذه الحروف الثلاثة لا تظهر أبدًا متجاورة على أنها كلمة. بل هي خانات، يُنسج بينها وزن من الحركات وأحيانًا حروف صامتة إضافية. الجذر نفسه مع ثلاثة أوزان يعطي kataba كَتَبَ أي "هو كتب"، وkitāb كِتَاب أي الكتاب، وkātib كَاتِب أي الكاتب. انظر إلى الكتابة العربية حيث الحروف الأصلية مظلّلة: ك وت وب تحافظ على ترتيبها في كل صيغة، ولا يتغير بينها إلا علامات الحركات القصيرة وحرف المدّ ا.
This is Templatic morphology, also called root-and-pattern morphology. The root is an abstract consonantal skeleton, and actual words are formed by adding the vowels and non-root consonants that go with a particular morphological category around the root consonants (Wikipedia, Semitic root). Ryding's reference grammar treats the root and pattern as the two fundamental building blocks of an Arabic word: the root supplies the semantic field, the pattern supplies the grammatical and derivational shape (Ryding, chapter 3). You will see the mechanism itself in the third concept of this part; for now the point is that K-T-B is a root in exactly the sense defined above, core lexical material, but it is discontinuous.
هذا هو templatic morphology (الصرف القالبي)، ويسمى أيضًا صرف الجذر والوزن (root-and-pattern morphology). الجذر هيكل مجرد من الحروف الصامتة، وتتكوّن الكلمات الفعلية بإضافة الحركات والحروف غير الأصلية الخاصة بفئة صرفية معينة حول حروف الجذر (Wikipedia، Semitic root). وتعامل قواعد Ryding المرجعية الجذر والوزن على أنهما لبنتا البناء الأساسيتان للكلمة العربية: الجذر يقدم الحقل الدلالي، والوزن يقدم الشكل النحوي والاشتقاقي (Ryding، الفصل 3). سترى الآلية نفسها في المفهوم الثالث من هذا الجزء؛ أما الآن فالمقصود أن K-T-B جذر بالمعنى المعرَّف أعلاه تمامًا، أي مادة معجمية أساسية، لكنه متقطع.
| Formالصيغة | Transliterationالنقل الصوتي | Meaningالمعنى | Patternالوزن |
|---|---|---|---|
| كَتَبَكَتَبَ | katabakataba | he wroteهو كتب | CaCaCaCaCaCa |
| كِتَابكِتَاب | kitābkitāb | bookكتاب | CiCāCCiCāC |
| كَاتِبكَاتِب | kātibkātib | writerكاتب | CāCiCCāCiC |
Why NLP caresلماذا يهتم NLP بهذا
SLP3 names three candidates for what a Token should be: words, morphemes and characters (SLP3, section 2.4). Earlier it observes that because morphemes are hard to define consistently across languages, it is very difficult to use morphemes as a standard for Tokenization cross-lingually (SLP3, section 2.2). That difficulty is the whole reason subword tokenizers exist, and you will meet them later in this lecture. Arabic root-and-pattern words are the hard case: there is no contiguous substring that means writing shared between kataba, kitāb and kātib, so a tokenizer that only cuts strings cannot see that they are related.
يذكر SLP3 ثلاثة مرشحين لما يجب أن يكون عليه الـ token: الكلمات، والمورفيمات، والحروف (SLP3، القسم 2.4). وقبل ذلك يلاحظ أنه لأن تعريف المورفيمات بشكل متسق عبر اللغات صعب، فمن الصعب جدًا استخدام المورفيمات معيارًا لعملية tokenization عبر اللغات (SLP3، القسم 2.2). هذه الصعوبة هي السبب الكامل لوجود الـ subword tokenizers، وستقابلها لاحقًا في هذه المحاضرة. وكلمات الجذر والوزن العربية هي الحالة الصعبة: لا توجد سلسلة جزئية متصلة تعني "الكتابة" مشتركة بين kataba وkitāb وkātib، فالـ tokenizer الذي يقطع السلاسل فقط لا يستطيع أن يرى أنها مترابطة.
Quick checkاختبار سريع
How many morphemes and how many syllables does the word cats contain?كم مورفيمًا وكم مقطعًا صوتيًا في كلمة cats؟
Recall
Segment unhappiness into morphemes and label each as root or affix, free or bound.قسّم unhappiness إلى مورفيمات وصنّف كلًّا منها: جذر أم لاصقة، حرّ أم مقيّد.
Recall
What is the difference between a root and a stem?ما الفرق بين الجذر (root) والساق (stem)؟
Open a dictionary. walk, walked and walks share one entry; the endings only tell you when the walking happened or who did it. happy and happiness get two entries: an adjective and a noun that names its quality. That single observation is the whole distinction between the two functions an Affix can have. Inflection marks grammar (tense, number, case, agreement) and usually keeps the same Lexeme (the slide's hedge, consistent with SLP3's continuum). Derivation creates a new lexeme, and often changes the part of speech.
افتح قاموسًا. walk وwalked وwalks تشترك في مدخل واحد؛ فالنهايات تخبرك فقط متى حدث المشي أو من قام به. أما happy وhappiness فلكل منهما مدخل: صفة، واسم يسمّي صفتها. هذه الملاحظة الواحدة هي كل الفرق بين الوظيفتين اللتين يمكن أن تؤديهما الـ affix (اللاصقة). الـ inflection (التصريف) يحدد الوظيفة النحوية (الزمن، العدد، الحالة الإعرابية، المطابقة) ويُبقي عادةً الـ lexeme (المفردة المعجمية) نفسها (كلمة "عادةً" تحفّظ من الشريحة، وهو متسق مع اعتبار SLP3 الأمر طيفًا متصلًا). أما الـ derivation (الاشتقاق) فيصنع مفردة معجمية جديدة، وكثيرًا ما يغيّر قسم الكلام.
SLP3 describes the two ends of the scale. Inflectional morphemes are grammatical morphemes that tend to play a syntactic role, such as marking agreement, the plural -s on nouns or the past tense -ed on verbs; they tend to be productive, often obligatory, and their meanings tend to be predictable. Derivational morphemes are more idiosyncratic in their application and meaning, usually apply only to a specific subclass of words, and result in a word of a different grammatical class than the Root, often with a meaning hard to predict exactly (SLP3, section 2.2). SLP3's own example is care, a noun, plus -ful giving an adjective, plus -ly giving an adverb: two derivations in a row, each moving the word to a new category.
يصف SLP3 طرفي المقياس. الـ morphemes التصريفية مورفيمات نحوية تميل إلى أداء دور تركيبي (syntactic)، مثل تحديد المطابقة، أو علامة الجمع -s على الأسماء، أو علامة الماضي -ed على الأفعال؛ وهي تميل إلى أن تكون منتجة (productive)، وكثيرًا ما تكون إلزامية، ومعانيها تميل إلى أن تكون متوقعة. أما المورفيمات الاشتقاقية فأكثر خصوصية في استعمالها ومعناها، وتنطبق عادةً على فئة فرعية محددة من الكلمات فقط، وتنتج كلمة من فئة نحوية مختلفة عن الـ root، وكثيرًا ما يصعب توقع معناها بدقة (SLP3، القسم 2.2). ومثال SLP3 نفسه هو care، وهو اسم، تضاف إليه -ful فيصبح صفة، ثم -ly فيصبح ظرفًا: اشتقاقان متتاليان، كل منهما ينقل الكلمة إلى قسم كلام جديد.
The English slide examples line up with that. walk to walk-ed and walk-s is inflection: every regular verb takes these endings, the meaning is exactly past tense (or past participle) or third person singular, and the word stays a verb. happy to happi-ness is derivation: -ness attaches mainly to adjectives, not every adjective takes it comfortably, and the result is a noun.
أمثلة الشريحة الإنجليزية تتفق مع ذلك. من walk إلى walk-ed وwalk-s تصريف: كل فعل قياسي يأخذ هذه النهايات، والمعنى هو بالضبط الماضي (أو اسم المفعول) أو الغائب المفرد، والكلمة تبقى فعلًا. ومن happy إلى happi-ness اشتقاق: -ness تلتصق بالصفات أساسًا، وليست كل صفة تقبلها بسهولة، والنتيجة اسم.
Derivation with nothing addedاشتقاق دون إضافة أي شيء
Here is the case that catches people. The noun an email became the verb to email without any affix at all. Nothing was attached, the spelling did not change, and yet a new lexeme with a new part of speech now exists. This is Conversion (zero derivation), also called zero derivation: the creation of a word of a new part of speech from an existing word of a different part of speech without any change in form (Wikipedia, Conversion). It is derivation by the test that matters, a new dictionary entry, even though there is no morpheme to point at.
هذه هي الحالة التي يقع فيها الناس. الاسم an email أصبح الفعل to email دون أي لاصقة على الإطلاق. لم يُضف شيء، ولم يتغير الإملاء، ومع ذلك صارت هناك مفردة معجمية جديدة بقسم كلام جديد. هذا هو الـ conversion (التحويل)، ويسمى أيضًا الاشتقاق الصفري (zero derivation): صنع كلمة من قسم كلام جديد من كلمة موجودة من قسم كلام آخر دون أي تغيير في الشكل (Wikipedia، Conversion). إنه اشتقاق بحسب الاختبار المهم، أي وجود مدخل جديد في القاموس، رغم أنه لا يوجد مورفيم تشير إليه.
The same two functions in Arabicالوظيفتان نفسهما في العربية
Arabic uses both functions too, and the slide picks an example of each. Inflection: katab-tu كَتَبْتُ I wrote is the Stem katab plus the suffix -tu, which marks first person singular past. The lexeme is still the verb to write; only who and when changed. Wikipedia's overview of Arabic verbs confirms katabtu as I wrote and notes that person, gender, number, tense, mood and voice are specified by changes to the vowels between the consonants along with prefixes or suffixes (Wikipedia, Arabic verbs). Derivation: kitāb كِتَاب book and kātib كَاتِب writer share the root K-T-B but are two lexemes, a noun for the object and an agent noun for the person, made by choosing two different patterns. Do not read a division of labour into that pair. The slide's inflection example happens to use a suffix and its derivation example a pattern, but Arabic uses both mechanisms for both jobs: the broken plural kutub كُتُب books inflects kitāb by changing the pattern alone, and maktab مَكْتَب office derives a place noun with the maCCaC pattern, whose ma- sits in front of the root like a prefix.
العربية تستخدم الوظيفتين أيضًا، والشريحة تختار مثالًا لكل منهما. التصريف: katab-tu كَتَبْتُ أي "كتبتُ" هي الـ stem katab زائد اللاحقة -tu التي تدل على المتكلم المفرد في الماضي. المفردة المعجمية ما زالت فعل الكتابة؛ لم يتغير إلا من فعل ومتى. وعرض Wikipedia للأفعال العربية يؤكد أن katabtu تعني "كتبتُ"، ويذكر أن الشخص والجنس والعدد والزمن والصيغة (mood) والبناء للمعلوم أو المجهول (voice) تُحدَّد بتغييرات في الحركات بين الحروف الصامتة مع سوابق أو لواحق (Wikipedia، Arabic verbs). الاشتقاق: kitāb كِتَاب أي الكتاب، وkātib كَاتِب أي الكاتب، يشتركان في الجذر K-T-B لكنهما مفردتان معجميتان، اسم للشيء واسم فاعل للشخص، صُنعتا باختيار وزنين مختلفين. لا تستنتج من هذا الزوج تقسيمًا للأدوار. صادف أن مثال الشريحة على التصريف يستخدم لاحقة ومثالها على الاشتقاق يستخدم وزنًا، لكن العربية تستخدم الآليتين للوظيفتين كلتيهما: جمع التكسير kutub كُتُب أي "كتب" يصرّف kitāb بتغيير الوزن وحده، وmaktab مَكْتَب أي المكتب يشتق اسم مكان بالوزن maCCaC، الذي تقع فيه ma- أمام الجذر كأنها سابقة.
| Processالعملية | What changesما الذي يتغير | Lexeme identityهوية المفردة المعجمية | Part of speechقسم الكلام | English exampleمثال إنجليزي | Arabic exampleمثال عربي |
|---|---|---|---|---|---|
| Inflectionالتصريف (inflection) | Grammar: tense, number, case, agreementالوظيفة النحوية: الزمن، العدد، الحالة الإعرابية، المطابقة | Same lexeme (usually)المفردة المعجمية نفسها (عادةً) | Unchangedلا يتغير | walk to walk-ed, walk-swalk إلى walk-ed، walk-s | katab-tu كَتَبْتُ, I wrotekatab-tu كَتَبْتُ، أي "كتبتُ" |
| Derivationالاشتقاق (derivation) | Meaning or categoryالمعنى أو قسم الكلام | New lexemeمفردة معجمية جديدة | Often changesيتغير غالبًا | happy to happi-nesshappy إلى happi-ness | kitāb كِتَاب book versus kātib كَاتِب writerkitāb كِتَاب أي الكتاب، مقابل kātib كَاتِب أي الكاتب |
| Conversionالتحويل (conversion) | Category only, no change in formقسم الكلام فقط، دون أي تغيير في الشكل | New lexemeمفردة معجمية جديدة | Changesيتغير | an email to to emailan email إلى to email | Not covered on the slideغير مذكور في الشريحة |
Four tests to decideأربعة اختبارات للحكم
- Lexeme: would a dictionary list the two forms under one entry? One entry means inflection.المفردة المعجمية (lexeme): هل يضع القاموس الصيغتين تحت مدخل واحد؟ المدخل الواحد يعني تصريفًا.
- Category: did the part of speech change? A change points to derivation, though derivation can also keep it, as un-happy does.قسم الكلام (category): هل تغيّر قسم الكلام؟ التغيير يشير إلى الاشتقاق، مع أن الاشتقاق قد يُبقيه أيضًا، كما في un-happy.
- Productivity: does the affix apply to essentially every word of its class with a predictable meaning? Every regular verb takes -ed; not every adjective takes -ness.الإنتاجية (productivity): هل تنطبق اللاصقة على كل كلمة من فئتها تقريبًا بمعنى متوقع؟ كل فعل قياسي يأخذ -ed؛ وليست كل صفة تأخذ -ness.
- Position: inflection closes the word. In un-happi-ness-es the derivational pieces sit inside and the plural sits outside. Haspelmath and Sims describe this ordering as a strong cross-linguistic tendency (chapter 5).الموضع (position): التصريف يُغلق الكلمة. في un-happi-ness-es تقع القطع الاشتقاقية في الداخل وعلامة الجمع في الخارج. ويصف Haspelmath وSims هذا الترتيب بأنه نزعة قوية عبر اللغات (الفصل 5).
Worked exampleمثال محلول
Is -ed in walked inflection or derivation?هل -ed في walked تصريف أم اشتقاق؟
Lexeme testاختبار المفردة المعجمية
walk and walked are one dictionary entry. Same lexeme.walk وwalked مدخل واحد في القاموس. المفردة المعجمية نفسها.Category testاختبار قسم الكلام
Both are verbs. The part of speech did not change.كلتاهما فعل. قسم الكلام لم يتغير.Productivity testاختبار الإنتاجية
Every regular English verb takes -ed, and its meaning is always grammatical, past tense or past participle. Obligatory and predictable.كل فعل إنجليزي قياسي يأخذ -ed، ومعناها دائمًا نحوي: الماضي أو اسم المفعول (past participle). إلزامية ومتوقعة.Position testاختبار الموضع
-ed is the last thing on walked, and in a verb form nothing follows it. That fits the tendency for inflection to sit outside derivation, though participial adjectives such as preparedness show it is a tendency, not a law.-ed هي آخر شيء في walked، ولا يأتي بعدها شيء في الصيغة الفعلية. وهذا يتفق مع نزعة التصريف إلى الوقوع خارج الاشتقاق، مع أن صفات اسم المفعول مثل preparedness تبيّن أنها نزعة لا قانون.Resultالنتيجة
Inflection, on all four tests.تصريف، بحسب الاختبارات الأربعة كلها.
Worked exampleمثال محلول
Label the affixes of un-happi-nessصنّف لواصق un-happi-ness
un-un-
Negation. The word stays an adjective, but unhappy is a separate dictionary entry from happy, and un- attaches selectively (unhappy, but not unsad). Derivational.نفي. الكلمة تبقى صفة، لكن unhappy مدخل مستقل في القاموس عن happy، وun- تلتصق انتقائيًا (unhappy، لكن ليس unsad). اشتقاقية.-ness-ness
Adjective to noun, a new lexeme with a new category. Derivational.من صفة إلى اسم، أي مفردة معجمية جديدة بقسم كلام جديد. اشتقاقية.Resultالنتيجة
Two derivational affixes and no inflection. Add a plural and you get unhappiness-es, with the inflection on the outside.لاصقتان اشتقاقيتان ولا تصريف. أضف علامة الجمع فتحصل على unhappiness-es، والتصريف في الخارج.
Quick checkاختبار سريع
Which process turns the noun email into the verb to email?أي عملية تحوّل الاسم email إلى الفعل to email؟
Quick checkاختبار سريع
Which pair shows the same lexeme with different grammatical marking?أي زوج يُظهر المفردة المعجمية نفسها مع علامة نحوية مختلفة؟
Recall
Is the -ed of walked inflection or derivation? Give two reasons.هل -ed في walked تصريف أم اشتقاق؟ اذكر سببين.
Take scissors to walked and you can cut it into walk and ed. Take scissors to sang and there is nowhere to cut: the past tense lives in the vowel, in the middle of the root, and no substring means past. Both words are past-tense Inflection. They differ not in function but in form. That is the second axis of this part, independent of the first: Concatenative morphology attaches segments in a line, and Non-concatenative morphology changes the inside of the word instead.
خذ مقصًّا إلى walked وستستطيع قصّها إلى walk وed. وخذ المقص إلى sang فلن تجد موضعًا للقص: زمن الماضي يسكن في الحركة، في وسط الجذر، ولا توجد سلسلة جزئية تعني "الماضي". الكلمتان كلتاهما inflection (تصريف) للماضي. وهما لا تختلفان في الوظيفة بل في الشكل. هذا هو المحور الثاني في هذا الجزء، وهو مستقل عن الأول: الـ concatenative morphology (الصرف التسلسلي) يضيف القطع متتالية في خط واحد، والـ non-concatenative morphology (الصرف غير التسلسلي) يغيّر داخل الكلمة بدلًا من ذلك.
Concatenative morphology covers everything you have segmented so far: a prefix before, a suffix after, or two roots side by side. cat-s, walk-ed, un-happy and snow-man are all built by placing one contiguous piece next to another. The pieces keep their shape, and you can recover them by cutting. Non-concatenative morphology is defined by what it lacks: word formation and inflection in which the Root is modified and which does not involve stringing morphemes together sequentially (Wikipedia, Nonconcatenative morphology). The slide groups it into internal change, templatic patterns and Suppletion.
الصرف التسلسلي يشمل كل ما قسّمته حتى الآن: سابقة قبل، أو لاحقة بعد، أو جذران جنبًا إلى جنب. cat-s وwalk-ed وun-happy وsnow-man كلها مبنية بوضع قطعة متصلة بجوار أخرى. القطع تحافظ على شكلها، وتستطيع استعادتها بالقص. أما الصرف غير التسلسلي فيُعرَّف بما ينقصه: بناء الكلمات والتصريف الذي يُعدَّل فيه الـ root ولا يتضمن ضمّ الـ morphemes بعضها إلى بعض بالتتابع (Wikipedia، Nonconcatenative morphology). والشريحة تجمعه في ثلاثة أنواع: التغيير الداخلي (internal change)، والـ templatic patterns (الأوزان القالبية)، والـ suppletion (الإبدال الكلي).
Concatenation taken to its limit: Turkishالتسلسل إلى أقصى حدوده: التركية
Turkish shows how far the concatenative strategy can go. The word evlerimden means from my houses, and it is four pieces in a row: ev-ler-im-den. Turkish is a highly agglutinative language, in that much of the grammar is expressed by means of suffixes added to nouns and verbs, and evlerden from the houses is analysed as ev house, -ler plural, -den ablative (Wikipedia, Turkish grammar). Adding the first person possessive -im between them gives the slide's form. Each suffix has a clean boundary and stays recognisable, which is what makes the word so easy to cut (one suffix, -im, still bundles person, number and possession, hence the periods in its gloss).
التركية تبيّن إلى أي حد يمكن أن تصل الاستراتيجية التسلسلية. كلمة evlerimden تعني "من بيوتي"، وهي أربع قطع في صف واحد: ev-ler-im-den. التركية لغة agglutinative (إلصاقية) إلى درجة عالية، بمعنى أن كثيرًا من النحو يُعبَّر عنه بلواحق تضاف إلى الأسماء والأفعال، وevlerden أي "من البيوت" تُحلَّل إلى ev بيت، و-ler جمع، و-den حالة الابتداء (ablative) (Wikipedia، Turkish grammar). وإضافة ضمير الملكية للمتكلم -im بينهما تعطي صيغة الشريحة. كل لاحقة لها حدّ واضح وتبقى قابلة للتمييز، وهذا ما يجعل قصّ الكلمة سهلًا جدًا (مع أن لاحقة واحدة، -im، ما زالت تجمع الشخص والعدد والملكية معًا، ولهذا توجد النقاط في تحليلها).
ev-ler-im-den, from my housesev-ler-im-den، أي من بيوتي
- ev
- house. Root, free.بيت (house). جذر، حرّ.
- -ler
- PL, plural. Suffix, bound.PL، الجمع. لاحقة، مقيّدة.
- -im
- 1SG.POSS, first person singular possessor, my. Suffix, bound.1SG.POSS، المالك المتكلم المفرد، أي "ـي" (my). لاحقة، مقيّدة.
- -den
- ABL, ablative case, from. Suffix, bound.ABL، حالة الابتداء (ablative)، أي "من". لاحقة، مقيّدة.
Three ways to change the insideثلاث طرق لتغيير الداخل
Internal change is the English strong-verb pattern. sing, sang, sung (and the noun song) differ only in the vowel of the root. This vowel alternation is called Ablaut, a system of regular vowel variations inherited from Proto-Indo-European (Wikipedia, Indo-European ablaut). The root and the tense are fused in one syllable; there is no -ed to remove.
التغيير الداخلي هو نمط الأفعال القوية (strong verbs) في الإنجليزية. sing وsang وsung (والاسم song) لا تختلف إلا في حركة الجذر. هذا التناوب في الحركة يسمى ablaut، وهو نظام من التغيرات المنتظمة في الحركات موروث من اللغة الهندية الأوروبية الأم (Proto-Indo-European) (Wikipedia، Indo-European ablaut). الجذر والزمن مندمجان في مقطع واحد؛ ولا توجد -ed لتنزعها.
Templatic patterns are the Arabic case from the first concept, now seen as a mechanism. The root ك ت ب stays fixed in order, and a template of vowels and extra consonants is woven through it: kataba كَتَبَ he wrote, kitāb كِتَاب book, kātib كَاتِب writer. The pieces of the pattern are not contiguous with each other and neither are the pieces of the root, so there is no cut that separates the two morphemes. Watch how the radicals never move while the material between them changes.
الأوزان القالبية هي الحالة العربية من المفهوم الأول، ونراها الآن آليةً. الجذر ك ت ب يبقى ثابت الترتيب، ويُنسج من خلاله قالب من الحركات والحروف الإضافية: kataba كَتَبَ أي "هو كتب"، وkitāb كِتَاب أي الكتاب، وkātib كَاتِب أي الكاتب. قطع الوزن ليست متصلة بعضها ببعض، وكذلك قطع الجذر، فلا يوجد قطع يفصل بين المورفيمين. لاحظ كيف أن الحروف الأصلية لا تتحرك أبدًا بينما تتغير المادة التي بينها.
Look closely at yaktubu يَكْتُبُ he writes, and you will see both mechanisms at once. The prefix ya- and the suffix -u are concatenative; the Stem shape -ktub-, with no vowel after k and u after t, the pattern CCuC woven through the radicals, is templatic. Arabic words are typically built by wrapping affixes around a root-and-pattern core, which is why an Arabic morphological analyzer has to do two different kinds of work.
تأمّل yaktubu يَكْتُبُ أي "هو يكتب"، وسترى الآليتين معًا. السابقة ya- واللاحقة -u تسلسليتان؛ أما شكل الـ stem -ktub-، بلا حركة بعد k وبـ u بعد t، أي الوزن CCuC المنسوج عبر الحروف الأصلية، فهو قالبي. الكلمات العربية تُبنى عادةً بلفّ affixes (لواصق) حول نواة من الجذر والوزن، ولهذا يحتاج المحلّل الصرفي العربي إلى أداء نوعين مختلفين من العمل.
Suppletion is the extreme case. The past tense of go is went, and no rule relates the two strings. Suppletion is the use of one word as the inflected form of another word when the two words are not cognates; went was originally the past tense of the verb wend (Wikipedia, Suppletion). Haspelmath and Sims treat it as the extreme case of allomorphy, where the two forms share no phonological material, and the slide lists it under non-concatenative because the outcome is the same: a grammatical change with no segment you can cut off. Suppletion also covers good to better.
الـ suppletion (الإبدال الكلي) هو الحالة القصوى. ماضي go هو went، ولا توجد قاعدة تربط السلسلتين. الإبدال الكلي هو استعمال كلمة صيغةً مصرَّفة لكلمة أخرى حين لا تكون الكلمتان من أصل واحد (cognates)؛ وwent كانت في الأصل ماضي الفعل wend (Wikipedia، Suppletion). ويعامله Haspelmath وSims على أنه الحالة القصوى من تعدد صور المورفيم (allomorphy)، حيث لا تشترك الصيغتان في أي مادة صوتية، والشريحة تضعه تحت غير التسلسلي لأن النتيجة واحدة: تغيير نحوي دون قطعة تستطيع قصّها. ويشمل الإبدال الكلي أيضًا good إلى better.
| Mechanismالآلية | How the form changesكيف يتغير الشكل | Englishالإنجليزية | Other languagesلغات أخرى | Cut with scissors?يُقصّ بالمقص؟ |
|---|---|---|---|---|
| Concatenativeتسلسلي (concatenative) | A contiguous affix or root is added in sequenceتُضاف لاصقة أو جذر متصل بالتتابع | cat-s, walk-ed, un-happy, snow-mancat-s، walk-ed، un-happy، snow-man | Turkish ev-ler-im-den, house-PL-1SG.POSS-ABL, from my housesالتركية ev-ler-im-den، house-PL-1SG.POSS-ABL، أي من بيوتي | Yesنعم |
| Non-concatenative: internal changeغير تسلسلي: تغيير داخلي (internal change) | A vowel inside the root changesتتغير حركة داخل الجذر | sing, sang, sungsing، sang، sung | German umlaut plural Vater, Väter (illustration)جمع الـ umlaut في الألمانية Vater، Väter (للتوضيح) | Noلا |
| Non-concatenative: templaticغير تسلسلي: قالبي (templatic) | A vowel pattern is interleaved with a consonantal rootيُنسج وزن من الحركات مع جذر من الحروف الصامتة | None in Englishلا يوجد في الإنجليزية | Arabic كَتَبَ kataba, يَكْتُبُ yaktubu, كِتَاب kitāb from K-T-Bالعربية كَتَبَ kataba، يَكْتُبُ yaktubu، كِتَاب kitāb من الجذر K-T-B | Noلا |
| Non-concatenative: suppletionغير تسلسلي: إبدال كلي (suppletion) | The whole form is replaced by an unrelated oneيُستبدل الشكل كله بشكل لا صلة له به | go, went; good, bettergo، went؛ good، better | Not on the slideغير مذكور في الشريحة | Noلا |
Two axes, not oneمحوران، لا محور واحد
Function and form are independent. walked and sang are both inflection; one is concatenative and one is not. happiness and kitāb are both Derivation; one is concatenative and one is templatic. When you analyse a form, answer both questions separately: what does the change do, and how is the change realised?
الوظيفة والشكل مستقلان. walked وsang كلتاهما تصريف؛ الأولى تسلسلية والثانية ليست كذلك. وhappiness وkitāb كلتاهما derivation (اشتقاق)؛ الأولى تسلسلية والثانية قالبية. عندما تحلّل صيغة ما، أجب عن السؤالين كلٍّ على حدة: ماذا يفعل التغيير، وكيف يتحقق التغيير؟
The form axis is the one that decides what a tokenizer can see. Subword tokenization methods such as Byte-pair encoding (BPE) work on contiguous substrings, so they approximate concatenative morphology well: walk can be shared between walked and walking because it is a substring of both. A discontinuous root like K-T-B is never a substring of anything, so the same tokenizer cannot share the writing meaning across kataba, kitāb and kātib. That is SLP3's cross-lingual difficulty made concrete, and it is the hook for most Arabic tokenization research.
محور الشكل هو الذي يحدد ما يستطيع الـ tokenizer أن يراه. طرق الـ subword tokenization مثل byte-pair encoding تعمل على سلاسل جزئية متصلة، ولذلك تقارب الصرف التسلسلي جيدًا: يمكن أن تكون walk مشتركة بين walked وwalking لأنها سلسلة جزئية من كلتيهما. أما الجذر المتقطع مثل K-T-B فليس سلسلة جزئية من أي شيء، فلا يستطيع الـ tokenizer نفسه أن يجعل معنى "الكتابة" مشتركًا بين kataba وkitāb وkātib. هذه هي الصعوبة عبر اللغات التي ذكرها SLP3 وقد صارت ملموسة، وهي المدخل لمعظم أبحاث الـ tokenization العربية.
Quick checkاختبار سريع
Which form is built by non-concatenative morphology?أي صيغة مبنية بالصرف غير التسلسلي (non-concatenative)؟
Recall
Give one example of non-concatenative morphology in English and one in Arabic.اذكر مثالًا واحدًا على الصرف غير التسلسلي في الإنجليزية ومثالًا واحدًا في العربية.
Recall
Gloss ev-ler-im-den morpheme by morpheme.حلّل ev-ler-im-den مورفيمًا بمورفيم (gloss).
Recapالخلاصة
If you remember nothing elseإن لم تتذكر شيئاً آخر فتذكّر هذا
- A morpheme is the smallest unit that carries meaning or grammatical function: cats = cat + -s, unhappiness = un- + happy + -ness.المورفيم (morpheme) هو أصغر وحدة تحمل معنى أو وظيفة نحوية: cats = cat + -s، وunhappiness = un- + happy + -ness.
- Free morphemes stand alone; bound morphemes (affixes) must attach. The root carries the core meaning; the stem is the base that takes inflection.المورفيمات الحرّة (free) تقف وحدها، أما المقيّدة (bound)، أي اللواصق (affixes)، فلا بد أن تلتصق بغيرها. الجذر (root) يحمل المعنى الأساسي، والساق (stem) هو القاعدة التي يدخل عليها التصريف (inflection).
- Affixes are prefixes, suffixes and the rare infixes and circumfixes; compounding joins two free roots (snowman, laptop).اللواصق هي السوابق (prefixes) واللواحق (suffixes)، ثم الدواخل (infixes) والمحيطات (circumfixes) النادرة؛ أما التركيب (compounding) فيضم جذرين حرّين معًا (snowman، laptop).
- Arabic roots such as K-T-B are discontinuous consonant skeletons; patterns interleave vowels to give kataba, kitab and katib.الجذور العربية مثل K-T-B هياكل متقطعة من الحروف الصامتة؛ والأوزان (patterns) تُدخل الحركات بين حروفها فتعطي kataba وkitab وkatib.
- Inflection marks grammar and usually keeps the lexeme (walk-ed, katab-tu); derivation makes a new lexeme and often a new category (happi-ness, kitab versus katib); conversion derives with no added form (an email, to email).التصريف (inflection) يحدد الوظيفة النحوية ويُبقي عادةً المفردة المعجمية (lexeme) نفسها (walk-ed، katab-tu)؛ والاشتقاق (derivation) يصنع مفردة معجمية جديدة وكثيرًا ما يغيّر قسم الكلام (happi-ness، kitab مقابل katib)؛ والتحويل (conversion) اشتقاق بلا أي إضافة في الشكل (an email، to email).
- Concatenative morphology attaches segments in a line (cat-s, ev-ler-im-den); non-concatenative morphology changes the inside (sing, sang, sung; kataba, yaktubu, kitab) or replaces the form (go, went).البنية التسلسلية (concatenative) تضيف القطع متتالية في خط واحد (cat-s، ev-ler-im-den)؛ والبنية غير التسلسلية (non-concatenative) تغيّر داخل الكلمة (sing، sang، sung؛ kataba، yaktubu، kitab) أو تستبدل الشكل كله (go، went).
- Function and form are independent axes: walked and sang are both inflection, one concatenative and one not. Arabic uses both mechanisms at once.الوظيفة والشكل محوران مستقلان: walked وsang كلاهما تصريف، لكن الأولى تسلسلية والثانية ليست كذلك. والعربية تستخدم الآليتين معًا في الوقت نفسه.
- Syllables are sound units and morphemes are meaning units. The two do not line up.المقاطع (syllables) وحدات صوتية، والمورفيمات وحدات معنى، ولا يتطابق الاثنان.
Sourcesالمصادر
- Speech and Language Processing, 3rd edition draft, chapter 2: Words and TokensBookJurafsky and Martin, StanfordSections 2.2 and 2.4: morphemes, roots and affixes, inflectional versus derivational; tokens as words, morphemes or charactersالقسمان 2.2 و2.4: المورفيمات، والجذور واللواصق، والتصريفي مقابل الاشتقاقي؛ والـ tokens كلماتٍ أو مورفيمات أو حروفًا(opens in a new tab)(يفتح في تبويب جديد)
- Understanding Morphology, 2nd editionBookRoutledge, Haspelmath and SimsBasic concepts (affix positions, circumfix), inflection and derivation (chapter 5), suppletionالمفاهيم الأساسية (مواضع اللواصق، والـ circumfix)، والتصريف والاشتقاق (الفصل 5)، والإبدال الكلي (suppletion)(opens in a new tab)(يفتح في تبويب جديد)
- A Reference Grammar of Modern Standard ArabicBookCambridge University Press, Karin C. RydingChapter 3, Arabic word structure: root and patternالفصل 3، بنية الكلمة العربية: الجذر والوزن(opens in a new tab)(يفتح في تبويب جديد)
- The Leipzig Glossing RulesDocsMax Planck Institute for Evolutionary AnthropologyRule 2 on hyphens; abbreviations PL, 1, SG, POSS, ABLالقاعدة 2 عن الشرطات؛ والاختصارات PL و1 وSG وPOSS وABL(opens in a new tab)(يفتح في تبويب جديد)
- Glossary of Linguistic Terms: bound morphemeDocsSIL InternationalDefinitions of free and bound morphemesتعريفات المورفيمات الحرّة والمقيّدة(opens in a new tab)(يفتح في تبويب جديد)
- Semitic rootArticleWikipediaConsonantal roots and transfixes; k-t-b forms kataba, yaktubu, kātibالجذور الصامتة والـ transfixes؛ وصيغ k-t-b: kataba وyaktubu وkātib(opens in a new tab)(يفتح في تبويب جديد)
- Arabic verbsArticleWikipediakatabtu, I wrote; affixes plus vowel changes mark person, number, tensekatabtu بمعنى كتبتُ؛ اللواصق مع تغييرات الحركات تحدد الشخص والعدد والزمن(opens in a new tab)(يفتح في تبويب جديد)
- Turkish grammarArticleWikipediaAgglutination, evlerden analysed as ev, -ler, -denالإلصاق (agglutination)، وتحليل evlerden إلى ev و-ler و-den(opens in a new tab)(يفتح في تبويب جديد)
- Nonconcatenative morphologyArticleWikipediaDefinition; apophony, transfixation, reduplication, truncationالتعريف؛ وتناوب الحركات (apophony)، والـ transfixation، والتكرار (reduplication)، والبتر (truncation)(opens in a new tab)(يفتح في تبويب جديد)
- Indo-European ablautArticleWikipediasing, sang, sung, song as a regular vowel alternationsing وsang وsung وsong بوصفها تناوبًا منتظمًا في الحركة(opens in a new tab)(يفتح في تبويب جديد)
- SuppletionArticleWikipediaDefinition; went from the verb wendالتعريف؛ وأصل went من الفعل wend(opens in a new tab)(يفتح في تبويب جديد)
- Conversion (word formation)ArticleWikipediaZero derivation; email as a verbified nounالاشتقاق الصفري (zero derivation)؛ وemail اسمًا صار فعلًا(opens in a new tab)(يفتح في تبويب جديد)
Part 04: Clitics and morphological typologyاللواحق المتصلة (Clitics) والتصنيف الصرفي
Why some attached pieces are words in disguise, how to tell a clitic from an affix, and where languages sit between isolating and polysynthetic, with English and Arabic placed on the map.لماذا تكون بعض الأجزاء الملتصقة كلمات متنكرة، وكيف نميز اللاحقة المتصلة (clitic) من الزائدة (affix)، وأين تقع اللغات بين العازلة (isolating) والمتعددة التركيب (polysynthetic)، مع تحديد موقع الإنجليزية والعربية على الخريطة.
3 concepts3 مفاهيم, ، slides 22-28الشرائح 22-28
Why this part mattersلماذا يهمّ هذا الجزء
Every Arabic NLP model you will build starts with a decision you may not notice making: what is a token? Arabic writes conjunctions, prepositions, the article and pronouns onto the same string as the noun or verb, so وَبِالْبَيْت is one whitespace token that a linguist would call four words. Alotaiby, Foda and Alkharashi (2010) measured what that costs: splitting clitics off a 600,000,000-word corpus removed 24.54% of its vocabulary. That number is why this part exists.
Part 03 gave you morphemes, roots, affixes and the difference between inflection and derivation. This part adds the two remaining pieces of the morphology story. First, a test that decides whether an attached element is an affix at all, or a word that only leans on its neighbor for pronunciation. Second, a vocabulary for comparing whole languages by how much they pack into a word, which ends in a number line that predicts how hard a language will be to tokenize. Exams ask for the diagnostics and the classification with forms; your research needs the same ideas to choose a preprocessing pipeline and to read why a shared subword vocabulary fragments Arabic more than English (part 07).
كل نموذج لمعالجة العربية ستبنيه يبدأ بقرار قد لا تنتبه أنك اتخذته: ما هو الـtoken؟ العربية تكتب حروف العطف وحروف الجر وأداة التعريف والضمائر ملتصقة بالاسم أو الفعل في سلسلة واحدة، لذلك وَبِالْبَيْت وحدة واحدة بين مسافتين بينما يعدّها اللساني أربع كلمات. قاس Alotaiby وFoda وAlkharashi (2010) تكلفة ذلك: فصل اللواحق الكلامية في مدوّنة من 600,000,000 كلمة أزال 24.54% من مفرداتها. هذا الرقم هو سبب وجود هذا الجزء.
أعطاك الجزء 03 المورفيمات والجذور والزوائد والفرق بين التصريف (inflection) والاشتقاق (derivation). يضيف هذا الجزء القطعتين الباقيتين من قصة الصرف. الأولى اختبار يحسم هل العنصر الملتصق زائدة صرفية أصلًا، أم كلمة مستقلة تستند إلى جارتها في النطق فقط. والثانية مفردات لمقارنة اللغات كاملة بحسب ما تحشوه في الكلمة الواحدة، وتنتهي بخط أعداد يتنبأ بصعوبة تقطيع اللغة. الامتحانات تطلب الاختبارات التشخيصية والتصنيف مع أمثلة صيغ؛ وبحثك يحتاج الأفكار نفسها لاختيار مسار المعالجة المسبقة، ولفهم لماذا تُفتّت مفردات الوحدات الفرعية المشتركة العربيةَ أكثر من الإنجليزية (الجزء 07).
By the end you canفي نهاية هذا الجزء ستستطيع
- Apply two diagnostics (selectivity, paradigm membership) to decide clitic versus affix, including katab-tu, kitab-u-hu and the borderline al-.تطبيق اختبارين تشخيصيين (الانتقائية، والانتماء إلى جدول التصريف) للحكم على عنصر ملتصق: هل هو لاحقة كلامية (clitic) أم زائدة صرفية (affix)، بما في ذلك katab-tu وkitab-u-hu والحالة الحدّية al-.
- Classify a language form as isolating, agglutinative, fusional or polysynthetic and explain why these are tendencies per subsystem, not boxes.تصنيف صيغة لغوية على أنها عازلة (isolating) أو لصقية (agglutinative) أو اندماجية (fusional) أو متعددة التركيب (polysynthetic)، وشرح لماذا هذه ميول تختلف من نظام فرعي إلى آخر وليست صناديق ثابتة.
- Place English and Arabic on the typology map and name one fusional pocket in English.تحديد موقع الإنجليزية والعربية على خريطة التصنيف، وذكر جيب اندماجي واحد في الإنجليزية.
- Define Greenberg's index of synthesis, order the eight languages on it, and compute it on a short text.تعريف مؤشر التركيب (index of synthesis) عند Greenberg، وترتيب اللغات الثماني عليه، وحسابه على نص قصير.
- Explain, with numbers, why rich morphology motivates subword tokenization, morphological segmentation and explicit clitic policies.شرح بالأرقام لماذا يدفع الصرف الغني إلى التقطيع إلى وحدات فرعية (subword tokenization) والتجزئة الصرفية وسياسات صريحة للواحق الكلامية.
Start with an English sentence that Zwicky and Pullum (1983) use in section 2 of their paper: The person I was talking to's going to be angry. The 's is a reduced is, and it is hanging off the preposition to. Now vary the host: The ball you hit's just broken my window puts it on a verb, Any answer not entirely right's going to be marked on an adjective, The drive home tonight's been really easy on an adverb. One element, four host categories. It is a reduced auxiliary throughout, is in the first and third sentence and has in the second and fourth, and in every case it does exactly what the separate word is or has would do.
ابدأ بجملة إنجليزية يستخدمها Zwicky وPullum (1983) في القسم 2 من ورقتهما: The person I was talking to's going to be angry. الـ's هنا صيغة مختصرة من is، وهي معلّقة بحرف الجر to. غيّر الآن المضيف: الجملة The ball you hit's just broken my window تضعها على فعل، وAny answer not entirely right's going to be marked على صفة، وThe drive home tonight's been really easy على ظرف. عنصر واحد وأربع فئات من المضيفات. وهو فعل مساعد مختصر في كل الحالات، is في الجملتين الأولى والثالثة وhas في الثانية والرابعة، وفي كل حالة يؤدي بالضبط ما كانت ستؤديه الكلمة المستقلة is أو has.
Compare the plural -s of cats. It attaches to nouns and to nothing else, and it never does the job of a word: there is no sentence in which plural -s is the verb or the subject. That difference in behavior is what separates a Clitic from an Affix. Jurafsky and Martin define a clitic as "a morpheme that acts syntactically like a word but is reduced in form and attached (phonologically and sometimes orthographically) to another word" (SLP3, chapter 2). The two halves of that definition pull in opposite directions, which is why clitics are confusing: in the syntax they are words, in the sound stream they are part of a word.
قارن ذلك بلاحقة الجمع -s في cats. إنها تلتصق بالأسماء ولا شيء غيرها، ولا تؤدي أبدًا عمل كلمة: لا توجد جملة تكون فيها -s الجمع هي الفعل أو الفاعل. هذا الفرق في السلوك هو ما يفصل اللاحقة الكلامية clitic عن الزائدة الصرفية affix. يعرّف Jurafsky وMartin الـclitic بأنه «مورفيم يتصرف نحويًا ككلمة لكنه مختزل في شكله وملتصق (صوتيًا وأحيانًا كتابيًا) بكلمة أخرى» (SLP3، الفصل 2). نصفا هذا التعريف يشدّان في اتجاهين متعاكسين، ولهذا تربك اللواحق الكلامية الطلاب: في النحو هي كلمات، وفي سلسلة الأصوات هي جزء من كلمة.
Why spelling is not the testلماذا ليست الكتابة هي الاختبار
English happens to mark most clitics with an apostrophe (I'm, we've, possessive 's), and French does the same with l' in l'opéra. That is a writing convention, not a grammatical fact. Arabic writes every clitic solidly attached with no separator at all, so if attachment in writing were the criterion, Arabic would have no clitics and English would have almost none outside contractions. The slide's key sentence is worth memorizing verbatim: attachment in writing is not enough, use diagnostics.
تصادف أن الإنجليزية تميّز معظم لواحقها الكلامية بفاصلة علوية (I'm وwe've و's الملكية)، والفرنسية تفعل الشيء نفسه مع l' في l'opéra. هذا عُرف كتابي وليس حقيقة نحوية. العربية تكتب كل لاحقة كلامية ملتصقة تمامًا دون أي فاصل، فلو كان الالتصاق في الكتابة هو المعيار لما كان في العربية لواحق كلامية أصلًا، ولما كان في الإنجليزية إلا القليل خارج الاختصارات. الجملة المفتاحية في الشريحة تستحق الحفظ حرفيًا: الالتصاق في الكتابة لا يكفي، استخدم الاختبارات التشخيصية.
The diagnostics come from Zwicky and Pullum. Their first criterion is the one this course uses as the primary test, and they state it as: "Clitics can exhibit a low degree of selection with respect to their hosts, while affixes exhibit a high degree of selection with respect to their stems." This is Selectivity. In a footnote they give it as a ladder: an element that attaches to any word of a major class is least selective, then one that attaches only to verbs, then only to a subclass of verbs, then only to a few specified verbs. The further down the ladder, the more affix-like the element. The second test the slide names is paradigm membership: an affix fills one cell of a table of forms, a clitic does not. All six of their criteria are in the table below alongside the slide's two tests, and you should be able to name at least selectivity, arbitrary gaps and idiosyncrasy.
الاختبارات التشخيصية مأخوذة من Zwicky وPullum. معيارهما الأول هو ما يعتمده هذا المقرر اختبارًا أساسيًا، ويصوغانه هكذا: «يمكن أن تُظهر اللواحق الكلامية درجة منخفضة من الانتقاء تجاه مضيفاتها، بينما تُظهر الزوائد الصرفية درجة عالية من الانتقاء تجاه جذوعها». هذه هي الانتقائية selectivity. وفي حاشية يقدّمانها كسلّم: العنصر الذي يلتصق بأي كلمة من فئة رئيسية هو الأقل انتقائية، يليه ما يلتصق بالأفعال فقط، ثم بفئة فرعية من الأفعال فقط، ثم بعدد قليل من أفعال محددة فقط. كلما نزلت على السلّم صار العنصر أشبه بالزائدة الصرفية. الاختبار الثاني الذي تذكره الشريحة هو الانتماء إلى جدول التصريف (paradigm): الزائدة الصرفية تملأ خانة واحدة في جدول صيغ، واللاحقة الكلامية لا تفعل. معاييرهما الستة كلها في الجدول أدناه إلى جانب اختباري الشريحة، وينبغي أن تستطيع تسمية الانتقائية والفجوات الاعتباطية (arbitrary gaps) والشذوذ (idiosyncrasy) على الأقل.
Clitic versus affix diagnostics (Zwicky and Pullum 1983)اختبارات التمييز بين اللاحقة الكلامية والزائدة الصرفية (Zwicky وPullum 1983)
- Syntactic roleالدور النحوي
- A clitic is a function word or pronoun that the syntax treats as a word of its own. An affix marks a feature on its host and has no independent slot in the sentence.اللاحقة الكلامية (clitic) كلمة وظيفية أو ضمير يعامله النحو كلمةً مستقلة. أما الزائدة الصرفية (affix) فتؤشّر على سمة في مضيفها، وليس لها موضع مستقل في الجملة.
- Selectivity (Zwicky and Pullum A)الانتقائية (المعيار A عند Zwicky وPullum)
- Clitics show low selectivity: they attach to almost any host category. Affixes show high selectivity: one stem class, sometimes one subclass.اللواحق الكلامية قليلة الانتقائية: تلتصق بأي فئة مضيف تقريبًا. والزوائد الصرفية عالية الانتقائية: صنف واحد من الجذوع، وأحيانًا صنف فرعي واحد.
- Paradigm membershipالانتماء إلى جدول التصريف
- An affix fills a cell in a paradigm (singular, plural; katab-tu, katab-ta, katab-a). A clitic belongs to no paradigm of its host.الزائدة الصرفية تملأ خانة في جدول تصريف (مفرد، جمع؛ katab-tu وkatab-ta وkatab-a). أما اللاحقة الكلامية فلا تنتمي إلى أي جدول تصريف لمضيفها.
- Arbitrary gaps (B)الفجوات الاعتباطية (B)
- Affixed forms have unexplained holes (no English amn't). Clitic combinations do not.الصيغ ذات الزوائد فيها فراغات بلا تفسير (لا توجد في الإنجليزية amn't). أما تركيبات اللواحق الكلامية فلا.
- Idiosyncrasy (C, D)الشذوذ (C وD)
- Affixed forms show unpredictable sound or meaning (won't, shan't). Clitic groups are regular.الصيغ ذات الزوائد تُظهر نطقًا أو معنى غير متوقع (won't وshan't). أما مجموعات اللواحق الكلامية فمنتظمة.
- Syntactic rules (E)القواعد النحوية (E)
- Syntactic operations such as agreement and inversion treat an affixed word as one unit; a host-plus-clitic group is not treated as a unit.العمليات النحوية مثل المطابقة والقلب (inversion) تعامل الكلمة ذات الزائدة وحدةً واحدة؛ أما مجموعة المضيف مع اللاحقة الكلامية فلا تُعامَل وحدةً واحدة.
- Stacking (F)التراكب (F)
- Clitics can attach to material that already contains a clitic; affixes cannot attach outside a clitic.يمكن أن تلتصق اللواحق الكلامية بمادة تحتوي أصلًا على لاحقة كلامية؛ أما الزوائد الصرفية فلا تلتصق خارج لاحقة كلامية.
Three Arabic cases and a fourth that refuses to settleثلاث حالات عربية ورابعة ترفض أن تُحسم
Arabic is where the test earns its keep, because the writing system gives you no hint. Take وَبِالْبَيْت, wa-bi-al-bayt, roughly "and in the house". The wa- is the conjunction "and" and the bi- is the preposition "with, by, in". Both are function words in the syntax, and both attach to whatever word begins the phrase: a noun here, a verb in wa-kataba, a pronoun, a particle. Lowest rung of the selectivity ladder, no paradigm. They are proclitics, clitics that lean forward onto the following word.
العربية هي المكان الذي يُثبت فيه الاختبار قيمته، لأن نظام الكتابة لا يعطيك أي تلميح. خذ وَبِالْبَيْت، wa-bi-al-bayt، أي تقريبًا «وفي البيت». الـwa- هي حرف العطف «و»، والـbi- هي حرف الجر «بـ، بواسطة، في». كلتاهما كلمة وظيفية في النحو، وكلتاهما تلتصق بأي كلمة تبدأ بها العبارة: اسم هنا، وفعل في wa-kataba، وضمير، وأداة. أدنى درجة على سلّم الانتقائية، ولا جدول تصريف. إنهما سابقتان كلاميتان proclitics، أي لواحق كلامية تستند إلى الأمام على الكلمة التالية.
Now كِتَابُهُ, kitāb-u-hu, "his book". The -u is the nominative case vowel, an inflectional ending. The -hu is the pronoun "he" in possessive position, and it is the possessor of the noun in the syntax. It attaches to nouns (kitāb-u-hu), to verbs as an object (kataba-hu, "he wrote it") and to prepositions (بِهِ, bi-hi, "with it"). Three host categories, a syntactic role of its own: an Enclitic, leaning backward onto the preceding word.
الآن كِتَابُهُ، kitāb-u-hu، «كتابه». الـ-u هي حركة الرفع، أي نهاية تصريفية. والـ-hu هي ضمير الغائب «هو» في موضع الملكية، وهي في النحو المالك للاسم (المضاف إليه). تلتصق بالأسماء (kitāb-u-hu)، وبالأفعال مفعولًا به (kataba-hu، «كتبه»)، وبحروف الجر (بِهِ، bi-hi، «به»). ثلاث فئات من المضيفات ودور نحوي خاص بها: إنها لاحقة كلامية خلفية enclitic، تستند إلى الخلف على الكلمة السابقة.
Finally كَتَبْتُ, katab-tu, "I wrote". The -tu also means something pronoun-like (first person singular), which is exactly what tempts students to call it a clitic. Apply the diagnostics. Selectivity: -tu attaches to verb stems and to nothing else. Paradigm: it is one cell of the perfective conjugation, next to -ta (you, masculine), -ti (you, feminine), -a (he) and -at (she). Syntactic role: it is subject agreement on the verb, and a separate subject pronoun can still appear alongside it. Every test says Inflection, so -tu is an inflectional affix on the Stem katab.
وأخيرًا كَتَبْتُ، katab-tu، «كتبتُ». الـ-tu تحمل هي أيضًا معنى يشبه الضمير (المتكلم المفرد)، وهذا بالضبط ما يغري الطلاب بتسميتها لاحقة كلامية. طبّق الاختبارات. الانتقائية: -tu تلتصق بجذوع الأفعال ولا شيء غيرها. جدول التصريف: هي خانة واحدة في تصريف الماضي، بجانب -ta (أنتَ) و-ti (أنتِ) و-a (هو) و-at (هي). الدور النحوي: هي مطابقة للفاعل على الفعل، ويمكن أن يظهر معها ضمير فاعل منفصل. كل الاختبارات تقول تصريف inflection، لذلك -tu زائدة تصريفية على الجذع stem katab.
| Formالصيغة | Transliterationالنقل الحرفي | Meaningالمعنى | Syntactic roleالدور النحوي | Selectivityالانتقائية | Paradigmجدول التصريف | Verdictالحكم |
|---|---|---|---|---|---|---|
| وَبِالْبَيْتوَبِالْبَيْت | wa-, bi-wa-, bi- | and; with, by, inو؛ بـ (مع، بواسطة، في) | Conjunction and preposition, function wordsحرف عطف وحرف جر، كلمتان وظيفيتان | Low: nouns, verbs, pronouns, particlesمنخفضة: أسماء وأفعال وضمائر وحروف | Noneلا يوجد | Procliticلاحقة كلامية سابقة (proclitic) |
| كِتَابُهُكِتَابُهُ | -hu-hu | his, himـه (له، إيّاه) | Pronoun, possessor or objectضمير، مالك أو مفعول به | Low: nouns, verbs, prepositionsمنخفضة: أسماء وأفعال وحروف جر | None in the host (a pronoun set, not a host paradigm)لا يوجد في المضيف (مجموعة ضمائر، لا جدول تصريف للمضيف) | Encliticلاحقة كلامية لاحقة (enclitic) |
| كَتَبْتُكَتَبْتُ | -tu-tu | I (subject agreement)أنا (مطابقة الفاعل) | Agreement marker on the verbعلامة مطابقة على الفعل | High: verb stems onlyعالية: جذوع الأفعال فقط | One cell of the perfective conjugationخانة واحدة في تصريف الماضي (perfective) | Inflectional affixزائدة صرفية تصريفية |
| الْبَيْتالْبَيْت | al-al- | theالـ (التعريف) | Definite article, function elementأداة التعريف، عنصر وظيفي | Moderate: nouns and adjectivesمتوسطة: أسماء وصفات | Definiteness system (definite, indefinite)نظام التعريف (معرفة، نكرة) | Borderlineحدّية |
The fourth row is the one the slide flags as borderline, and it is worth understanding why rather than memorizing the label. The article al- is a function element like French l', which argues clitic. But it attaches only to nouns and adjectives, and it alternates with the indefinite ending -n (bayt-un versus al-bayt-u) inside a definiteness system, which argues prefix. Arabic NLP tools split the difference. Pasha et al. (2014) list two segmentation schemes for MADAMIRA: ATB, which "tokenizes all clitics except for the definite article", and D3, in which "basically all clitics are tokenized". On the two strings this section tokenizes, the schemes differ on a single element: al-, which ATB leaves on the noun and D3 peels off, while both split the conjunction, the preposition, the future particle and the pronoun. Alotaiby et al. (2010) note that their parse-it-as-a-separate-word test "covers most of the clitics except the definite article". When the tools disagree, borderline is the honest verdict.
الصف الرابع هو الذي تصفه الشريحة بأنه حدّي، ومن المفيد أن تفهم السبب بدل أن تحفظ التسمية. أداة التعريف al- عنصر وظيفي مثل l' الفرنسية، وهذا يرجّح أنها لاحقة كلامية. لكنها تلتصق بالأسماء والصفات فقط، وتتناوب مع نهاية التنكير -n (التنوين: bayt-un مقابل al-bayt-u) داخل نظام للتعريف، وهذا يرجّح أنها سابقة صرفية. أدوات معالجة العربية تقسم الفرق. يذكر Pasha وزملاؤه (2014) مخططين للتجزئة في MADAMIRA: مخطط ATB الذي «يفصل كل اللواحق الكلامية ما عدا أداة التعريف»، ومخطط D3 الذي «تُفصل فيه كل اللواحق الكلامية تقريبًا». على السلسلتين اللتين يقطّعهما هذا القسم يختلف المخططان في عنصر واحد فقط: al-، التي يتركها ATB على الاسم ويفصلها D3، بينما يفصل كلاهما حرف العطف وحرف الجر وحرف الاستقبال والضمير. ويلاحظ Alotaiby وزملاؤه (2010) أن اختبارهم القائم على تحليلها ككلمة منفصلة «يغطي معظم اللواحق الكلامية ما عدا أداة التعريف». حين تختلف الأدوات، يكون «حدّي» هو الحكم الصادق.
For each attached element decide: is it a word in the syntax that merely leans on a host (clitic), a member of a paradigm that attaches to one stem class (affix), or a case where analyses disagree? Keys 1, 2 and 3 pick a verdict, arrows move between cards.قرّر لكل عنصر متصل: هل هو كلمة في التركيب النحوي تستند فقط إلى كلمة مضيفة (clitic)، أم عضو في نموذج صرفي يتصل بصنف واحد من الجذوع (affix)، أم حالة تختلف فيها التحليلات؟ تختار المفاتيح 1 و2 و3 الحكم، وتنقلك الأسهم بين البطاقات.
Clitic status and tokenization policy are different questionsوضع اللاحقة الكلامية وسياسة التقطيع سؤالان مختلفان
The slide ends on a practical fork: keep the clitic attached, or split it? Linguistics does not answer that Tokenization question for you, and the cleanest proof is English n't. Zwicky and Pullum devote their paper to showing that n't passes all six criteria as an inflectional affix: it attaches only to auxiliaries, it has arbitrary gaps (there is no amn't), it has idiosyncratic forms (won't, shan't), and it cannot attach to a host that already carries a clitic (I'd've is fine, I'dn't is not). Yet the Penn Treebank tokenization standard splits it, producing does n't (SLP3, section 2.8). The tokenizer made a modeling decision (a negation token is useful) that contradicts the linguistic analysis, and it was right to.
تنتهي الشريحة عند مفترق عملي: هل نُبقي اللاحقة الكلامية ملتصقة أم نفصلها؟ اللسانيات لا تجيب عن سؤال التقطيع tokenization نيابة عنك، وأوضح دليل على ذلك n't الإنجليزية. يكرّس Zwicky وPullum ورقتهما لإثبات أن n't تجتاز المعايير الستة كلها بوصفها زائدة تصريفية: تلتصق بالأفعال المساعدة فقط، ولها فجوات اعتباطية (لا توجد amn't)، ولها صيغ شاذة (won't وshan't)، ولا يمكن أن تلتصق بمضيف يحمل لاحقة كلامية أصلًا (I'd've سليمة، وI'dn't ليست كذلك). ومع ذلك فإن معيار التقطيع في Penn Treebank يفصلها، فينتج does n't (SLP3، القسم 2.8). اتخذ المقطِّع قرارًا نمذجيًا (وحدة النفي مفيدة) يناقض التحليل اللساني، وكان محقًا في ذلك.
Modern subword tokenizers make the same kind of decision by frequency rather than by rule. Jurafsky and Martin observe that the GPT-4o tokenizer segments 's off proper nouns such as Jane but keeps it inside frequent words such as she's (SLP3, section 2.4.3). For Arabic the choice is explicit and named: whitespace, ATB or D3. Try the three on the same two strings.
المقطِّعات الحديثة القائمة على الوحدات الفرعية تتخذ القرار نفسه بالتكرار لا بالقاعدة. يلاحظ Jurafsky وMartin أن مقطِّع GPT-4o يفصل 's عن أسماء العلم مثل Jane لكنه يُبقيها داخل الكلمات الشائعة مثل she's (SLP3، القسم 2.4.3). أما في العربية فالاختيار صريح ومسمّى: المسافات (whitespace)، أو ATB، أو D3. جرّب الثلاثة على السلسلتين نفسيهما.
Accent chips are clitics, the teal chip is the article, plain chips are the base word. The second word has no article, so ATB and D3 tokenize it the same way.الرقاقات باللون المميز هي اللواحق المتصلة، والرقاقة الخضراء المزرقة هي أداة التعريف، والرقاقات العادية هي الكلمة الأساس. الكلمة الثانية بلا أداة تعريف، لذلك يقسمها ATB وD3 بالطريقة نفسها.
Worked exampleمثال محلول
Whitespace, ATB or D3 on one stringالمسافات أو ATB أو D3 على سلسلة واحدة
Whitespaceالتقطيع بالمسافات
وَبِالْبَيْت is one token. Every combination of conjunction, preposition, article and noun becomes its own vocabulary Type.وَبِالْبَيْت وحدة واحدة. كل تركيبة من حرف عطف وحرف جر وأداة تعريف واسم تصبح نوعًا مستقلًا (type) في المفردات.ATBمخطط ATB
wa+ bi+ albayt: three tokens. The conjunction and preposition are split, the article stays on the noun.wa+ bi+ albayt: ثلاث وحدات. يُفصل حرف العطف وحرف الجر، وتبقى أداة التعريف على الاسم.D3مخطط D3
wa+ bi+ al+ bayt: four tokens. Every clitic is separated and the bare noun bayt is recovered.wa+ bi+ al+ bayt: أربع وحدات. تُفصل كل لاحقة كلامية ويُستعاد الاسم المجرد bayt.Same string, 1, 3 or 4 tokensالسلسلة نفسها: 1 أو 3 أو 4 وحدات
The count of tokens is a property of the policy, not of the text. Any statistic you compute on Arabic (vocabulary size, sequence length, Zipf curve) must state which policy produced it.عدد الوحدات tokens خاصية للسياسة لا للنص. أي إحصاء تحسبه على العربية (حجم المفردات، طول التسلسل، منحنى Zipf) يجب أن يذكر السياسة التي أنتجته.
Recall
State two diagnostics that separate a clitic from an affix and apply them to katab-tu and kitab-u-hu.اذكر اختبارين تشخيصيين يفصلان اللاحقة الكلامية عن الزائدة الصرفية، وطبّقهما على katab-tu وkitab-u-hu.
Recall
Why is 'it is written attached' not a valid test, and what does al- show?لماذا لا يصلح «يُكتب ملتصقًا» اختبارًا، وماذا تُظهر al-؟
Quick checkاختبار سريع
Which diagnostic shows that Arabic -tu in katab-tu is an affix rather than a clitic?ما الاختبار التشخيصي الذي يبيّن أن -tu في katab-tu زائدة صرفية وليست لاحقة كلامية؟
Take four languages and watch how each packages grammar. English and Turkish can share one meaning, "from my houses". English spends three words: from, my, house-s, four morphemes spread over three words. Turkish spends one: ev-ler-im-den, house-PL-1SG.POSS-ABL, four morphemes in one word, each suffix doing exactly one job in a fixed order. Spanish habl-o, "I speak", is a different meaning chosen to show a different trick: the single vowel -o carries person, number, tense and mood all at once, two morphemes carrying four features, and you cannot cut it into a piece for each. Mandarin wǒmen míngtiān qù Běijīng, "we tomorrow go Beijing", has almost no Inflection (the plural -men of wǒmen is about as far as it goes); word order and free words carry the grammar.
خذ أربع لغات وراقب كيف تغلّف كل واحدة منها القواعد. الإنجليزية والتركية يمكن أن تتشاركا معنى واحدًا هو «من بيوتي». الإنجليزية تنفق ثلاث كلمات: from وmy وhouse-s، أي أربعة مورفيمات morphemes موزعة على ثلاث كلمات. والتركية تنفق كلمة واحدة: ev-ler-im-den، أي house-PL-1SG.POSS-ABL، أربعة مورفيمات في كلمة واحدة، وكل لاحقة تؤدي وظيفة واحدة فقط بترتيب ثابت. أما الإسبانية habl-o، «أتكلم»، فمعنى مختلف اختير لإظهار حيلة مختلفة: الحرف الصائت الوحيد -o يحمل الشخص والعدد والزمن والصيغة دفعة واحدة، مورفيمان يحملان أربع سمات، ولا يمكنك تقطيعه إلى قطعة لكل سمة. والماندرينية wǒmen míngtiān qù Běijīng، «نحن غدًا نذهب بكين»، ليس فيها تصريف inflection تقريبًا (لاحقة الجمع -men في wǒmen هي أقصى ما تصل إليه)؛ ترتيب الكلمات والكلمات المستقلة يحملان القواعد.
Turkish, Spanish and Mandarin illustrate three of the four labels on slide 24 (the fourth, polysynthetic, comes below), and English is the analytic baseline. The labels line up on two independent axes rather than one scale. The first axis is how many morphemes a word carries, from isolating (about one) to polysynthetic (a word can hold what English needs a clause for). The second axis is how cleanly the morphemes can be cut apart, from agglutinative (one morpheme, one feature, clean seams) to fusional (one segment bundles several features). This two-axis picture goes back to Sapir's 1921 classification, which separated degree of synthesis from technique of combination (Arkadiev 2019, and SLP3 section 2.2 uses the same two ideas).
التركية والإسبانية والماندرينية توضّح ثلاثًا من التسميات الأربع في الشريحة 24 (الرابعة، متعددة التركيب، تأتي أدناه)، والإنجليزية هي خط الأساس التحليلي. هذه التسميات تتوزع على محورين مستقلين لا على مقياس واحد. المحور الأول هو عدد المورفيمات التي تحملها الكلمة، من العازلة isolating (نحو مورفيم واحد) إلى متعددة التركيب polysynthetic (قد تحمل الكلمة ما تحتاج إليه الإنجليزية جملة كاملة). والمحور الثاني هو مدى نظافة فصل المورفيمات بعضها عن بعض، من اللصقية agglutinative (مورفيم واحد لسمة واحدة، وحدود نظيفة) إلى الاندماجية fusional (مقطع واحد يجمع عدة سمات). هذه الصورة ذات المحورين تعود إلى تصنيف Sapir عام 1921، الذي فصل درجة التركيب عن تقنية الضم (Arkadiev 2019، ويستخدم SLP3 في القسم 2.2 الفكرتين نفسيهما).
| Typeالنوع | Definitionالتعريف | Example languageلغة المثال | Example formصيغة المثال | Glossالشرح الحرفي |
|---|---|---|---|---|
| Isolatingعازلة (isolating) | Little morphology; grammar carried by word order and function wordsصرف قليل؛ يحمل القواعدَ ترتيبُ الكلمات والكلماتُ الوظيفية | Mandarin Chineseالصينية الماندرينية | wǒmen míngtiān qù Běijīngwǒmen míngtiān qù Běijīng | we tomorrow go Beijingنحن غدًا نذهب بكين |
| Agglutinativeلصقية (agglutinative) | Many affixes, each with one clear function and a clean boundaryزوائد كثيرة، لكل منها وظيفة واحدة واضحة وحدّ نظيف | Turkishالتركية | ev-ler-im-denev-ler-im-den | house-PL-1SG.POSS-ABL, from my houseshouse-PL-1SG.POSS-ABL، أي: من بيوتي |
| Fusionalاندماجية (fusional) | One affix bundles several grammatical featuresزائدة واحدة تجمع عدة سمات نحوية | Spanishالإسبانية | habl-ohabl-o | speak-1SG.PRS.IND, I speakspeak-1SG.PRS.IND، أي: أتكلّم |
| Polysyntheticمتعددة التركيب (polysynthetic) | Very complex words encode sentence-like content, many morphemes per wordكلمات معقدة جدًا تُرمّز محتوى يشبه الجملة، ومورفيمات كثيرة في الكلمة | Inuktitut on the slide; Koryak in SLP3الإينكتيتوت في الشريحة؛ والكورياكية في SLP3 | t-ə-nk'e-mejŋ-ə-jetemə-nni-kt-ə-nk'e-mejŋ-ə-jetemə-nni-k | one word: I sewed a lot of yurt covers in the middle of a nightكلمة واحدة: خِطتُ كثيرًا من أغطية الخيام (yurt) في منتصف ليلة |
The Turkish and Spanish rows deserve a closer look, because the difference between them is the second axis. Bickel and Nichols (WALS chapter 21) call Turkish case and number monoexponential: -ler means plural and nothing else, and the case suffixes -in, -i, -e each mean one case. In a fusional language such as Russian, they note, there is "no element that exclusively expresses case or number": the genitive plural ending says both at once. English has the same fusion in miniature. Jurafsky and Martin point out that the -s of she reads encodes third person, singular and present tense in one segment, exactly as Spanish -o does.
صفّا التركية والإسبانية يستحقان نظرة أقرب، لأن الفرق بينهما هو المحور الثاني. يصف Bickel وNichols (WALS، الفصل 21) الحالة الإعرابية والعدد في التركية بأنهما أحاديا التعبير (monoexponential): -ler تعني الجمع ولا شيء آخر، ولواحق الحالة -in و-i و-e تعني كل منها حالة واحدة. أما في لغة اندماجية مثل الروسية، كما يلاحظان، فـ«لا يوجد عنصر يعبّر حصريًا عن الحالة أو العدد»: نهاية الجمع في حالة الإضافة (genitive plural) تقول الاثنين معًا. وفي الإنجليزية الاندماج نفسه بصورة مصغّرة. يشير Jurafsky وMartin إلى أن -s في she reads ترمّز الغائب والمفرد والمضارع في مقطع واحد، تمامًا كما تفعل -o الإسبانية.
The polysynthetic row borrows its form from a neighboring language on purpose. The slide names Inuktitut but prints no word, warning that examples vary by dialect and orthography and that the key property is morpheme density. Jurafsky and Martin's example is Koryak: t-ə-nk'e-mejŋ-ə-jetemə-nni-k, one word meaning "I sewed a lot of yurt covers in the middle of a night" (SLP3, example 2.9), and that is the form to quote for the polysynthetic type. Gupta and Boulianne (2020) describe Inuktitut as showing "a much higher degree of polysynthesis than other agglutinative languages usually considered in ASR, such as Finnish or Turkish", which is a useful reminder that polysynthetic languages are usually agglutinative too: the axes are independent.
صف متعددة التركيب يستعير صيغته من لغة مجاورة عن قصد. الشريحة تذكر الإينكتيتوت (Inuktitut) لكنها لا تطبع أي كلمة، محذّرة من أن الأمثلة تختلف باختلاف اللهجة والإملاء، وأن الخاصية الأساسية هي كثافة المورفيمات. مثال Jurafsky وMartin من لغة الكورياك (Koryak): t-ə-nk'e-mejŋ-ə-jetemə-nni-k، كلمة واحدة تعني «خِطتُ كثيرًا من أغطية الخيام في منتصف الليل» (SLP3، المثال 2.9)، وهذه هي الصيغة التي تُستشهد بها للنوع متعدد التركيب. ويصف Gupta وBoulianne (2020) الإينكتيتوت بأنها تُظهر «درجة من التركيب المتعدد أعلى بكثير من اللغات اللصقية الأخرى التي تُدرس عادة في التعرف الآلي على الكلام (ASR)، مثل الفنلندية أو التركية»، وهذا تذكير مفيد بأن اللغات متعددة التركيب لصقية عادةً أيضًا: المحوران مستقلان.
Tendencies, not boxesميول لا صناديق
The slide's mental model is that a language can be "more X" in one subsystem and "more Y" in another, and this is not a hedge. Jurafsky and Martin write that "languages can make use of different morphological systems so it would be more accurate to talk about these as general tendencies." Bickel and Nichols (WALS chapter 22) give an example inside one language: "the English past, for example, is more synthetic than the future", because walked packs tense into the verb while will walk spends a separate auxiliary. So when you classify, name the subsystem: English verbs are mostly analytic with a fusional pocket, English Derivation is productive and concatenative, and Arabic verbs are fusional while Arabic attached function elements are clitic-like.
النموذج الذهني في الشريحة هو أن اللغة يمكن أن تكون «أكثر X» في نظام فرعي و«أكثر Y» في نظام آخر، وهذا ليس تحفّظًا. يكتب Jurafsky وMartin أن «اللغات قد تستخدم أنظمة صرفية مختلفة، لذلك من الأدق الحديث عن هذه التصنيفات بوصفها ميولًا عامة». ويعطي Bickel وNichols (WALS، الفصل 22) مثالًا داخل لغة واحدة: «الماضي الإنجليزي مثلًا أكثر تركيبًا من المستقبل»، لأن walked تحشو الزمن في الفعل بينما will walk تنفق فعلًا مساعدًا منفصلًا. لذلك حين تصنّف سمِّ النظام الفرعي: الأفعال الإنجليزية تحليلية في الغالب مع جيب اندماجي، والاشتقاق derivation في الإنجليزية منتج وتسلسلي (concatenative)، والأفعال العربية اندماجية بينما العناصر الوظيفية الملتصقة في العربية أشبه باللواحق الكلامية.
Where English and Arabic sitأين تقع الإنجليزية والعربية
Slide 26 places the two languages this course cares about. English is largely analytic: auxiliaries and word order do most of the grammatical work, and inflection is limited to a handful of endings, -s, -ed, -ing. But it has fusional pockets. am, is and are each bundle person, number and tense in a form with no separable ending at all, and went replaces the expected go-ed wholesale, a case of Suppletion. Where English is genuinely productive is derivation and Compounding: un-happi-ness, laptop, and every new noun coined this year.
الشريحة 26 تحدد موقع اللغتين اللتين يهتم بهما هذا المقرر. الإنجليزية تحليلية analytic في الغالب: الأفعال المساعدة وترتيب الكلمات تؤدي معظم العمل النحوي، والتصريف محدود بحفنة من النهايات، -s و-ed و-ing. لكن فيها جيوبًا اندماجية. am وis وare تجمع كل منها الشخص والعدد والزمن في صيغة لا نهاية قابلة للفصل فيها أصلًا، وwent تحل محل go-ed المتوقعة كليًا، وهذه حالة إبدال كلي suppletion. أما ما تُنتج فيه الإنجليزية حقًا فهو الاشتقاق والتركيب compounding: un-happi-ness وlaptop وكل اسم جديد يُصاغ هذا العام.
Modern Standard Arabic sits elsewhere on both axes. Word formation follows templatic morphology, so a consonantal Root such as K-T-B is interleaved with vowel patterns, a non-concatenative mechanism that no amount of prefix and suffix cutting will recover. The verb system is largely fusional, and it is large: Obeid et al. (2020) note that this richness "leads to MSA verbs with upwards of 5,400 forms". On top of the templatic core sit the concatenative pieces from the previous concept, proclitics wa-, bi-, li- and the pronominal enclitics, which behave as clitics in NLP, plus the borderline al-. Sapir's own table, as reproduced by Arkadiev, files English as fusional and analytic and Arabic as fusional, symbolic and synthetic, which is the same placement in older words.
العربية الفصحى المعاصرة تقع في مكان آخر على المحورين. بناء الكلمات يتبع الصرف القالبي templatic morphology، فيتداخل جذر صامتي root مثل K-T-B مع أوزان صائتة، وهي آلية غير تسلسلية non-concatenative لا يستعيدها أي قدر من قطع السوابق واللواحق. نظام الفعل اندماجي إلى حد كبير، وهو ضخم: يلاحظ Obeid وزملاؤه (2020) أن هذا الغنى «يؤدي إلى أفعال فصيحة تتجاوز صيغها 5,400 صيغة». وفوق النواة القالبية تجلس القطع التسلسلية من المفهوم السابق، السوابق الكلامية proclitics wa- وbi- وli- واللواحق الكلامية الضميرية enclitics، التي تتصرف كلواحق كلامية clitics في معالجة اللغة، إضافة إلى al- الحدّية. وجدول Sapir نفسه، كما يعيد Arkadiev نشره، يصنّف الإنجليزية اندماجية وتحليلية، والعربية اندماجية ورمزية (symbolic) وتركيبية، وهو الموقع نفسه بكلمات أقدم.
| Subsystemالنظام الفرعي | Englishالإنجليزية | Arabic (MSA)العربية (الفصحى المعاصرة) |
|---|---|---|
| Word formationتكوين الكلمات | Productive derivation and compounding, concatenativeاشتقاق وتركيب منتجان، بالسلسلة (concatenative) | Templatic root-and-pattern, non-concatenativeقالبي قائم على الجذر والوزن، غير سلسلي (non-concatenative) |
| Verb inflectionتصريف الأفعال | Limited: -s, -ed, -ing; fusional pockets am/is/are, go/wentمحدود: -s و-ed و-ing؛ وجيوب اندماجية am/is/are وgo/went | Largely fusional; upwards of 5,400 forms per verbاندماجي في الغالب؛ أكثر من 5,400 صيغة للفعل الواحد |
| Attached function elementsالعناصر الوظيفية الملتصقة | 's, 'm, 've, marked by apostrophe's و'm و've، تُميَّز بالفاصلة العليا | wa-, bi-, li-, pronominal enclitics, written solidwa- وbi- وli- والضمائر المتصلة، تُكتب ملتصقة |
| Borderline elementالعنصر الحدّي | n'tn't | al-al- |
Recall
Classify Turkish, Spanish, Mandarin and Inuktitut by typology and give one form each.صنّف التركية والإسبانية والماندرينية والإينكتيتوت تصنيفًا نمطيًا وأعطِ صيغة واحدة لكل منها.
Quick checkاختبار سريع
Turkish ev-ler-im-den gives each suffix exactly one function. Which typological tendency is that?في التركية ev-ler-im-den تؤدي كل لاحقة وظيفة واحدة بالضبط. أي ميل تصنيفي هذا؟
Quick checkاختبار سريع
Which set of English forms is a fusional pocket, where one form bundles several grammatical features?أي مجموعة من الصيغ الإنجليزية تمثّل جيبًا اندماجيًا، حيث تجمع صيغة واحدة عدة سمات نحوية؟
The typology labels can be turned into a single number. Take a long text, count its morphemes, count its words, and divide. Joseph Greenberg proposed this ratio in 1960 as the Index of synthesis, "calculated as the ratio of morphemes to words in a sufficiently long text" (Arkadiev 2019). Try it on four English words: The cats walked home is the (1), cat-s (2), walk-ed (2), home (1), six morphemes over four words, an index of 1.5. Turkish ev-ler-im-den alone is 4 / 1 = 4.0, and the English equivalent from my houses is 4 / 3 ≈ 1.33.
يمكن تحويل تسميات التصنيف إلى رقم واحد. خذ نصًا طويلًا، وعُدّ مورفيماته morphemes، وعُدّ كلماته، واقسم. اقترح Joseph Greenberg هذه النسبة عام 1960 بوصفها مؤشر التركيب index of synthesis، «ويُحسب بوصفه نسبة المورفيمات إلى الكلمات في نص طويل بما يكفي» (Arkadiev 2019). جرّبه على أربع كلمات إنجليزية: The cats walked home تتكون من the (1) وcat-s (2) وwalk-ed (2) وhome (1)، أي ستة مورفيمات على أربع كلمات، فالمؤشر 1.5. والتركية ev-ler-im-den وحدها تعطي 4 / 1 = 4.0، وما يقابلها في الإنجليزية from my houses يعطي 4 / 3 ≈ 1.33.
Greenberg computed the index for eight languages, and the result is the number line on slide 27, reproduced from the same figure in Jurafsky and Martin (SLP3, figure 2.3). Vietnamese sits at the bottom with almost exactly one morpheme per word. English is close behind, which confirms the analytic label of the previous concept. Old English, Yakut, Swahili and Sanskrit cluster in the middle band, and Greenlandic (Eskimo in Greenberg's paper) stands far to the right at almost four morphemes per word. The bands drawn through this line are the ones you already know: analytic below about 2, synthetic between 2 and 3, polysynthetic above 3.
حسب Greenberg المؤشر لثماني لغات، والنتيجة هي خط الأعداد في الشريحة 27، المنقول من الشكل نفسه عند Jurafsky وMartin (SLP3، الشكل 2.3). الفيتنامية في القاع بمورفيم واحد تقريبًا لكل كلمة. والإنجليزية قريبة منها، وهذا يؤكد تسمية «تحليلية» من المفهوم السابق. والإنجليزية القديمة والياقوتية (Yakut) والسواحيلية والسنسكريتية تتجمع في الشريحة الوسطى، والغرينلاندية (الإسكيمو في ورقة Greenberg) تقف بعيدًا إلى اليمين بنحو أربعة مورفيمات لكل كلمة. والنطاقات المرسومة على هذا الخط هي التي تعرفها: تحليلية تحت نحو 2، وتركيبية بين 2 و3، ومتعددة التركيب فوق 3.
| Languageاللغة | GreenbergGreenberg | Slideالشريحة | Bandالنطاق |
|---|---|---|---|
| Vietnameseالفيتنامية | 1.061.06 | 1.11.1 | Analyticتحليلية |
| Persian (Farsi)الفارسية | 1.521.52 | 1.51.5 | Analyticتحليلية |
| Englishالإنجليزية | 1.681.68 | 1.71.7 | Analyticتحليلية |
| Anglo-Saxon (Old English)الأنجلوسكسونية (الإنجليزية القديمة) | 2.122.12 | 2.12.1 | Syntheticتركيبية |
| Yakutالياقوتية | 2.172.17 | 2.22.2 | Syntheticتركيبية |
| Swahiliالسواحيلية | 2.552.55 | 2.52.5 | Syntheticتركيبية |
| Sanskritالسنسكريتية | 2.592.59 | 2.62.6 | Syntheticتركيبية |
| Eskimo (Greenlandic)الإسكيمو (الغرينلاندية) | 3.723.72 | 3.73.7 | Polysyntheticمتعددة التركيب |
Greenberg's paper contains several more indices, and two of them explain what the synthesis number hides. Eskimo scores 2.72 on suffixation and 1.75 on inflection against English's 0.64 and 0.53; Swahili scores 1.16 on prefixation against English's 0.04. Swahili sits mid-synthetic not because it stacks suffixes but because its noun-class and agreement system lives in prefixes. Same band, different subsystem, which is the tendencies-not-boxes lesson in numbers.
ورقة Greenberg تحتوي على مؤشرات أخرى، واثنان منها يفسّران ما يخفيه رقم التركيب. تسجّل الإسكيمو 2.72 في اللواحق (suffixation) و1.75 في التصريف مقابل 0.64 و0.53 للإنجليزية؛ وتسجّل السواحيلية 1.16 في السوابق (prefixation) مقابل 0.04 للإنجليزية. السواحيلية في منتصف النطاق التركيبي لا لأنها تكدّس اللواحق، بل لأن نظام فئات الأسماء والمطابقة فيها يعيش في السوابق. النطاق نفسه والنظام الفرعي مختلف، وهذا هو درس «ميول لا صناديق» بالأرقام.
Why the index decides your tokenizerلماذا يحدد المؤشر مقطِّعك
Slide 28 closes the morphology chapter with one sentence: "word" is not universal, because morphology and clitics change what counts as a Token. The index of synthesis makes that quantitative. Every extra morpheme per word multiplies the number of distinct surface forms a Lemma can take, and every clitic that attaches multiplies it again. Since a model's Vocabulary is a set of surface forms, a language with a high index and heavy cliticization will have a higher Type-token ratio (TTR), far more types for the same number of tokens, and far more of them will be Out-of-vocabulary (OOV) at test time. Recall Heaps' law from part 02: rich morphology raises the vocabulary constant k, so a high-index language has more types at every corpus size the course fits (part 02 fits k = 73 for Arabic against 15 for English, with the Arabic βslightly lower).
تختم الشريحة 28 فصل الصرف بجملة واحدة: «الكلمة» ليست مفهومًا كونيًا، لأن الصرف واللواحق الكلامية clitics يغيّران ما يُعدّ وحدة token. ومؤشر التركيب يجعل ذلك كميًا. كل مورفيم إضافي في الكلمة يضاعف عدد الصيغ السطحية المتمايزة التي يمكن أن يتخذها المدخل المعجمي lemma، وكل لاحقة كلامية تلتصق تضاعفه مرة أخرى. وبما أن مفردات النموذج vocabulary مجموعة من الصيغ السطحية، فإن لغة ذات مؤشر مرتفع ولواحق كلامية كثيفة سيكون لها نسبة أنواع إلى وحدات type-token ratio أعلى، أي أنواع types أكثر بكثير للعدد نفسه من الوحدات، وسيكون عدد أكبر بكثير منها خارج المفردات out-of-vocabulary وقت الاختبار. تذكّر قانون Heaps Heaps' law من الجزء 02: الصرف الغني يرفع ثابت المفردات k، فتملك اللغة ذات المؤشر المرتفع أنواعًا أكثر عند كل حجم مدوّنة يقيسه المقرر (الجزء 02 يقدّر k = 73 للعربية مقابل 15 للإنجليزية، مع β للعربية أقل بقليل).
Worked exampleمثال محلول
What clitic splitting does to an Arabic vocabulary (Alotaiby et al. 2010)ماذا يفعل فصل اللواحق الكلامية بمفردات العربية (Alotaiby وزملاؤه 2010)
Whitespace tokensالوحدات المفصولة بالمسافات
A 600,000,000-word Arabic corpus has 2,207,637 unique whitespace tokens, against about 1.26 million for an equivalent English corpus, a ratio of about 1.76x.مدوّنة عربية من 600,000,000 كلمة فيها 2,207,637 وحدة فريدة مفصولة بالمسافات، مقابل نحو 1.26 million لمدوّنة إنجليزية مكافئة، أي بنسبة نحو 1.76x.Split the cliticsافصل اللواحق الكلامية
After clitic tokenization with AMIRA the corpus grows to 848,000,000 tokens (about 1.41x more), because each clitic is now a token of its own.بعد تقطيع اللواحق الكلامية باستخدام AMIRA تكبر المدوّنة إلى 848,000,000 وحدة (أكثر بنحو 1.41x)، لأن كل لاحقة كلامية أصبحت وحدة مستقلة.Count the types againعُدّ الأنواع مجددًا
Unique tokens fall to 1,665,899, a reduction of 24.54%. The six clitics below account for most of the clitic occurrences.Share of clitic occurrences (Alotaiby et al. 2010)نسبة مرات ظهور كل لاحقة كلامية (Alotaiby وزملاؤه 2010)
- al-
- 57.02%57.02%
- wa-
- 17.17%17.17%
- li-
- 6.35%6.35%
- -hu
- 5.55%5.55%
- bi-
- 4.9%4.9%
- -hā
- 4.41%4.41%
تنخفض الوحدات الفريدة إلى 1,665,899، أي بنقص قدره 24.54%. اللواحق الكلامية الست أدناه تمثّل معظم مرات ظهور اللواحق الكلامية.Share of clitic occurrences (Alotaiby et al. 2010)نسبة مرات ظهور كل لاحقة كلامية (Alotaiby وزملاؤه 2010)
- al-
- 57.02%57.02%
- wa-
- 17.17%17.17%
- li-
- 6.35%6.35%
- -hu
- 5.55%5.55%
- bi-
- 4.9%4.9%
- -hā
- 4.41%4.41%
A quarter of the vocabulary was clitic combinationsربع المفردات كان تركيبات من اللواحق الكلامية
Nothing about the language changed. A tokenization policy removed 541,738 types, which is why clitic splitting is the first preprocessing decision in Arabic NLP.لم يتغير شيء في اللغة. سياسة تقطيع أزالت 541,738 نوعًا، ولهذا يُعدّ فصل اللواحق الكلامية أول قرار في المعالجة المسبقة لمعالجة العربية.
At the polysynthetic end the effect is far larger. Schwartz et al. (2020) compare the parallel Inuktitut and English sides of the Nunavut Hansard. The numbers below come from their table 3.2.
عند الطرف متعدد التركيب يكون الأثر أكبر بكثير. يقارن Schwartz وزملاؤه (2020) الجانبين المتوازيين بالإينكتيتوت والإنجليزية من Nunavut Hansard. الأرقام أدناه من جدولهم 3.2.
| Sideالجانب | Tokens Nعدد الوحدات N | Types |V|عدد الأنواع |V| | TTRTTR |
|---|---|---|---|
| Inuktitutالإينكتيتوت | 10,869,99510,869,995 | 1,563,8831,563,883 | 0.1440.144 |
| Englishالإنجليزية | 20,367,59520,367,595 | 59,23459,234 | 0.0030.003 |
Inuktitut produces about 26 times as many types from about half as many tokens. Gupta and Boulianne (2020) report the practical consequence for speech recognition: even with a 1.3 million word vocabulary, held-out Inuktitut stories still have "more than 60% of words out-of-vocabulary". A word-level vocabulary cannot be made large enough. That is the open-vocabulary problem, and slide 28 lists three responses to it.
تُنتج الإينكتيتوت نحو 26 ضعفًا من الأنواع من نحو نصف عدد الوحدات. ويذكر Gupta وBoulianne (2020) العاقبة العملية على التعرف على الكلام: حتى مع مفردات من 1.3 million كلمة، تبقى في قصص الإينكتيتوت المحجوزة للاختبار «أكثر من 60% من الكلمات خارج المفردات». لا يمكن جعل مفردات على مستوى الكلمة كبيرة بما يكفي. هذه هي مشكلة المفردات المفتوحة (open-vocabulary)، والشريحة 28 تذكر ثلاث استجابات لها.
- Subword tokenization with BPE or WordPiece. Sennrich, Haddow and Birch (2016) motivated BPE for translation precisely because vocabularies are "typically limited to 30 000 to 50 000 words, but translation is an open-vocabulary problem", "especially for languages with productive word formation processes such as agglutination and compounding". WordPiece, from Wu et al. (2016), divides words "into a limited set of common sub-word units". Part 06 builds BPE from scratch.التقطيع إلى وحدات فرعية subword tokenization باستخدام BPE أو WordPiece. برّر Sennrich وHaddow وBirch (2016) استخدام BPE في الترجمة تحديدًا لأن المفردات «تقتصر عادةً على 30 000 إلى 50 000 كلمة، لكن الترجمة مشكلة مفردات مفتوحة»، «خصوصًا في اللغات ذات عمليات بناء الكلمات المنتجة مثل اللصق والتركيب». وWordPiece، من Wu وزملائه (2016)، تقسم الكلمات «إلى مجموعة محدودة من الوحدات الفرعية الشائعة». الجزء 06 يبني BPE من الصفر.
- Morphological segmentation when linguistic structure matters. A frequency-driven tokenizer will not reliably cut وَبِالْبَيْت at the clitic boundaries. MADAMIRA and CAMeL Tools do, using an analyzer and an explicit scheme (ATB or D3), which is what you want when a downstream task needs the bare lemma.التجزئة الصرفية morphological segmentation حين تكون البنية اللسانية مهمة. المقطِّع القائم على التكرار لن يقطع وَبِالْبَيْت عند حدود اللواحق الكلامية بشكل موثوق. أما MADAMIRA وCAMeL Tools فيفعلان، باستخدام محلل صرفي ومخطط صريح (ATB أو D3)، وهذا ما تريده حين تحتاج مهمة لاحقة إلى المدخل المعجمي المجرد (lemma).
- Careful preprocessing: case, punctuation and a stated clitic splitting policy. Jurafsky and Martin describe the pre-tokenization stage as "breaking the input at spaces and punctuation, stripping off clitics, and breaking numbers into sets of digits" (SLP3), which is the tokenization pipeline's first pass.معالجة مسبقة دقيقة: حالة الأحرف وعلامات الترقيم وسياسة معلنة لفصل اللواحق الكلامية. يصف Jurafsky وMartin مرحلة التقطيع المسبق pre-tokenization بأنها «تقسيم المدخل عند المسافات وعلامات الترقيم، ونزع اللواحق الكلامية، وتقسيم الأعداد إلى مجموعات من الأرقام» (SLP3)، وهي المرور الأول في مسار التقطيع tokenization.
The last thread to pull runs into part 07. A multilingual subword vocabulary is trained mostly on English, and Jurafsky and Martin note that such tokenizers "use most of the tokens for English" while "the other languages tend to get their words split up into shorter tokens" (SLP3, section 2.4.3). Arabic suffers twice: it has less training data in the mix, and its clitics and templatic verbs (upwards of 5,400 forms per verb) spread that data across far more surface forms, so fewer of them earn a merge. The same sentence costs more tokens in Arabic than in English, which means more compute per sentence and a shorter effective context.
الخيط الأخير يقود إلى الجزء 07. مفردات الوحدات الفرعية متعددة اللغات تُدرَّب في معظمها على الإنجليزية، ويلاحظ Jurafsky وMartin أن هذه المقطِّعات «تستخدم معظم الوحدات للإنجليزية» بينما «تميل اللغات الأخرى إلى تقسيم كلماتها إلى وحدات أقصر» (SLP3، القسم 2.4.3). تعاني العربية مرتين: بياناتها في خليط التدريب أقل، ولواحقها الكلامية وأفعالها القالبية (أكثر من 5,400 صيغة للفعل الواحد) توزّع تلك البيانات على صيغ سطحية أكثر بكثير، فيستحق عدد أقل منها عملية دمج (merge). والجملة نفسها تكلّف وحدات أكثر بالعربية منها بالإنجليزية، ما يعني حسابًا أكثر لكل جملة وسياقًا فعليًا أقصر.
Recall
Define Greenberg's index of synthesis and place English on it.عرّف مؤشر التركيب عند Greenberg وحدد موقع الإنجليزية عليه.
Recall
Name the three NLP responses on slide 28 and one tool or paper for each.اذكر الاستجابات الثلاث في معالجة اللغة الطبيعية الواردة في الشريحة 28، وأداة أو ورقة لكل منها.
Quick checkاختبار سريع
Which statement about Greenberg's 1960 morphemes-per-word index is correct?أي عبارة عن مؤشر Greenberg لعدد المورفيمات في الكلمة (1960) صحيحة؟
Quick checkاختبار سريع
Why does a shared multilingual BPE vocabulary usually split Arabic words into more pieces than English words?لماذا تقسّم مفردات BPE متعددة اللغات المشتركة الكلمات العربية عادةً إلى قطع أكثر من الكلمات الإنجليزية؟
Recapالخلاصة
If you remember nothing elseإن لم تتذكر شيئاً آخر فتذكّر هذا
- A clitic is a word in syntax and part of a word in sound; an affix is a paradigm member. Test selectivity and paradigm membership, not spelling.اللاحقة الكلامية (clitic) كلمة في النحو وجزء من كلمة في النطق؛ أما الزائدة الصرفية (affix) فعضو في جدول تصريف. اختبر الانتقائية والانتماء إلى جدول التصريف، لا طريقة الكتابة.
- wa-, bi- and -hu attach to almost any host (clitics); -tu attaches only to verbs inside the conjugation paradigm (affix); al- is borderline and treated differently by ATB and D3.wa- وbi- و-hu تلتصق بأي مضيف تقريبًا (لواحق كلامية)؛ و-tu تلتصق بالأفعال فقط داخل جدول تصريف الماضي (زائدة صرفية)؛ وal- حالة حدّية يعاملها مخطط ATB ومخطط D3 بطريقتين مختلفتين.
- English n't is an affix by Zwicky and Pullum's six criteria, yet the Penn Treebank splits it: linguistic status and tokenization policy are separate choices.n't في الإنجليزية زائدة صرفية وفق معايير Zwicky وPullum الستة، ومع ذلك يفصلها Penn Treebank: الوضع اللساني وسياسة التقطيع قراران منفصلان.
- Typology has two independent axes: morphemes per word (analytic to polysynthetic) and segmentability (agglutinative to fusional). Languages show tendencies per subsystem, not one box.للتصنيف محوران مستقلان: عدد المورفيمات في الكلمة (من التحليلي إلى متعدد التركيب) وقابلية التقطيع (من اللصقي إلى الاندماجي). اللغات تُظهر ميولًا لكل نظام فرعي، لا صندوقًا واحدًا.
- Mandarin isolating, Turkish agglutinative (ev-ler-im-den), Spanish fusional (habl-o), Inuktitut polysynthetic (one word, one clause).الصينية الماندرينية عازلة، والتركية لصقية (ev-ler-im-den)، والإسبانية اندماجية (habl-o)، والإينكتيتوت متعددة التركيب (كلمة واحدة تساوي جملة).
- English is largely analytic with fusional pockets (am/is/are, went, reads); Arabic is templatic, fusional in verbs and clitic-heavy.الإنجليزية تحليلية في الغالب مع جيوب اندماجية (am/is/are وwent وreads)؛ والعربية قالبية، اندماجية في الأفعال، وكثيرة اللواحق الكلامية.
- Greenberg 1960: Vietnamese 1.06, Persian 1.52, English 1.68, Old English 2.12, Yakut 2.17, Swahili 2.55, Sanskrit 2.59, Eskimo 3.72. Arabic is not in his sample.Greenberg 1960: الفيتنامية 1.06، الفارسية 1.52، الإنجليزية 1.68، الإنجليزية القديمة 2.12، الياقوتية 2.17، السواحيلية 2.55، السنسكريتية 2.59، الإسكيمو 3.72. العربية ليست في عيّنته.
- Rich morphology multiplies surface forms (Arabic 1.76x the English vocabulary at 600M words; Inuktitut Hansard 26x the English types), which is why BPE and WordPiece, morphological segmentation and clitic policies exist.الصرف الغني يضاعف عدد الصيغ السطحية (مفردات العربية 1.76 ضعف مفردات الإنجليزية عند 600 مليون كلمة؛ وأنواع الإينكتيتوت في Hansard تبلغ 26 ضعف أنواع الإنجليزية)، ولهذا وُجدت BPE وWordPiece والتجزئة الصرفية وسياسات اللواحق الكلامية.
Sourcesالمصادر
- Speech and Language Processing, 3rd edition draft, chapter 2: Words and TokensBookJurafsky and Martin, StanfordClitic definition, figure 2.3, tendencies quote, Koryak example, Penn Treebank splitting, GPT-4o clitic behavior, multilingual BPE biasتعريف اللاحقة الكلامية، والشكل 2.3، واقتباس الميول، ومثال الكورياكية، والفصل في Penn Treebank، وسلوك GPT-4o مع اللواحق الكلامية، وانحياز BPE متعدد اللغات(opens in a new tab)(يفتح في تبويب جديد)
- Cliticization vs. Inflection: English n'tPaperLanguage 59(3), 1983, Zwicky and PullumSix diagnostics; selectivity criterion A; n't as an inflectional affixستة اختبارات تشخيصية؛ معيار الانتقائية A؛ n't بوصفها زائدة صرفية تصريفية(opens in a new tab)(يفتح في تبويب جديد)
- A Quantitative Approach to the Morphological Typology of LanguagePaperInternational Journal of American Linguistics 26(3), 1960, GreenbergIndex of synthesis and the eight-language table, p. 193مؤشر التركيب وجدول اللغات الثماني، ص 193(opens in a new tab)(يفتح في تبويب جديد)
- Morphology in Typology: Historical Retrospect, State of the Art and ProspectsArticleOxford Research Encyclopedia of Morphology, 2019 preprint, ArkadievSapir's two axes; table 3 reproduces Greenberg's indices with two decimalsمحورا Sapir؛ والجدول 3 يعيد عرض مؤشرات Greenberg بمنزلتين عشريتين(opens in a new tab)(يفتح في تبويب جديد)
- WALS chapter 21: Exponence of Selected Inflectional FormativesDocsWorld Atlas of Language Structures, Bickel and NicholsTurkish monoexponential versus Russian polyexponential case and numberالحالة الإعرابية والعدد في التركية بعلامة لكل سمة (monoexponential) مقابل الروسية بعلامة تجمع عدة سمات (polyexponential)(opens in a new tab)(يفتح في تبويب جديد)
- WALS chapter 22: Inflectional Synthesis of the VerbDocsWorld Atlas of Language Structures, Bickel and NicholsSynthesis varies within one language: English past versus futureدرجة التركيب تختلف داخل اللغة الواحدة: الماضي الإنجليزي مقابل المستقبل(opens in a new tab)(يفتح في تبويب جديد)
- Introduction to Arabic Natural Language ProcessingBookSpringer, 2010, HabashArabic clitics, tokenization schemes and morphological analysisاللواحق الكلامية العربية، ومخططات التقطيع، والتحليل الصرفي(opens in a new tab)(يفتح في تبويب جديد)
- MADAMIRA: A Fast, Comprehensive Tool for Morphological Analysis and Disambiguation of ArabicPaperLREC 2014, Pasha et al.Table 1: ATB tokenizes all clitics except the definite article, D3 tokenizes all cliticsالجدول 1: مخطط ATB يفصل كل اللواحق الكلامية عدا أداة التعريف، ومخطط D3 يفصلها كلها(opens in a new tab)(يفتح في تبويب جديد)
- CAMeL Tools: An Open Source Python Toolkit for Arabic Natural Language ProcessingPaperLREC 2020, Obeid et al.Upwards of 5,400 forms per MSA verb; D3 tokenization exampleأكثر من 5,400 صيغة للفعل الواحد في الفصحى المعاصرة؛ مثال على التقطيع بمخطط D3(opens in a new tab)(يفتح في تبويب جديد)
- Clitics in Arabic Language: A Statistical StudyPaperPACLIC 24, 2010, Alotaiby, Foda and Alkharashi600M-word corpus, 2,207,637 to 1,665,899 unique tokens (24.54%), clitic frequency tableمدوّنة من 600 مليون كلمة، من 2,207,637 إلى 1,665,899 وحدة فريدة (24.54%)، وجدول تكرار اللواحق الكلامية(opens in a new tab)(يفتح في تبويب جديد)
- Neural Machine Translation of Rare Words with Subword UnitsPaperACL 2016, Sennrich, Haddow and BirchBPE for open-vocabulary translation, agglutination and compoundingBPE للترجمة بمفردات مفتوحة، واللصق والتركيب(opens in a new tab)(يفتح في تبويب جديد)
- Google's Neural Machine Translation System: Bridging the Gap between Human and Machine TranslationPaperarXiv, 2016, Wu et al.WordPiece sub-word unitsوحدات WordPiece الفرعية(opens in a new tab)(يفتح في تبويب جديد)
- Neural Polysynthetic Language ModellingPaperJSALT 2019 final report, arXiv 2020, Schwartz et al.Table 3.2: Nunavut Hansard token and type counts for Inuktitut and Englishالجدول 3.2: أعداد الوحدات والأنواع في Nunavut Hansard للإينكتيتوت والإنجليزية(opens in a new tab)(يفتح في تبويب جديد)
- Automatic Transcription Challenges for Inuktitut, a Low-Resource Polysynthetic LanguagePaperLREC 2020, Gupta and BoulianneMore than 60% OOV with a 1.3 million word vocabulary; Inuktitut versus Finnish and Turkishأكثر من 60% كلمات خارج المفردات (OOV) مع مفردات من 1.3 مليون كلمة؛ الإينكتيتوت مقابل الفنلندية والتركية(opens in a new tab)(يفتح في تبويب جديد)
Part 05: Corpora, Unicode and UTF-8المدونات النصية وUnicode وUTF-8
What a corpus is and why it must be documented, how Unicode names every character with a code point, and how UTF-8 packs code points into bytes that any model can consume.ما هي المدونة النصية (corpus) ولماذا يجب توثيقها، وكيف يسمي Unicode كل حرف بنقطة ترميز (code point)، وكيف يحزم UTF-8 نقاط الترميز في بايتات يستطيع أي نموذج استهلاكها.
4 concepts4 مفاهيم, ، slides 29-37الشرائح 29-37
Why this part mattersلماذا يهمّ هذا الجزء
Your research project processes Arabic, and Arabic is where text representation stops being a detail. One letter has four visual shapes, one sound has several hamza spellings, legacy keyboards emit presentation forms, and every letter costs two bytes. A tokenizer that does not know this splits words in places no linguist would recognize.
مشروعك البحثي يعالج العربية، والعربية هي المكان الذي يتوقف فيه تمثيل النص عن كونه تفصيلًا ثانويًا. فللحرف الواحد أربعة أشكال مرئية، وللصوت الواحد عدة كتابات للهمزة، ولوحات المفاتيح القديمة تُخرج أشكال العرض (presentation forms)، وكل حرف يكلّف بايتين. والمقطِّع (tokenizer) الذي لا يعرف ذلك يقسم الكلمات في مواضع لا يمكن لأي لغوي أن يتعرّف عليها.
This part builds the foundation under every tokenizer count in the rest of the course. First it asks what a corpus actually is and what you owe a reader who will trust a model trained on it. Then it descends from characters to numbers (code points), from numbers to bytes (UTF-8), and finally explains why bytes are the floor that byte-level BPE in part 7 stands on. Every corpus you use or build for the project must carry a data statement to be publishable, and every byte count you will ever see in a tokenizer log traces back to the four-row mapping table taught here.
يبني هذا الجزء الأساس الذي تقوم عليه كل أعداد المقطِّع في بقية المقرر. فهو يسأل أولًا: ما المدونة النصية فعلًا، وما الذي تدين به لقارئ سيثق بنموذج دُرِّب عليها؟ ثم ينزل من الحروف إلى الأعداد (نقاط الترميز)، ومن الأعداد إلى البايتات (UTF-8)، ويشرح أخيرًا لماذا البايتات هي الأرضية التي يقوم عليها BPE على مستوى البايت في الجزء 7. كل مدونة تستخدمها أو تبنيها للمشروع يجب أن يصحبها بيان بيانات (data statement) حتى تكون قابلة للنشر، وكل عدد بايتات ستراه يومًا في سجل مقطِّع يعود إلى جدول التحويل ذي الصفوف الأربعة الذي يُدرَّس هنا.
By the end you canفي نهاية هذا الجزء ستستطيع
- Name the variation dimensions of a corpus and list the fields of a data statement or datasheet.سمِّ أبعاد التباين في المدونة النصية (corpus)، واذكر حقول بيان البيانات (data statement) أو صحيفة البيانات (datasheet).
- Distinguish code point, glyph and encoding, and explain why saying Unicode is an encoding is wrong.ميّز بين نقطة الترميز (code point) والرسم الحرفي (glyph) والترميز (encoding)، واشرح لماذا يُعدّ القول إن Unicode ترميزٌ قولًا خاطئًا.
- Apply NFC, NFD and NFKC to precomposed and decomposed Latin and Arabic examples and say which tokenization bug each prevents.طبّق NFC وNFD وNFKC على أمثلة لاتينية وعربية مركّبة مسبقًا ومفكّكة، وبيّن أي خلل في التقطيع (tokenization) يمنعه كل منها.
- Encode any code point into UTF-8 bytes by hand using the four-row table, and decode bytes back.رمّز أي نقطة ترميز إلى بايتات UTF-8 يدويًا باستخدام الجدول ذي الصفوف الأربعة، وفُكّ ترميز البايتات عائدًا إلى نقطة الترميز.
- Explain why bytes remove the unknown-character problem and what they cost.اشرح لماذا تُزيل البايتات مشكلة الحرف المجهول، وما الثمن الذي تدفعه مقابل ذلك.
Two datasets both labelled "Arabic corpus" can be almost unrelated. One is Modern Standard Arabic newswire from 2005, written by trained journalists in a formal register. The other is Gulf-dialect tweets from 2024, full of Arabizi, emoji and code switching into English. A model trained on the first will stumble on the second, and a vocabulary learned from either will miss most of the other. Same language label, different domain, genre, time, demographics and variety.
مجموعتا بيانات تحملان كلتاهما وسم "مدونة عربية" قد لا تكاد تجمعهما صلة. الأولى أخبار بالعربية الفصحى المعاصرة من عام 2005، كتبها صحفيون مدرَّبون بأسلوب رسمي. والثانية تغريدات باللهجة الخليجية من عام 2024، مليئة بالعربيزي والرموز التعبيرية (emoji) والتبديل اللغوي إلى الإنجليزية. النموذج المدرَّب على الأولى سيتعثر في الثانية، والمفردات المتعلَّمة من أيٍّ منهما ستفوّت معظم ما في الأخرى. الوسم اللغوي نفسه، لكن المجال والنوع والزمن والخصائص الديموغرافية والتنوع اللغوي كلها مختلفة.
A Corpus is a structured collection of texts, often annotated, drawn from sources such as books, news, web crawls, social media and speech transcripts. The word "structured" matters: a corpus is a deliberate sample with metadata, not a pile of files. Jurafsky and Martin describe the dimensions along which such samples vary as language and variety (including code switching), genre, the demographics of the writer or speaker, and time. The table below adds domain, which the slides list separately, and gives an Arabic example for each.
المدونة النصية corpus مجموعة منظّمة من النصوص، كثيرًا ما تكون موسومة، مأخوذة من مصادر مثل الكتب والأخبار وعمليات الزحف على الويب ووسائل التواصل الاجتماعي ونصوص الكلام المفرَّغة. وكلمة "منظّمة" مهمة: فالمدونة عيّنة مقصودة مصحوبة ببيانات وصفية (metadata)، وليست كومة من الملفات. ويصف Jurafsky وMartin الأبعاد التي تتباين فيها هذه العينات بأنها: اللغة والتنوع اللغوي (بما في ذلك التبديل اللغوي code switching)، والنوع (genre)، والخصائص الديموغرافية للكاتب أو المتحدث، والزمن. ويضيف الجدول أدناه المجال (domain)، الذي تذكره الشرائح منفصلًا، ويعطي مثالًا عربيًا لكل بعد.
| Dimensionالبعد | Question it answersالسؤال الذي يجيب عنه | Arabic exampleمثال عربي |
|---|---|---|
| Language and varietyاللغة والتنوع اللغوي | Which language, dialect or register, and is there code switching?أي لغة أو لهجة أو مستوى لغوي (register)، وهل فيها تبديل لغوي؟ | Modern Standard Arabic newswire versus Najdi tweets, or Arabizi in Latin lettersأخبار بالعربية الفصحى المعاصرة مقابل تغريدات باللهجة النجدية، أو العربيزي بالحروف اللاتينية |
| Genreالنوع (genre) | What kind of text is it?أي نوع من النصوص هو؟ | Quranic commentary, a parliamentary transcript, a product reviewتفسير قرآني، أو محضر جلسة برلمانية، أو مراجعة منتج |
| Timeالزمن | When was it written or spoken?متى كُتب أو قيل؟ | Pre-2011 news versus post-2020 social media, where vocabulary shiftedأخبار ما قبل 2011 مقابل وسائل التواصل الاجتماعي بعد 2020، حيث تغيّرت المفردات |
| Demographicsالخصائص الديموغرافية | Who wrote or spoke it, by age, gender, region, education?من كتبه أو قاله، بحسب العمر والجنس والمنطقة والتعليم؟ | Teenage gamers in Riyadh versus retired teachers in Cairoمراهقون من محبي ألعاب الفيديو في الرياض مقابل معلمين متقاعدين في القاهرة |
| Domainالمجال (domain) | What is it about?عمّ يتحدث؟ | Medical records, legal contracts, football commentaryسجلات طبية، أو عقود قانونية، أو تعليق على مباريات كرة القدم |
Models inherit their corpusالنماذج ترث مدونتها
A language model is a compressed description of its training corpus, so it inherits the corpus's biases and blind spots. Bender and Friedman argue that systems perform best for the populations represented in their training data, so bias and exclusion arise when that data does not match the people the system is deployed for, and the fix begins with knowing what the data contains. Without that knowledge, a result on a benchmark cannot be interpreted: a 95% accuracy on 2005 newswire says nothing about 2024 tweets. To interpret any result you need the metadata below.
النموذج اللغوي وصف مضغوط لمدونة تدريبه، ولذلك يرث تحيزاتها ونقاطها العمياء. ويرى Bender وFriedman أن الأنظمة تعمل بأفضل أداء مع الفئات الممثَّلة في بيانات تدريبها، فينشأ التحيز والإقصاء حين لا تطابق تلك البيانات الناس الذين يُنشر النظام لخدمتهم، والعلاج يبدأ بمعرفة ما تحتويه البيانات. ومن دون هذه المعرفة لا يمكن تفسير نتيجة على معيار قياس (benchmark): فدقة 95% على أخبار 2005 لا تقول شيئًا عن تغريدات 2024. ولتفسير أي نتيجة تحتاج إلى البيانات الوصفية أدناه.
Metadata a corpus must carry before its results can be interpretedالبيانات الوصفية التي يجب أن تحملها المدونة قبل أن يمكن تفسير نتائجها
- Collection procedureإجراء الجمع
- How texts were sampled or crawled, and what was filtered outكيف أُخذت عينات النصوص أو زُحف عليها، وما الذي استُبعد بالتصفية
- Time periodالفترة الزمنية
- When the texts were produced, not only when they were collectedمتى أُنتجت النصوص، لا متى جُمعت فقط
- Languages and varietiesاللغات والتنوعات اللغوية
- Which languages, dialects and registers, and how much code switchingأي اللغات واللهجات والمستويات اللغوية، وما مقدار التبديل اللغوي
- Speaker or author demographicsالخصائص الديموغرافية للمتحدثين أو الكتّاب
- Age, gender, region, education and any other known attributesالعمر والجنس والمنطقة والتعليم وأي سمات أخرى معروفة
- Licensing and privacyالترخيص والخصوصية
- Who may use the data, for what, and whether consent was obtainedمن يحق له استخدام البيانات، ولأي غرض، وهل أُخذت الموافقة
Data statements and datasheetsبيان البيانات (data statement) وصحيفة البيانات (datasheet)
Two papers turned that metadata list into a standard document. Bender and Friedman (2018) proposed the data statement for NLP datasets, a short structured write-up with lettered sections from curation rationale through language variety, speaker and annotator demographics, speech situation and text characteristics. Gebru and colleagues (2021) proposed the datasheet for any machine learning dataset, borrowing the idea from electronics: a component datasheet lists operating ranges and test conditions, so a dataset should too. The slides merge the two into six fields.
حوّلت ورقتان علميتان قائمة البيانات الوصفية تلك إلى وثيقة قياسية. اقترح Bender وFriedman (2018) بيان البيانات data statement لمجموعات بيانات NLP، وهو وصف قصير منظّم بأقسام مرقّمة بالحروف تمتد من مبررات الانتقاء (curation rationale) مرورًا بالتنوع اللغوي والخصائص الديموغرافية للمتحدثين والموسِّمين، وموقف الكلام، وخصائص النص. واقترح Gebru وزملاؤه (2021) صحيفة البيانات (datasheet) لأي مجموعة بيانات في تعلم الآلة، مستعيرين الفكرة من الإلكترونيات: فصحيفة بيانات المكوِّن الإلكتروني تذكر نطاقات التشغيل وظروف الاختبار، وكذلك ينبغي لمجموعة البيانات أن تفعل. وتدمج الشرائح الاثنين في ستة حقول.
The six datasheet fields, with the matching sections in the two papersحقول صحيفة البيانات الستة، مع الأقسام المقابلة لها في الورقتين
- Motivation and intended useالدافع والاستخدام المقصود
- Why the corpus was built, by whom, funded how, and what tasks it is meant for (Gebru: motivation and uses; Bender and Friedman: A, curation rationale)لماذا بُنيت المدونة، ومن بناها، وكيف مُوّلت، وما المهام المقصودة بها (Gebru: الدافع والاستخدامات؛ Bender وFriedman: A، مبررات الانتقاء)
- Compositionالتركيب
- What the instances are, how many, which languages, varieties and demographics they cover (Gebru: composition; Bender and Friedman: B to F)ما الحالات (instances)، وكم عددها، وأي اللغات والتنوعات اللغوية والخصائص الديموغرافية تغطيها (Gebru: التركيب؛ Bender وFriedman: من B إلى F)
- Collection processعملية الجمع
- How and when the texts were gathered, by crawl, purchase or recording, and who did it (Gebru: collection process; Bender and Friedman: I, provenance)كيف ومتى جُمعت النصوص، بالزحف أو الشراء أو التسجيل، ومن قام بذلك (Gebru: عملية الجمع؛ Bender وFriedman: I، المصدر والمنشأ)
- Preprocessing and annotationالمعالجة المسبقة والتوسيم
- Cleaning, filtering, tokenization and labelling steps, and the annotators' guidelines and demographics (Gebru: preprocessing, cleaning, labeling; Bender and Friedman: D)خطوات التنظيف والتصفية والتقطيع والتوسيم، وإرشادات الموسِّمين وخصائصهم الديموغرافية (Gebru: المعالجة المسبقة والتنظيف والتوسيم؛ Bender وFriedman: D)
- Ethical considerationsالاعتبارات الأخلاقية
- Consent, privacy, sensitive content and the populations who could be harmed by a model trained on it (Gebru: uses and maintenance)الموافقة والخصوصية والمحتوى الحساس والفئات التي قد يتضرر أفرادها من نموذج مدرَّب عليها (Gebru: الاستخدامات والصيانة)
- Distribution constraintsقيود التوزيع
- License, access terms, versioning and who maintains the release (Gebru: distribution and maintenance)الترخيص وشروط الوصول وإدارة الإصدارات ومن يتولى صيانة الإصدار (Gebru: التوزيع والصيانة)
The payoff is transparency, reproducibility and responsible use. Transparency because a reader can judge whether your corpus matches their population. Reproducibility because someone else can rebuild or extend the sample. Responsible use because a datasheet states what the data must not be used for, which is the only place such a limit can live once the files are downloaded.
العائد هو الشفافية وقابلية إعادة الإنتاج والاستخدام المسؤول. الشفافية لأن القارئ يستطيع أن يحكم هل تطابق مدونتك الفئة التي يعمل عليها. وقابلية إعادة الإنتاج لأن شخصًا آخر يستطيع إعادة بناء العينة أو توسيعها. والاستخدام المسؤول لأن صحيفة البيانات تنص على ما يجب ألا تُستخدم فيه البيانات، وهي المكان الوحيد الذي يمكن أن يبقى فيه مثل هذا القيد بعد تنزيل الملفات.
Recall
Name four fields of a datasheet, and state the one-sentence reason a corpus needs one.اذكر أربعة حقول من صحيفة البيانات، واذكر في جملة واحدة لماذا تحتاج المدونة إلى صحيفة بيانات.
Quick checkاختبار سريع
Which datasheet field explains why the corpus was created?أي حقول صحيفة البيانات يشرح سبب إنشاء المدونة؟
Type the word café on two computers. On a Mac the é arrives as one unit, U+00E9. On a system with a decomposed input method it arrives as two, the plain letter U+0065 followed by a combining acute accent U+0301. On screen the two strings are pixel for pixel identical. In a program they are unequal, they have different lengths, and a tokenizer trained on one will split the other into pieces it never saw during training. Arabic has the same trap: a legacy keyboard emits the lam-alef ligature U+FEFB as one character, while a modern one emits U+0644 then U+0627.
اكتب كلمة café على حاسوبين. على جهاز Mac يصل الحرف é وحدةً واحدة، U+00E9. وعلى نظام يستخدم طريقة إدخال مفكَّكة يصل وحدتين: الحرف العادي U+0065 متبوعًا بعلامة الحدة المركِّبة (combining acute accent) U+0301. على الشاشة السلسلتان متطابقتان بكسلًا ببكسل. أما في البرنامج فهما غير متساويتين، وطولاهما مختلفان، والمقطِّع المدرَّب على إحداهما سيقسم الأخرى إلى قطع لم يرها أثناء التدريب قط. وللعربية الفخ نفسه: لوحة المفاتيح القديمة تُخرج رباط اللام ألف U+FEFB حرفًا واحدًا، بينما تُخرج الحديثة U+0644 ثم U+0627.
To reason about this you need three separate words. Unicode assigns every character a Code point, an integer between 0 and 0x10FFFF written with a U+ prefix in hexadecimal, such as U+0061 for the letter a. That gives 1,114,112 possible positions, and the standard covers Latin, Cyrillic, Arabic, Han, emoji and over 170 other scripts within them. A Glyph is the rendered shape a font draws for a code point. The Unicode core specification is explicit that an abstract character should not be confused with a glyph: the code point is the identity, the glyph is one of many possible pictures of it.
لتفكر في هذا تحتاج إلى ثلاث كلمات منفصلة. يعيّن Unicode لكل حرف نقطة ترميز code point، وهي عدد صحيح بين 0 و0x10FFFF يُكتب بالنظام الست عشري مع البادئة U+، مثل U+0061 للحرف a. وهذا يعطي 1,114,112 موضعًا ممكنًا، ويغطي المعيار ضمنها اللاتينية والسيريلية والعربية والهان (Han) والرموز التعبيرية وأكثر من 170 نظام كتابة آخر. أما الرسم الحرفي glyph فهو الشكل الذي يرسمه الخط لنقطة الترميز. والمواصفة الأساسية لـ Unicode صريحة في أن الحرف المجرد لا ينبغي أن يُخلط بالرسم الحرفي: نقطة الترميز هي الهوية، والرسم الحرفي صورة واحدة من صور كثيرة ممكنة لها.
The mapping runs many to many in both directions. One glyph can stand for several code points: the é above is one shape and two encodings, and Latin A (U+0041), Cyrillic А (U+0410) and Greek Α (U+0391) look identical in most fonts. One code point can also have several glyphs: the Arabic letter beh U+0628 is drawn as isolated, initial, medial or final form depending on its neighbours, yet the text stores a single code point and the font chooses the shape.
العلاقة متعدد إلى متعدد في الاتجاهين. فقد يمثّل رسم حرفي واحد عدة نقاط ترميز: الحرف é أعلاه شكل واحد بترميزين، والحرف اللاتيني A (U+0041) والسيريلي А (U+0410) واليوناني Α (U+0391) تبدو متطابقة في معظم الخطوط. وقد يكون لنقطة ترميز واحدة عدة رسوم حرفية: حرف الباء U+0628 يُرسم منفصلًا أو في أول الكلمة أو وسطها أو آخرها بحسب جيرانه، ومع ذلك يخزّن النص نقطة ترميز واحدة ويختار الخط الشكل.
ASCII: the first 128 code pointsASCII: أول 128 نقطة ترميز
The oldest slice of Unicode is ASCII, a 7-bit code with 128 positions defined in RFC 20, which occupies code points U+0000 to U+007F unchanged. The slide shows a fragment of the table in hexadecimal and decimal. The version below adds the binary column, because the binary reveals a fact you will use every time you write a case-folding rule.
أقدم شريحة في Unicode هي ASCII، وهو ترميز بسبع بتات فيه 128 موضعًا، معرَّف في RFC 20، ويشغل نقاط الترميز من U+0000 إلى U+007F دون تغيير. وتعرض الشريحة جزءًا من الجدول بالست عشري والعشري. والنسخة أدناه تضيف العمود الثنائي، لأن التمثيل الثنائي يكشف حقيقة ستستخدمها كلما كتبت قاعدة لتوحيد حالة الأحرف.
| Characterالحرف | Hexست عشري | Decimalعشري | Binaryثنائي |
|---|---|---|---|
| << | 3C3C | 6060 | 0011 11000011 1100 |
| == | 3D3D | 6161 | 0011 11010011 1101 |
| >> | 3E3E | 6262 | 0011 11100011 1110 |
| ?? | 3F3F | 6363 | 0011 11110011 1111 |
| @@ | 4040 | 6464 | 0100 00000100 0000 |
| AA | 4141 | 6565 | 0100 00010100 0001 |
| BB | 4242 | 6666 | 0100 00100100 0010 |
| CC | 4343 | 6767 | 0100 00110100 0011 |
| \\ | 5C5C | 9292 | 0101 11000101 1100 |
| ]] | 5D5D | 9393 | 0101 11010101 1101 |
| ^^ | 5E5E | 9494 | 0101 11100101 1110 |
| __ | 5F5F | 9595 | 0101 11110101 1111 |
| `` | 6060 | 9696 | 0110 00000110 0000 |
| aa | 6161 | 9797 | 0110 00010110 0001 |
| bb | 6262 | 9898 | 0110 00100110 0010 |
| cc | 6363 | 9999 | 0110 00110110 0011 |
Compare A at 0100 0001 with a at 0110 0001. They differ in exactly one bit, bit 5, which is worth 0x20 or 32. Every uppercase letter sits 32 positions before its lowercase partner, so Case folding in ASCII is a single OR with 0x20, which is why it is so fast and why it breaks the moment text leaves ASCII. Arabic has no case, and Greek final sigma has no simple bit rule, so Unicode defines case folding as a table lookup instead.
قارن A عند 0100 0001 بـ a عند 0110 0001. يختلفان في بت واحد بالضبط، البت 5، وقيمته 0x20 أي 32. كل حرف كبير يقع قبل نظيره الصغير بـ 32 موضعًا، لذا فإن توحيد حالة الأحرف case folding في ASCII عملية OR واحدة مع 0x20، ولهذا هو سريع جدًا، ولهذا أيضًا ينكسر لحظة خروج النص عن ASCII. فالعربية لا حالة فيها، وحرف سيغما الختامي اليوناني لا قاعدة بتية بسيطة له، ولذلك يعرّف Unicode توحيد الحالة بالبحث في جدول بدلًا من ذلك.
Normalization: one canonical spelling for each characterالتطبيع: كتابة قياسية واحدة لكل حرف
Back to café. Unicode calls U+00E9 the precomposed form and U+0065 U+0301 the decomposed form, and declares them canonically equivalent: they must be treated as the same character. Arabic has the same pair. Alef with hamza above, U+0623, decomposes canonically to bare alef U+0627 plus the combining hamza above U+0654, as the Unicode code chart records. A different, weaker relation is compatibility equivalence: the lam-alef ligature U+FEFB is compatible with U+0644 U+0627, and the ligature fi (U+FB01) with the two letters f and i. Compatibility variants look different or carry formatting, so folding them loses information.
لنعد إلى café. يسمي Unicode الشكل U+00E9 الشكل المركَّب مسبقًا (precomposed)، والشكل U+0065 U+0301 الشكل المفكَّك (decomposed)، ويعلن أنهما متكافئان قانونيًا canonically equivalent: يجب أن يُعاملا بوصفهما الحرف نفسه. وللعربية الزوج نفسه. فالألف مع همزة فوقها، U+0623، تتفكك قانونيًا إلى ألف مجردة U+0627 مع الهمزة المركِّبة فوقها U+0654، كما يسجّل جدول رموز Unicode. وثمة علاقة أخرى أضعف هي التكافؤ التوافقي (compatibility equivalence): فرباط اللام ألف U+FEFB متوافق مع U+0644 U+0627، والرباط fi (U+FB01) متوافق مع الحرفين f وi. والمتغيرات التوافقية تبدو مختلفة أو تحمل تنسيقًا، لذا فإن طيّها يُفقد معلومات.
Unicode normalization converts text to one of four standard forms defined in Unicode Standard Annex 15. The D forms decompose, the C forms decompose and then recompose, and the K forms also apply the lossy compatibility mappings. The table gives the result for é, for the lam-alef ligature and for the fi ligature, with the UTF-8 byte count of each result so you can see that normalization changes lengths, not only identities.
تطبيع Unicode (Unicode normalization) يحوّل النص إلى أحد أربعة أشكال قياسية معرَّفة في الملحق 15 من معيار Unicode (UAX 15). أشكال D تفكّك، وأشكال C تفكّك ثم تعيد التركيب، وأشكال K تطبّق أيضًا تحويلات التوافق التي تُفقد معلومات. ويعطي الجدول النتيجة للحرف é ولرباط اللام ألف ولرباط fi، مع عدد بايتات UTF-8 لكل نتيجة، لترى أن التطبيع يغيّر الأطوال، لا الهويات فقط.
| Formالشكل | Operationالعملية | é (either spelling)é (بأيٍّ من الكتابتين) | ﻻ U+FEFBﻻ U+FEFB | fi U+FB01fi U+FB01 |
|---|---|---|---|---|
| NFDNFD | Canonical decompositionتفكيك قانوني | U+0065 U+0301 (3 bytes)U+0065 U+0301 (3 بايتات) | U+FEFB (3 bytes)U+FEFB (3 بايتات) | U+FB01 (3 bytes)U+FB01 (3 بايتات) |
| NFCNFC | Canonical decomposition, then canonical compositionتفكيك قانوني، ثم تركيب قانوني | U+00E9 (2 bytes)U+00E9 (بايتان) | U+FEFB (3 bytes)U+FEFB (3 بايتات) | U+FB01 (3 bytes)U+FB01 (3 بايتات) |
| NFKDNFKD | Compatibility decompositionتفكيك توافقي | U+0065 U+0301 (3 bytes)U+0065 U+0301 (3 بايتات) | U+0644 U+0627 (4 bytes)U+0644 U+0627 (4 بايتات) | f i (2 bytes)f i (بايتان) |
| NFKCNFKC | Compatibility decomposition, then canonical compositionتفكيك توافقي، ثم تركيب قانوني | U+00E9 (2 bytes)U+00E9 (بايتان) | U+0644 U+0627 (4 bytes)U+0644 U+0627 (4 بايتات) | f i (2 bytes)f i (بايتان) |
Worked exampleمثال محلول
NFD and NFC on a Latin and an Arabic letterNFD وNFC على حرف لاتيني وحرف عربي
Decompose éفكّك é
NFD(U+00E9) looks up the canonical decomposition and returns U+0065 U+0301, base letter then combining mark. Two code points, three UTF-8 bytes.يبحث NFD(U+00E9) عن التفكيك القانوني ويعيد U+0065 U+0301، الحرف الأساسي ثم العلامة المركِّبة. نقطتا ترميز، وثلاثة بايتات في UTF-8.Recompose éأعد تركيب é
NFC(U+0065 U+0301) first decomposes (no change) and then composes the base with its mark, returning U+00E9. One code point, two bytes. Both input spellings end in the same place.يفكّك NFC(U+0065 U+0301) أولًا (دون تغيير) ثم يركّب الحرف الأساسي مع علامته، فيعيد U+00E9. نقطة ترميز واحدة، وبايتان. وكلتا كتابتي الإدخال تنتهيان في المكان نفسه.Decompose alef with hamzaفكّك الألف المهموزة
NFD(U+0623) returns U+0627 U+0654, and NFC folds that pair back to U+0623. Bare alef U+0627 stays bare under every form: it is a different letter, not a variant spelling.يعيد NFD(U+0623) التسلسل U+0627 U+0654، ويطوي NFC هذا الزوج عائدًا إلى U+0623. أما الألف المجردة U+0627 فتبقى مجردة تحت كل الأشكال: إنها حرف مختلف، لا كتابة بديلة.Fold the ligatureاطوِ الرباط
NFC(U+FEFB) is unchanged, three bytes. NFKC(U+FEFB) returns U+0644 U+0627, two letters and four bytes, because the ligature is only compatibility-equivalent.يبقى NFC(U+FEFB) دون تغيير، ثلاثة بايتات. أما NFKC(U+FEFB) فيعيد U+0644 U+0627، حرفين وأربعة بايتات، لأن الرباط متكافئ توافقيًا فقط.Resultالنتيجة
NFC is the safe default for storage, because it is lossless and shortest. NFKC is the matching form, because it also folds ligatures, fullwidth digits and superscripts, at the price of erasing them.NFC هو الخيار الافتراضي الآمن للتخزين، لأنه لا يُفقد معلومات وهو الأقصر. وNFKC هو شكل المطابقة، لأنه يطوي أيضًا الأربطة والأرقام كاملة العرض (fullwidth) والأحرف العلوية (superscripts)، على حساب محوها.
Here is the tokenizer bug normalization prevents. Suppose a BPE vocabulary is learned on NFC text, so "café" is one frequent token. Now NFD input arrives. The tokenizer sees c a f e U+0301, finds no merge that includes a lone combining mark, and emits "cafe" plus a separate accent token that no training word ever contained. Equality tests, dictionary lookups and Tokenization all fail in the same way, and all three are fixed by normalizing once, at ingestion, before anything else runs. Note that alef normalization in Arabic NLP toolkits, which folds U+0623, U+0625 and U+0622 into bare alef, is an application rule on top of Unicode, not one of the four forms.
هذا هو خلل المقطِّع الذي يمنعه التطبيع. افترض أن مفردات BPE تعلّمت على نص بصيغة NFC، فصارت "café" وحدة (token) واحدة متكررة. ثم وصل إدخال بصيغة NFD. يرى المقطِّع c a f e U+0301، ولا يجد أي دمج يتضمن علامة مركِّبة منفردة، فيُخرج "cafe" ومعها وحدة منفصلة للعلامة لم تحتوها أي كلمة في التدريب. واختبارات التساوي والبحث في القواميس والتقطيع tokenization تفشل كلها بالطريقة نفسها، وكلها تُصلَح بالتطبيع مرة واحدة عند الاستيعاب، قبل أن يعمل أي شيء آخر. ولاحظ أن تطبيع الألف في أدوات معالجة العربية، الذي يطوي U+0623 وU+0625 وU+0622 إلى ألف مجردة، قاعدة تطبيقية فوق Unicode، وليس أحد الأشكال الأربعة.
Recall
Define code point and glyph, and give one example of each direction of the many-to-many mapping.عرّف نقطة الترميز والرسم الحرفي، وأعطِ مثالًا واحدًا لكل اتجاه من اتجاهي العلاقة متعدد إلى متعدد.
Recall
Name two normalization forms and one tokenization bug that normalization prevents.سمِّ شكلين من أشكال التطبيع وخللًا واحدًا في التقطيع يمنعه التطبيع.
Quick checkاختبار سريع
Which statement correctly separates Unicode from UTF-8?أي العبارات تفصل بشكل صحيح بين Unicode وUTF-8؟
Quick checkاختبار سريع
NFC applied to the sequence U+0065 U+0301 produces what?ماذا ينتج عن تطبيق NFC على التسلسل U+0065 U+0301؟
The Arabic word كتاب has four letters, and Python's len agrees: four. Encode it and count the bytes: eight. The English word "Hi" is two and two. The difference is the whole content of this concept. Every Code point above U+007F needs more than one byte, and the rule that decides how many, and which bits go where, is small enough to learn by heart.
كلمة كتاب العربية فيها أربعة حروف، والدالة len في Python توافق: أربعة. رمّزها وعُدّ البايتات: ثمانية. أما الكلمة الإنجليزية "Hi" فاثنان واثنان. هذا الفرق هو مضمون هذا المفهوم كله. فكل نقطة ترميز فوق U+007F تحتاج إلى أكثر من بايت، والقاعدة التي تحدد كم بايتًا، وأي البتات تذهب إلى أين، صغيرة بما يكفي لتحفظها عن ظهر قلب.
UTF-8 is a variable-length encoding form that maps each Unicode scalar value (a code point that is not a surrogate) to a sequence of one to four bytes. It is defined in the Unicode core specification and, for the Internet, in RFC 3629. Code points below 0x80 take one byte, and most other characters take two, three or four. The slide's mapping table is the exact rule, reproduced here with the payload capacity of each row.
UTF-8 صيغة ترميز متغيرة الطول تحوّل كل قيمة عددية في Unicode (scalar value، أي نقطة ترميز ليست بديلًا surrogate) إلى سلسلة من بايت واحد إلى أربعة بايتات. وهي معرَّفة في المواصفة الأساسية لـ Unicode، ولأغراض الإنترنت في RFC 3629. نقاط الترميز تحت 0x80 تأخذ بايتًا واحدًا، ومعظم الحروف الأخرى تأخذ اثنين أو ثلاثة أو أربعة. وجدول التحويل في الشريحة هو القاعدة الدقيقة، وهو منقول هنا مع سعة الحمولة لكل صف.
| Rangeالنطاق | Code point bitsبتات نقطة الترميز | Payload bitsبتات الحمولة | Byte 1البايت 1 | Byte 2البايت 2 | Byte 3البايت 3 | Byte 4البايت 4 |
|---|---|---|---|---|---|---|
| U+0000 to U+007Fمن U+0000 إلى U+007F | 0xxxxxxx0xxxxxxx | 77 | 0xxxxxxx0xxxxxxx | |||
| U+0080 to U+07FFمن U+0080 إلى U+07FF | 00000yyy yyxxxxxx00000yyy yyxxxxxx | 1111 | 110yyyyy110yyyyy | 10xxxxxx10xxxxxx | ||
| U+0800 to U+FFFFمن U+0800 إلى U+FFFF | zzzzyyyy yyxxxxxxzzzzyyyy yyxxxxxx | 1616 | 1110zzzz1110zzzz | 10yyyyyy10yyyyyy | 10xxxxxx10xxxxxx | |
| U+010000 to U+10FFFFمن U+010000 إلى U+10FFFF | 000uuuuu zzzzyyyy yyxxxxxx000uuuuu zzzzyyyy yyxxxxxx | 2121 | 11110uuu11110uuu | 10uuzzzz10uuzzzz | 10yyyyyy10yyyyyy | 10xxxxxx10xxxxxx |
Read the templates as two kinds of byte. The first byte of every sequence is the lead byte, and its run of leading ones announces the length: 0 means one byte, 110 two, 1110 three and 11110 four. Every later byte is a continuation byte and starts 10, leaving six payload bits. The payload capacities are 7, 11, 16 and 21 bits, and the last is no accident: the largest code point U+10FFFF is exactly a 21-bit number, so four bytes suffice for the whole codespace.
اقرأ القوالب بوصفها نوعين من البايتات. البايت الأول في كل سلسلة هو البايت القائد lead byte، وسلسلة الآحاد في بدايته تعلن الطول: 0 تعني بايتًا واحدًا، و110 اثنين، و1110 ثلاثة، و11110 أربعة. وكل بايت بعده بايت استمرار (continuation byte) يبدأ بـ 10، فيترك ست بتات للحمولة. وسعات الحمولة هي 7 و11 و16 و21 بتًا، والأخيرة ليست مصادفة: فأكبر نقطة ترميز U+10FFFF عدد من 21 بتًا بالضبط، لذا تكفي أربعة بايتات لفضاء الترميز كله.
Worked exampleمثال محلول
Encode the Arabic letter beh, U+0628رمّز حرف الباء العربي، U+0628
Write the code point in binaryاكتب نقطة الترميز بالثنائي
0x0628 is 0000 0110 0010 1000. Its value 1576 lies between 0x80 and 0x7FF, so it takes the two-byte row with 11 payload bits.0x0628 هي 0000 0110 0010 1000. وقيمتها 1576 تقع بين 0x80 و0x7FF، لذا تأخذ صف البايتين ذا 11 بت حمولة.Take the low 11 bitsخذ أدنى 11 بتًا
Drop the five leading zeros: 11000 101000. The template is 110yyyyy 10xxxxxx, so yyyyy = 11000 and xxxxxx = 101000.احذف الأصفار الخمسة البادئة: 11000 101000. القالب هو 110yyyyy 10xxxxxx، لذا yyyyy = 11000 وxxxxxx = 101000.Fill the templatesاملأ القوالب
Byte 1 is 110 + 11000 = 11011000 = D8. Byte 2 is 10 + 101000 = 10101000 = A8.البايت 1 هو 110 + 11000 = 11011000 = D8. والبايت 2 هو 10 + 101000 = 10101000 = A8.Resultالنتيجة
U+0628 encodes as D8 A8, two bytes.تُرمَّز U+0628 إلى D8 A8، أي بايتين.
Worked exampleمثال محلول
Encode the grinning face emoji, U+1F600رمّز الرمز التعبيري للوجه المبتسم، U+1F600
Pick the rowاختر الصف
0x1F600 is above 0xFFFF, so it takes the four-byte row with 21 payload bits: 0 0001 1111 0110 0000 0000.0x1F600 أكبر من 0xFFFF، لذا تأخذ صف الأربعة بايتات ذا 21 بت حمولة: 0 0001 1111 0110 0000 0000.Split into u, z, y, x groupsقسّم البتات إلى المجموعات u وz وy وx
uuuuu = 00001, zzzz = 1111, yyyyyy = 011000, xxxxxx = 000000. The five u bits straddle two bytes: the top three go into byte 1 and the low two into byte 2, exactly as the template 11110uuu 10uuzzzz shows.uuuuu = 00001، zzzz = 1111، yyyyyy = 011000، xxxxxx = 000000. وبتات u الخمس تمتد على بايتين: الثلاث العليا تذهب إلى البايت 1 والاثنتان الدنيا إلى البايت 2، تمامًا كما يُظهر القالب 11110uuu 10uuzzzz.Fill the templatesاملأ القوالب
Byte 1: 11110 + 000 = F0. Byte 2: 10 + 01 + 1111 = 10011111 = 9F. Byte 3: 10 + 011000 = 98. Byte 4: 10 + 000000 = 80.البايت 1: 11110 + 000 = F0. البايت 2: 10 + 01 + 1111 = 10011111 = 9F. البايت 3: 10 + 011000 = 98. البايت 4: 10 + 000000 = 80.Resultالنتيجة
U+1F600 encodes as F0 9F 98 80, four bytes.تُرمَّز U+1F600 إلى F0 9F 98 80، أي أربعة بايتات.
Worked exampleمثال محلول
Encode the letter a, U+0061رمّز الحرف a، U+0061
Pick the row and copyاختر الصف وانسخ البتات
0x61 is below 0x80, so the template is 0xxxxxxx and the seven payload bits 1100001 sit under a leading zero: 01100001.0x61 أصغر من 0x80، لذا القالب هو 0xxxxxxx، وبتات الحمولة السبع 1100001 توضع بعد صفر بادئ: 01100001.Resultالنتيجة
U+0061 encodes as 61, the same number as its ASCII code. Nothing changed.تُرمَّز U+0061 إلى 61، وهو العدد نفسه في رمز ASCII. لم يتغير شيء.
| Characterالحرف | Code pointنقطة الترميز | Rangeالنطاق | Bytesالبايتات | UTF-8 (hex)UTF-8 (ست عشري) |
|---|---|---|---|---|
| aa | U+0061U+0061 | U+0000 to U+007Fمن U+0000 إلى U+007F | 11 | 6161 |
| éé | U+00E9U+00E9 | U+0080 to U+07FFمن U+0080 إلى U+07FF | 22 | C3 A9C3 A9 |
| بب | U+0628U+0628 | U+0080 to U+07FFمن U+0080 إلى U+07FF | 22 | D8 A8D8 A8 |
| €€ | U+20ACU+20AC | U+0800 to U+FFFFمن U+0800 إلى U+FFFF | 33 | E2 82 ACE2 82 AC |
| 中中 | U+4E2DU+4E2D | U+0800 to U+FFFFمن U+0800 إلى U+FFFF | 33 | E4 B8 ADE4 B8 AD |
| ﻻﻻ | U+FEFBU+FEFB | U+0800 to U+FFFFمن U+0800 إلى U+FFFF | 33 | EF BB BBEF BB BB |
| 😀😀 | U+1F600U+1F600 | U+010000 to U+10FFFFمن U+010000 إلى U+10FFFF | 44 | F0 9F 98 80F0 9F 98 80 |
Now do it live. The simulator below encodes whatever you type, one character at a time, and shows the row, the payload bits, the templates and the resulting bytes. It preloads Hi كتاب 😀: nine code points, ten UTF-16 units and sixteen bytes. The € 中 preset exercises the three-byte row, the only one with a 1110 lead byte. Switch the normalization control to NFD with the café preset, or to NFKC with the ligature preset, and watch the byte count change before a single byte is encoded.
جرّبها الآن مباشرة. المحاكي أدناه يرمّز كل ما تكتبه، حرفًا حرفًا، ويعرض الصف وبتات الحمولة والقوالب والبايتات الناتجة. وهو يُحمَّل مسبقًا بالنص Hi كتاب 😀: تسع نقاط ترميز، وعشر وحدات UTF-16، وستة عشر بايتًا. والإعداد المسبق € 中 يختبر صف الثلاثة بايتات، وهو الصف الوحيد ذو البايت القائد 1110. حوّل عنصر التحكم في التطبيع إلى NFD مع الإعداد المسبق café، أو إلى NFKC مع الإعداد المسبق للرباط، وراقب عدد البايتات يتغير قبل أن يُرمَّز بايت واحد.
- HU+0048U+0000 to U+007F
1 byte, 7 payload bits1 بايت، 7 بتات حمولةbits 100100048010010000xxxxxxx - iU+0069U+0000 to U+007F
1 byte, 7 payload bits1 بايت، 7 بتات حمولةbits 110100169011010010xxxxxxx - ␠U+0020U+0000 to U+007F
1 byte, 7 payload bits1 بايت، 7 بتات حمولةbits 010000020001000000xxxxxxx - كU+0643U+0080 to U+07FF
2 bytes, 11 payload bits2 بايتات، 11 بتات حمولةbits 11001000011D9 8311011001110yyyyy1000001110xxxxxx - تU+062AU+0080 to U+07FF
2 bytes, 11 payload bits2 بايتات، 11 بتات حمولةbits 11000101010D8 AA11011000110yyyyy1010101010xxxxxx - اU+0627U+0080 to U+07FF
2 bytes, 11 payload bits2 بايتات، 11 بتات حمولةbits 11000100111D8 A711011000110yyyyy1010011110xxxxxx - بU+0628U+0080 to U+07FF
2 bytes, 11 payload bits2 بايتات، 11 بتات حمولةbits 11000101000D8 A811011000110yyyyy1010100010xxxxxx - ␠U+0020U+0000 to U+007F
1 byte, 7 payload bits1 بايت، 7 بتات حمولةbits 010000020001000000xxxxxxx - 😀U+1F600U+010000 to U+10FFFF
4 bytes, 21 payload bits4 بايتات، 21 بتات حمولةbits 000011111011000000000F0 9F 98 801111000011110uuu1001111110uuzzzz1001100010yyyyyy1000000010xxxxxx
Dim cells are the fixed prefix bits of each byte template. Accent cells are the payload bits copied from the code point, left to right. Switch to NFD or NFKC to watch a precomposed letter or a ligature change its byte count before encoding.الخلايا الباهتة هي بتات البادئة الثابتة في قالب كل بايت. والخلايا باللون المميز هي بتات الحمولة المنسوخة من نقطة الترميز من اليسار إلى اليمين. بدّل إلى NFD أو NFKC لترى كيف يتغير عدد بايتات حرف مركّب مسبقًا أو حرف مدمج (ligature) قبل الترميز.
Decoding, and why the prefixes matterفك الترميز، ولماذا تهم البادئات
The prefixes are what make UTF-8 safe to read from any position. A decoder that sees a byte starting 0 knows it is a complete ASCII character. A byte starting 110, 1110 or 11110 announces one, two or three continuation bytes to follow. A byte starting 10 can never begin a character, so a decoder dropped into the middle of a stream steps backwards at most three bytes to find a lead byte. RFC 3629 lists this as a design property (character boundaries are easily found from anywhere in an octet stream), Jurafsky and Martin call it self-synchronizing, and it is why a corrupted byte damages one character rather than the rest of the file.
البادئات هي ما يجعل قراءة UTF-8 آمنة من أي موضع. فمفكِّك الترميز الذي يرى بايتًا يبدأ بـ 0 يعرف أنه حرف ASCII كامل. والبايت الذي يبدأ بـ 110 أو 1110 أو 11110 يعلن أن بعده بايت استمرار واحدًا أو اثنين أو ثلاثة. أما البايت الذي يبدأ بـ 10 فلا يمكن أن يبدأ حرفًا أبدًا، لذا فإن المفكِّك الذي يُلقى في منتصف تدفق يرجع إلى الخلف ثلاثة بايتات على الأكثر ليجد بايتًا قائدًا. ويذكر RFC 3629 هذا بوصفه خاصية تصميمية (حدود الحروف يسهل إيجادها من أي مكان في تدفق الثُّمانيات)، ويسميها Jurafsky وMartin المزامنة الذاتية (self-synchronizing)، وهي سبب أن البايت التالف يُفسد حرفًا واحدًا لا بقية الملف.
Worked exampleمثال محلول
Decode D8 A8 back to a code pointفكّ ترميز D8 A8 عائدًا إلى نقطة ترميز
Read the lead byteاقرأ البايت القائد
D8 is 11011000. It starts 110, so expect exactly one continuation byte and keep the five bits after the prefix: 11000.D8 هو 11011000. يبدأ بـ 110، لذا توقّع بايت استمرار واحدًا بالضبط، واحتفظ بالبتات الخمس التي بعد البادئة: 11000.Read the continuation byteاقرأ بايت الاستمرار
A8 is 10101000. It starts 10 as required, so keep the six bits after the prefix: 101000.A8 هو 10101000. يبدأ بـ 10 كما هو مطلوب، لذا احتفظ بالبتات الست التي بعد البادئة: 101000.Concatenateاربط البتات
11000 + 101000 = 11000101000 = 0x628.اربط الجزأين: 11000 + 101000 = 11000101000 = 0x628.Resultالنتيجة
U+0628, the letter beh. Had the second byte started with anything other than 10, the decoder would report an error at that exact position.U+0628، حرف الباء. ولو بدأ البايت الثاني بأي شيء غير 10 لأبلغ المفكِّك عن خطأ في ذلك الموضع بالضبط.
Three consequences follow from the table and are worth stating explicitly. First, backward compatibility with ASCII: every code point below 0x80 becomes the single byte with the same value, so an ASCII file is already a valid UTF-8 file and a UTF-8 file that happens to contain only ASCII is byte for byte an ASCII file. Second, bytes below 0x80 never appear inside a multibyte sequence, so a program that searches for a space or a newline byte will never find one in the middle of an Arabic letter. Third, some byte values are simply impossible: C0, C1 and F5 to FF never occur in valid UTF-8, because they would encode overlong sequences or code points past U+10FFFF (RFC 3629, section 1, with the syntax that rules them out in section 4).
ثلاث نتائج تترتب على الجدول وتستحق أن تُذكر صراحة. أولًا، التوافق مع ASCII: كل نقطة ترميز تحت 0x80 تصبح بايتًا واحدًا بالقيمة نفسها، لذا فإن ملف ASCII هو أصلًا ملف UTF-8 صالح، وملف UTF-8 لا يحتوي إلا ASCII هو ملف ASCII بايتًا ببايت. ثانيًا، البايتات تحت 0x80 لا تظهر أبدًا داخل سلسلة متعددة البايتات، لذا فإن البرنامج الذي يبحث عن بايت مسافة أو سطر جديد لن يجده أبدًا في منتصف حرف عربي. ثالثًا، بعض قيم البايتات مستحيلة ببساطة: C0 وC1 ومن F5 إلى FF لا تظهر أبدًا في UTF-8 صالح، لأنها سترمّز سلاسل مطوّلة (overlong) أو نقاط ترميز بعد U+10FFFF (RFC 3629، القسم 1، مع الصياغة التي تستبعدها في القسم 4).
Recall
How many UTF-8 bytes do U+0628, U+00E9, U+4E2D and U+1F600 need, and why?كم بايتًا في UTF-8 تحتاج U+0628 وU+00E9 وU+4E2D وU+1F600، ولماذا؟
Recall
Encode ñ, U+00F1, by hand.رمّز ñ، U+00F1، يدويًا.
Recall
Why is UTF-8 backward compatible with ASCII, and how does a decoder find where a character starts?لماذا يتوافق UTF-8 مع ASCII، وكيف يجد مفكِّك الترميز بداية الحرف؟
Quick checkاختبار سريع
How many bytes does UTF-8 use for the Arabic letter beh, U+0628?كم بايتًا يستخدم UTF-8 لحرف الباء العربي، U+0628؟
Quick checkاختبار سريع
A decoder reads a byte whose top bits are 10. What does it conclude?يقرأ مفكِّك الترميز بايتًا بتاته العليا 10. ماذا يستنتج؟
A tokenizer trained with a character vocabulary in 2020 meets the melting face emoji 🫠, added as U+1FAE0 in Unicode 14 the following year. It has never seen the character, so it emits the unknown token. The same happens with an Arabizi spelling like "ktaab" typed into a word-level vocabulary, or any typo, any new script, any rare Han character. Now imagine the base symbols were bytes instead. Every UTF-8 byte is one of exactly 256 values, all of them already in the vocabulary, so there is nothing left to be unknown.
مقطِّع دُرِّب بمفردات من الحروف عام 2020 يصادف الرمز التعبيري للوجه الذائب 🫠، الذي أُضيف بوصفه U+1FAE0 في Unicode 14 في العام التالي. لم يرَ هذا الحرف قط، فيُخرج وحدة المجهول (unknown token). ويحدث الشيء نفسه مع كتابة بالعربيزي مثل "ktaab" تُكتب في مفردات على مستوى الكلمة، أو مع أي خطأ إملائي، أو أي نظام كتابة جديد، أو أي حرف هان نادر. والآن تخيّل أن الرموز الأساسية كانت بايتات بدلًا من ذلك. كل بايت في UTF-8 هو واحد من 256 قيمة بالضبط، وكلها موجودة أصلًا في المفردات، فلا يبقى شيء يمكن أن يكون مجهولًا.
That is Byte-level tokenization: treat the UTF-8 bytes of the text, not its characters, as the atoms. Radford and colleagues motivated it in the GPT-2 paper with the numbers. A Code point base vocabulary would start at over 130,000 symbols before a single merge (about 160,000 in Unicode 17), while a byte-level base needs only 256. Jurafsky and Martin draw the consequence: because there are only 256 possible byte values, there will be no unknown tokens, and the <UNK> symbol becomes unnecessary. Arbitrary scripts, emoji and typos all decompose into bytes the model has seen.
هذا هو التقطيع على مستوى البايت byte-level tokenization: عامِل بايتات UTF-8 للنص، لا حروفه، بوصفها الذرّات. وقد برّره Radford وزملاؤه في ورقة GPT-2 بالأرقام. فمفردات أساسية مبنية على نقاط الترميز ستبدأ بأكثر من 130,000 رمز قبل أي دمج (نحو 160,000 في Unicode 17)، بينما تحتاج القاعدة على مستوى البايت إلى 256 فقط. ويستخلص Jurafsky وMartin النتيجة: لأنه لا توجد إلا 256 قيمة ممكنة للبايت، فلن تكون هناك وحدات مجهولة unknown، ويصبح الرمز <UNK> غير ضروري. فأنظمة الكتابة أيًّا كانت والرموز التعبيرية والأخطاء الإملائية تتفكك كلها إلى بايتات رآها النموذج.
| Propertyالخاصية | Character vocabularyمفردات الحروف | Byte vocabularyمفردات البايتات |
|---|---|---|
| Base symbolsالرموز الأساسية | About 160,000 assigned characters (over 130,000 when GPT-2 was written)نحو 160,000 حرف مُعيَّن (أكثر من 130,000 وقت كتابة ورقة GPT-2) | Exactly 256 byte values256 قيمة بايت بالضبط |
| Unknown input possibleهل يمكن أن يكون الإدخال مجهولًا | Yes, any unseen characterنعم، أي حرف لم يُرَ من قبل | No, every byte is in the baseلا، كل بايت موجود في القاعدة |
| Base units for كتابالوحدات الأساسية لكلمة كتاب | 4 characters4 حروف | 8 bytes8 بايتات |
| Interpretability of a base unitقابلية تفسير الوحدة الأساسية | A letter you can readحرف يمكنك قراءته | Half of an Arabic letterنصف حرف عربي |
| Structureالبنية | Given by the scriptيعطيها نظام الكتابة | Recovered by learned mergesتستعيدها الدمجات المتعلَّمة (merges) |
The price is structure. Bytes do not know where a character ends. The word كتاب becomes eight opaque symbols, and the letter ب is D8 A8, two units that mean nothing on their own. A sentence of Arabic is roughly twice as many base units as Latin text of the same length, which the simulator's كتاب preset shows as 4 characters against 8 bytes. Left alone, a byte model would spend its capacity relearning the UTF-8 table. So bytes are never used alone: they are combined with learned merges that glue frequent byte sequences back into characters, then into subwords. Jurafsky and Martin note that BPE over bytes rediscovers the two- and three-byte UTF-8 sequences early, and that it can also learn invalid sequences straddling a character boundary, which implementations filter out. GPT-2 adds a rule that prevents merges across character categories, because naive byte merges were sub-optimal.
الثمن هو البنية. فالبايتات لا تعرف أين ينتهي الحرف. كلمة كتاب تصبح ثمانية رموز معتمة، وحرف ب هو D8 A8، وحدتان لا تعنيان شيئًا بمفردهما. والجملة العربية تساوي تقريبًا ضعف عدد الوحدات الأساسية لنص لاتيني بالطول نفسه، وهو ما يُظهره الإعداد المسبق كتاب في المحاكي: 4 حروف مقابل 8 بايتات. ولو تُرك نموذج البايتات وحده لأنفق سعته في إعادة تعلّم جدول UTF-8. لذا لا تُستخدم البايتات وحدها أبدًا: بل تُجمع مع دمجات merges متعلَّمة تلصق سلاسل البايتات المتكررة لتعيدها حروفًا، ثم وحدات دون الكلمة subwords. ويلاحظ Jurafsky وMartin أن BPE على البايتات يعيد اكتشاف سلاسل UTF-8 ذات البايتين والثلاثة بايتات مبكرًا، وأنه قد يتعلم أيضًا سلاسل غير صالحة تمتد عبر حدود الحرف، وتقوم التطبيقات بتصفيتها. ويضيف GPT-2 قاعدة تمنع الدمج عبر فئات الحروف، لأن دمج البايتات الساذج كان دون المستوى الأمثل.
Recall
What does Python return for len of the string كتاب, and for len of its UTF-8 encoding? Which number does a byte-level tokenizer start from?ماذا يعيد Python للدالة len على السلسلة كتاب، ولـ len على ترميزها بـ UTF-8؟ ومن أي الرقمين يبدأ المقطِّع على مستوى البايت؟
Quick checkاختبار سريع
How large is the base vocabulary of a byte-level tokenizer before any merges?ما حجم المفردات الأساسية للمقطِّع على مستوى البايت قبل أي دمج؟
Recapالخلاصة
If you remember nothing elseإن لم تتذكر شيئاً آخر فتذكّر هذا
- A corpus is a situated sample that varies by domain, genre, time, demographics and variety. Models inherit its limits, so document it with a data statement or datasheet.المدونة النصية عيّنة لها سياقها، تتباين بحسب المجال والنوع والزمن والخصائص الديموغرافية والتنوع اللغوي. والنماذج ترث حدودها، لذا وثّقها ببيان بيانات أو صحيفة بيانات.
- Datasheet fields: motivation and intended use, composition, collection process, preprocessing and annotation, ethical considerations, distribution constraints.حقول صحيفة البيانات: الدافع والاستخدام المقصود، والتركيب، وعملية الجمع، والمعالجة المسبقة والتوسيم، والاعتبارات الأخلاقية، وقيود التوزيع.
- A code point is an integer from U+0000 to U+10FFFF. A glyph is the drawn shape. The two map many to many.نقطة الترميز عدد صحيح من U+0000 إلى U+10FFFF. والرسم الحرفي (glyph) هو الشكل المرسوم. والعلاقة بينهما متعدد إلى متعدد.
- ASCII is the first 128 code points, and upper and lower case letters differ by exactly 0x20.ASCII هو أول 128 نقطة ترميز، والحرف الكبير يختلف عن الصغير بمقدار 0x20 بالضبط.
- NFC and NFD make é and e plus U+0301 compare and tokenize alike. Only NFKC and NFKD also fold the ligature ﻻ into ل plus ا.يجعل NFC وNFD الحرف é والتسلسل e مع U+0301 متطابقين في المقارنة والتقطيع. أما NFKC وNFKD فوحدهما يفكّان أيضًا الرباط ﻻ إلى ل مع ا.
- UTF-8 uses 1, 2, 3 or 4 bytes with lead patterns 0, 110, 1110, 11110 and continuation bytes 10xxxxxx. Payloads hold 7, 11, 16 and 21 bits.يستخدم UTF-8 بايتًا واحدًا أو 2 أو 3 أو 4 بايتات، بأنماط بايت قائد 0 و110 و1110 و11110، وبايتات استمرار على شكل 10xxxxxx. وتسع الحمولات 7 و11 و16 و21 بتًا.
- U+0628 is D8 A8, U+00E9 is C3 A9, U+4E2D is E4 B8 AD, U+1F600 is F0 9F 98 80, and a is 61.U+0628 هو D8 A8، وU+00E9 هو C3 A9، وU+4E2D هو E4 B8 AD، وU+1F600 هو F0 9F 98 80، والحرف a هو 61.
- String length counts code points, not bytes: كتاب is 4 code points and 8 bytes.طول السلسلة يعدّ نقاط الترميز لا البايتات: كلمة كتاب 4 نقاط ترميز و8 بايتات.
- Bytes give a 256-symbol base with no unknown character. Learned merges restore the structure that bytes lose.تعطي البايتات قاعدة من 256 رمزًا بلا حرف مجهول. والدمجات المتعلَّمة (merges) تعيد البنية التي تفقدها البايتات.
Sourcesالمصادر
- Speech and Language Processing, chapter 2: Words and TokensBookJurafsky and Martin, 3rd edition draftSections 2.3 on code points, UTF-8 and its self-synchronizing property, 2.4.3 on byte-level BPE, 2.5 on corpora and datasheetsالقسم 2.3 عن نقاط الترميز وUTF-8 وخاصية المزامنة الذاتية فيه، والقسم 2.4.3 عن BPE على مستوى البايت، والقسم 2.5 عن المدونات النصية وصحف البيانات(opens in a new tab)(يفتح في تبويب جديد)
- RFC 3629: UTF-8, a transformation format of ISO 10646RFCIETFByte templates (section 3); section 1 lists ASCII compatibility, character boundaries findable from any position, and the bytes C0, C1, F5 to FF never appearingقوالب البايتات (القسم 3)؛ ويذكر القسم 1 التوافق مع ASCII، وإمكان إيجاد حدود الحروف من أي موضع، وأن البايتات C0 وC1 ومن F5 إلى FF لا تظهر أبدًا(opens in a new tab)(يفتح في تبويب جديد)
- The Unicode Standard, Version 17.0, chapter 3: ConformanceDocsUnicode ConsortiumAbstract character versus glyph (D7), codespace and code point (D9, D10), UTF-8 encoding form (D92)الحرف المجرد مقابل الرسم الحرفي (D7)، وفضاء الترميز ونقطة الترميز (D9 وD10)، وصيغة الترميز UTF-8 (D92)(opens in a new tab)(يفتح في تبويب جديد)
- Unicode Standard Annex 15: Unicode Normalization FormsDocsUnicode ConsortiumTable 1 defines NFD, NFC, NFKD and NFKCالجدول 1 يعرّف NFD وNFC وNFKD وNFKC(opens in a new tab)(يفتح في تبويب جديد)
- FAQ: UTF-8, UTF-16, UTF-32 and BOMDocsUnicode ConsortiumUnicode versus encoding forms, the 21-bit codespace, UTF-16 in Java and WindowsUnicode مقابل صيغ الترميز، وفضاء الترميز ذو 21 بتًا، وUTF-16 في Java وWindows(opens in a new tab)(يفتح في تبويب جديد)
- Arabic code chart, U+0600 to U+06FFDocsUnicode ConsortiumU+0623 decomposes canonically to U+0627 U+0654; U+0628 ARABIC LETTER BEHU+0623 تتفكك قانونيًا إلى U+0627 U+0654؛ وU+0628 هي حرف الباء العربي (ARABIC LETTER BEH)(opens in a new tab)(يفتح في تبويب جديد)
- Arabic Presentation Forms-B code chart, U+FE70 to U+FEFFDocsUnicode ConsortiumU+FEFB is compatibility-equivalent to U+0644 U+0627U+FEFB متكافئة توافقيًا مع U+0644 U+0627(opens in a new tab)(يفتح في تبويب جديد)
- RFC 20: ASCII format for network interchangeRFCIETF7-bit code, 0x5B is [, 0x5D is ], A is 0x41 and a is 0x61ترميز بسبع بتات، و0x5B هو [، و0x5D هو ]، وA هو 0x41، وa هو 0x61(opens in a new tab)(يفتح في تبويب جديد)
- Unicode HOWTODocsPython documentationlen counts code points; encode returns bytes; unicodedata.normalizeالدالة len تعدّ نقاط الترميز؛ والدالة encode تعيد بايتات؛ والدالة unicodedata.normalize(opens in a new tab)(يفتح في تبويب جديد)
- Data Statements for Natural Language Processing: Toward Mitigating System Bias and Enabling Better SciencePaperTransactions of the ACL, Bender and Friedman, 2018Schema sections A to I; systems work best for the populations represented in their training dataأقسام المخطط من A إلى I؛ والأنظمة تعمل بأفضل أداء مع الفئات الممثَّلة في بيانات تدريبها(opens in a new tab)(يفتح في تبويب جديد)
- Datasheets for DatasetsPaperCommunications of the ACM, Gebru et al., December 2021Motivation, composition, collection, preprocessing, uses, distribution, maintenance; the electronics datasheet analogyالدافع، والتركيب، والجمع، والمعالجة المسبقة، والاستخدامات، والتوزيع، والصيانة؛ وتشبيه صحيفة بيانات المكوّنات الإلكترونية(opens in a new tab)(يفتح في تبويب جديد)
- Language Models are Unsupervised Multitask LearnersPaperOpenAI, Radford et al., 2019Section 2.2: over 130,000 code point symbols versus a 256-symbol byte base; merges blocked across character categoriesالقسم 2.2: أكثر من 130,000 رمز من نقاط الترميز مقابل قاعدة بايتات من 256 رمزًا؛ ومنع الدمج عبر فئات الحروف(opens in a new tab)(يفتح في تبويب جديد)
- Usage statistics of UTF-8 for websitesArticleW3TechsUTF-8 used by 99.1% of websites with a known encoding, September 2026يستخدم UTF-8 في 99.1% من المواقع المعروف ترميزها، سبتمبر 2026(opens in a new tab)(يفتح في تبويب جديد)
Part 06: Tokenization units and byte-pair encodingوحدات التقسيم وترميز أزواج البايتات (BPE)
Words, characters or subwords as the unit of text, the tradeoffs among them, and the BPE algorithm that learns a subword vocabulary by merging frequent pairs, traced by hand on a toy corpus.الكلمات أو الحروف أو الوحدات الجزئية (subwords) كوحدة للنص، والموازنات بينها، وخوارزمية BPE التي تتعلم مفردات جزئية بدمج الأزواج المتكررة، مع تتبعها يدويا على مدونة صغيرة.
5 concepts5 مفاهيم, ، slides 38-48الشرائح 38-48
Why this part mattersلماذا يهمّ هذا الجزء
Every model you train or evaluate in this course fixes a tokenizer before it sees a single example. That choice decides the vocabulary size, the sequence length, the cost per token, and whether an Arabic clitic such as wa- or the article al- ends up as a clean unit or as a fragment glued to whatever follows it.
This part first asks what a good tokenization is trying to achieve, then compares the three obvious units (words, characters, subwords) against those goals. The second half is the byte-pair encoding algorithm that modern language models use to learn subwords from data: how it trains, a full hand trace on the toy corpus from the slides with every pair count shown, and how the learned merges are replayed on new text. Tracing BPE by hand is a standard exam exercise, and reading a merge list is what you will do when you debug a Hugging Face tokenizer on Arabic text in your research.
كل نموذج تدرّبه أو تقيّمه في هذا المقرر يثبّت مقطِّعًا (tokenizer) قبل أن يرى مثالًا واحدًا. هذا الاختيار يحدد حجم المفردات، وطول التسلسل، وتكلفة كل وحدة (token)، وما إذا كانت لاحقة عربية مثل wa- (و) أو أداة التعريف al- (الـ) ستنتهي وحدة نظيفة مستقلة أم قطعة ملتصقة بما يليها.
يسأل هذا الجزء أولًا: ما الذي يحاول التقطيع الجيد تحقيقه؟ ثم يقارن الوحدات الثلاث البديهية (الكلمات والحروف والوحدات الفرعية) بهذه الأهداف. النصف الثاني مخصص لخوارزم byte-pair encoding الذي تستخدمه النماذج اللغوية الحديثة لتعلّم الوحدات الفرعية من البيانات: كيف يتدرّب، وتتبّع يدوي كامل على المدوّنة الصغيرة من الشرائح مع إظهار عدد كل زوج، وكيف تُعاد الدمجات المُتعلَّمة على نص جديد. تتبّع BPE يدويًا تمرين امتحاني معتاد، وقراءة قائمة الدمجات هي ما ستفعله عندما تصحّح مقطِّع Hugging Face على نص عربي في بحثك.
By the end you canفي نهاية هذا الجزء ستستطيع
- Name the four properties a tokenization balances and place words, characters and subwords on the coverage versus compactness spectrum.تسمية الخصائص الأربع التي يوازن بينها التقطيع (tokenization)، ووضع الكلمات والحروف والوحدات الفرعية (subwords) على طيف التغطية مقابل الإيجاز.
- Write the BPE training pseudocode from memory and explain the role of k.كتابة الشيفرة الزائفة (pseudocode) لتدريب BPE من الذاكرة، وشرح دور k.
- Run BPE by hand for k merges on a small corpus, showing pair counts, stating the tie rule, and listing the vocabulary and final corpus.تنفيذ BPE يدويًا لعدد k من الدمجات على مدوّنة صغيرة، مع إظهار عدّ الأزواج، وذكر قاعدة كسر التعادل، وسرد المفردات والمدوّنة النهائية.
- Encode an unseen word by replaying the merge list in order and explain why order matters.ترميز كلمة لم تظهر في التدريب بإعادة تطبيق قائمة الدمجات بترتيبها، وشرح لماذا يهمّ الترتيب.
- Explain how a leading space marker versus an end-of-word marker changes the learned units.شرح كيف يغيّر وسم المسافة البادئ، مقارنةً بوسم نهاية الكلمة، الوحداتِ التي يتعلمها الخوارزم.
Take the six-word string that the rest of this part will keep returning to: set new new renew reset renew. Split it at spaces and you have one token per word. Split it into characters, keeping a marker for each space, and you have one token per character. Split it with the subword vocabulary this part will learn and you get something in between.
خذ السلسلة ذات الكلمات الست التي سيعود إليها هذا الجزء مرارًا: set new new renew reset renew. قسّمها عند المسافات فتحصل على وحدة لكل كلمة. قسّمها إلى حروف مع الإبقاء على وسم لكل مسافة فتحصل على وحدة لكل حرف. قسّمها بمفردات الوحدات الفرعية التي سيتعلمها هذا الجزء فتحصل على شيء بينهما.
| Splitالتقسيم | Tokens Nعدد الوحدات N | Distinct typesالأنواع المميزة | Vocabulary |V|المفردات |V| |
|---|---|---|---|
| Wordsكلمات | 66 | 44 | 44 |
| Characters with markerحروف مع وسم المسافة | 2929 | 77 | 77 |
| BPE, k = 4BPE، k = 4 | 1515 | 66 | 1111 |
Same text, three very different values of N and |V|. That is the whole subject of Tokenization in one example. Tokenization converts raw text into a sequence of tokens, the units that a model or a pipeline operates on, and the choice of unit fixes three things at once: the Vocabulary the model must learn embeddings for, the length of every input, and what the model can represent at all. Earlier parts of this lecture treated the unit as given and asked what a word is. This part reverses the question: given that we may pick the unit, what should we optimise for?
النص نفسه، وثلاث قيم مختلفة جدًا لـ N و|V|. هذا هو موضوع tokenization كله في مثال واحد. يحوّل التقطيع النص الخام إلى تسلسل من tokens، وهي الوحدات التي يعمل عليها النموذج أو خط المعالجة، واختيار الوحدة يثبّت ثلاثة أشياء دفعة واحدة: المفردات (vocabulary) التي يجب أن يتعلم النموذج تضمينات (embeddings) لها، وطول كل مدخل، وما يستطيع النموذج تمثيله أصلًا. الأجزاء السابقة من هذه المحاضرة عاملت الوحدة على أنها معطاة وسألت: ما الكلمة؟ هذا الجزء يعكس السؤال: إذا كان لنا أن نختار الوحدة، فما الذي ينبغي أن نحسّنه؟
Four properties a tokenization balancesأربع خصائص يوازن بينها التقطيع
- Coverageالتغطية (Coverage)
- How rarely new text contains a token the vocabulary cannot represent. Characters and bytes win outright; words lose.مدى ندرة احتواء نص جديد على وحدة لا تستطيع المفردات تمثيلها. الحروف والبايتات تفوز بلا منازع، والكلمات تخسر.
- Compactnessالإيجاز (Compactness)
- How short the token sequence is for a given text. Words win; characters lose by a factor of four to six.مدى قِصَر تسلسل الوحدات لنص معيّن. الكلمات تفوز، والحروف تخسر بعامل يتراوح بين أربعة وستة.
- Meaningfulnessالدلالة (Meaningfulness)
- How well one token lines up with one unit of meaning. Words win; characters carry almost none on their own.مدى توافق الوحدة الواحدة مع وحدة معنى واحدة. الكلمات تفوز، والحروف لا تحمل بمفردها أي معنى تقريبًا.
- Cross-lingual applicabilityالصلاحية عبر اللغات (Cross-lingual applicability)
- Whether the same scheme works for Arabic, Chinese and English alike. Data-driven subwords and bytes win; whitespace words fail for scripts without spaces.هل يعمل المخطط نفسه مع العربية والصينية والإنجليزية على حد سواء. الوحدات الفرعية المدفوعة بالبيانات والبايتات تفوز، والكلمات المقسومة عند المسافات تفشل مع الكتابات التي لا مسافات فيها.
The four criteria pull in different directions, which is why no single unit wins. Coverage asks how often new text contains something the vocabulary cannot represent, the out-of-vocabulary problem from the Zipf and Heaps part: with word tokens the answer is always, because Heaps' law says the word vocabulary never closes. Compactness asks how many tokens the model must process; every token costs attention, memory and, in a hosted API, money. Meaningfulness asks whether one token corresponds to one unit of meaning, which makes downstream tasks such as tagging and parsing easier. Cross-lingual applicability asks whether the same scheme works for Chinese, which has no spaces, and for Arabic, whose clitics glue several words into one whitespace token.
المعايير الأربعة تشدّ في اتجاهات مختلفة، ولهذا لا تفوز وحدة واحدة. التغطية (coverage) تسأل: كم مرة يحتوي نص جديد على شيء لا تستطيع المفردات تمثيله؟ وهذه مشكلة out-of-vocabulary من جزء Zipf وHeaps: مع وحدات الكلمات يكون الجواب دائمًا، لأن Heaps' law ينص على أن مفردات الكلمات لا تنغلق أبدًا. الإيجاز (compactness) يسأل: كم وحدة يجب أن يعالجها النموذج؟ فكل وحدة تكلّف انتباهًا (attention) وذاكرة، وفي واجهة API مستضافة تكلّف مالًا. الدلالة (meaningfulness) تسأل: هل تقابل الوحدة الواحدة وحدة معنى واحدة؟ وهذا يسهّل المهام اللاحقة مثل الوسم والإعراب (tagging، parsing). الصلاحية عبر اللغات تسأل: هل يعمل المخطط نفسه مع الصينية التي لا مسافات فيها، ومع العربية التي تلصق لواحقها (clitics) عدة كلمات في وحدة مسافية واحدة؟
There is also a quieter reason to care. Jurafsky and Martin note that a standardised tokenization is essential for replicability: a perplexity or an F1 score only means something if the units are the same, so the tokenizer is part of the experimental protocol, not a preprocessing detail (SLP3, chapter 2).
وهناك سبب أهدأ للاهتمام. يشير Jurafsky وMartin إلى أن التقطيع الموحَّد ضروري لقابلية تكرار التجارب: قيمة perplexity أو F1 لا تعني شيئًا إلا إذا كانت الوحدات نفسها، لذلك المقطِّع جزء من البروتوكول التجريبي وليس تفصيلًا من تفاصيل المعالجة المسبقة (SLP3، الفصل 2).
Recall
Name the four properties a good tokenization balances, and say which one word tokens fail on.سمِّ الخصائص الأربع التي يوازن بينها التقطيع الجيد، وقل أيّها تفشل فيه وحدات الكلمات.
Take the word renewed. As a word token it is one unit, but only if it appeared in training; if it did not, it is an unknown. As characters it is 7 letters, eight tokens with the leading space marker, none of which means anything alone. With the subword vocabulary learned later in this part it is four tokens, _re new e d, and the model has seen every one of them before even though it has never seen the word. Those three outcomes are the three granularities, and each buys something by paying for something else.
خذ الكلمة renewed. كوحدة كلمة هي وحدة واحدة، لكن فقط إذا ظهرت في التدريب؛ وإن لم تظهر فهي مجهولة. كحروف هي 7 أحرف، أي ثماني وحدات مع space marker البادئ، ولا يعني أيٌّ منها شيئًا بمفرده. ومع مفردات الوحدات الفرعية التي سنتعلمها لاحقًا في هذا الجزء تصبح أربع وحدات، _re new e d، وقد رأى النموذج كل واحدة منها من قبل رغم أنه لم يرَ الكلمة قط. هذه النتائج الثلاث هي مستويات الدقة (granularity) الثلاثة، وكل منها يكسب شيئًا بدفع ثمن شيء آخر.
| Wordsالكلمات | Charactersالحروف | Subwordsالوحدات الفرعية | |
|---|---|---|---|
| Vocabulary sizeحجم المفردات | Very large and open-ended; grows with the corpus under Heaps' lawضخم جدًا ومفتوح بلا حد، وينمو مع المدوّنة وفق Heaps' law | Tiny: the letters of a script, or 256 byte valuesصغير جدًا: حروف الكتابة، أو 256 قيمة للبايت | Fixed by design, typically 32k to 200k unitsثابت بالتصميم، عادةً من 32k إلى 200k وحدة |
| Sequence lengthطول التسلسل | Shortest: one token per wordالأقصر: وحدة واحدة لكل كلمة | Longest: one token per characterالأطول: وحدة واحدة لكل حرف | In between: frequent words stay whole, rare words splitبينهما: الكلمات المتكررة تبقى كاملة، والنادرة تنقسم |
| Out-of-vocabularyخارج المفردات (OOV) | Yes: rare words, misspellings, new namesنعم: الكلمات النادرة والأخطاء الإملائية والأسماء الجديدة | None: every string is spelled from the base symbolsلا شيء: كل سلسلة تُكتب من الرموز الأساسية | Almost none: unseen words are composed from piecesتقريبًا لا شيء: الكلمات غير المرئية تُركَّب من قطع |
| Meaningfulnessالدلالة | Highest; aligns with lexicons and syntaxالأعلى، تتوافق مع المعاجم والتركيب النحوي | Spread across many tokens; the model must learn to reassemble itموزّعة على وحدات كثيرة، ويجب أن يتعلم النموذج إعادة تجميعها | Often morpheme-like, but only by accident of frequencyغالبًا شبيهة بالصرفيمات، لكن فقط بمصادفة التكرار |
| Best useأفضل استخدام | POS tagging, parsing, lexicon-driven systems that need explicit word boundariesوسم أقسام الكلام (POS tagging) والإعراب النحوي والأنظمة المعتمدة على المعاجم التي تحتاج حدودًا صريحة للكلمات | Noisy OCR or typo-heavy text, very low-resource languages, specialised tasksنص OCR المليء بالضوضاء أو كثير الأخطاء الطباعية، واللغات شديدة الندرة في الموارد، والمهام المتخصصة | Modern language models and machine translationالنماذج اللغوية الحديثة والترجمة الآلية |
Words: meaningful, but the vocabulary never closesالكلمات: ذات معنى، لكن المفردات لا تنغلق أبدًا
Word tokens are the natural first choice. They are meaningful, they line up with dictionaries and with the lexicons that rule-based systems consult, and tasks that need explicit word boundaries, such as part-of-speech tagging, syntactic parsing and lexicon-driven pipelines, are built around them. The problems are the ones the first four parts of this lecture already exposed. "Word" is ambiguous across languages: punctuation, contractions, compounds, clitics and scripts without spaces all give different answers. And the vocabulary is enormous and open-ended. Heaps' law says |V| keeps growing with N, so however large the training corpus, test text brings rare and unseen words, and every one of them is an OOV token the model must lump into a single UNK symbol.
وحدات الكلمات هي الخيار الأول الطبيعي. فهي ذات معنى، وتتوافق مع القواميس ومع المعاجم التي ترجع إليها الأنظمة القائمة على القواعد، والمهام التي تحتاج حدودًا صريحة للكلمات، مثل وسم أقسام الكلام (POS tagging) والإعراب النحوي وخطوط المعالجة المعتمدة على المعاجم، مبنية حولها. المشكلات هي نفسها التي كشفتها الأجزاء الأربعة الأولى من هذه المحاضرة. مفهوم "الكلمة" ملتبس بين اللغات: علامات الترقيم والاختصارات المدمجة (contractions) والكلمات المركبة واللواحق والكتابات التي بلا مسافات كلها تعطي إجابات مختلفة. ثم إن المفردات ضخمة ومفتوحة بلا حد. ينص Heaps' law على أن |V| يستمر في النمو مع N، فمهما كبرت مدوّنة التدريب يأتي نص الاختبار بكلمات نادرة وغير مرئية، وكل واحدة منها وحدة OOV يجب على النموذج أن يجمعها في رمز UNK واحد.
Characters: nothing is unknown, but everything is longالحروف: لا شيء مجهول، لكن كل شيء طويل
Go to the other extreme and tokenize into characters. The vocabulary is tiny, a few dozen letters for Latin script or, at byte level, exactly 256 values. There is no OOV at all, because any string is spelled from the base symbols, and the tokenizer is robust to spelling variants, typos and OCR noise since a damaged word still shares most of its characters with the clean one. The price is paid in sequence length and in meaning. The 6-word string became 29 tokens, roughly five times longer, and attention cost grows with the square of that length. Two words that sit a sentence apart become dozens of positions apart, so a model with a fixed context window sees less of the surrounding text and must learn dependencies across far longer distances. Meaning is spread across many tokens, so the model must spend capacity learning to reassemble words before it can learn anything about them, which makes training slower. Characters are the right call for noisy text, for extremely low-resource languages where no subword vocabulary can be trusted, and for specialised tasks such as transliteration where the character really is the unit.
اذهب إلى الطرف الآخر وقطّع إلى حروف. المفردات صغيرة جدًا: بضع عشرات من الحروف للكتابة اللاتينية، أو بالضبط 256 قيمة على مستوى البايت. لا توجد OOV إطلاقًا، لأن أي سلسلة تُكتب من الرموز الأساسية، والمقطِّع متين أمام اختلافات الإملاء والأخطاء الطباعية وضوضاء OCR، لأن الكلمة المشوّهة تشترك مع السليمة في معظم حروفها. الثمن يُدفع في طول التسلسل وفي المعنى. السلسلة ذات الكلمات 6 صارت 29 وحدة، أي أطول بخمس مرات تقريبًا، وتكلفة الانتباه تنمو مع مربع هذا الطول. كلمتان تفصل بينهما جملة تصبحان على بُعد عشرات المواضع، فيرى نموذج ذو نافذة سياق ثابتة قدرًا أقل من النص المحيط، ويجب أن يتعلم اعتماديات عبر مسافات أطول بكثير. والمعنى موزّع على وحدات كثيرة، فيُنفق النموذج سعته في تعلّم إعادة تجميع الكلمات قبل أن يتعلم أي شيء عنها، وهذا يبطئ التدريب. الحروف هي الخيار الصحيح للنص المليء بالضوضاء، وللغات شديدة الندرة في الموارد حيث لا يمكن الوثوق بأي مفردات فرعية، وللمهام المتخصصة مثل النقحرة (transliteration) حيث يكون الحرف هو الوحدة فعلًا.
Subwords: the middle ground modern models useالوحدات الفرعية: الحل الوسط الذي تستخدمه النماذج الحديثة
Subword tokenization keeps a vocabulary smaller than a word vocabulary and produces sequences shorter than a character sequence, and its decisive property is the third row of the table: an unseen word is composed from pieces that were seen. The GPT-2 paper describes byte-pair encoding as a practical middle ground that interpolates between word-level inputs for frequent symbol sequences and character-level inputs for infrequent ones (Radford et al., 2019). Frequent words stay whole, rare words shatter into recognisable parts, and nothing is ever unknown.
Subword tokenization يحافظ على مفردات أصغر من مفردات الكلمات، وينتج تسلسلات أقصر من تسلسلات الحروف، وخاصيته الحاسمة هي الصف الثالث في الجدول: الكلمة غير المرئية تُركَّب من قطع سبق رؤيتها. تصف ورقة GPT-2 الـ byte-pair encoding بأنه حل وسط عملي يتدرّج بين مدخلات على مستوى الكلمة للتسلسلات الرمزية المتكررة ومدخلات على مستوى الحرف للنادرة (Radford et al., 2019). الكلمات المتكررة تبقى كاملة، والكلمات النادرة تتفتت إلى أجزاء يمكن التعرف عليها، ولا شيء يكون مجهولًا أبدًا.
There are two ways to decide what the pieces are. The linguistically natural way is to cut at morphemes, since morphemes carry meaning by definition. But the morphology parts of this lecture showed why that is hard: allomorphy changes the shape of a morpheme by context, non-concatenative morphology interleaves an Arabic root with a pattern rather than concatenating anything, and clitics blur the boundary between word and affix. Morpheme segmentation needs a linguist, or a model, per language, and it remains ambiguous even then. It is useful in some applications but it is not the common approach in modern language models. The language-agnostic way is to learn frequent substrings from data with no linguistic knowledge at all. That is what byte-pair encoding does, and Jurafsky and Martin name BPE and unigram language modelling as the two families widely used in modern language models (SLP3, section 2.4). They work across languages, reduce OOV and stay efficient, which is why the rest of this part is about one of them.
هناك طريقتان لتحديد ما هي القطع. الطريقة الطبيعية لغويًا هي القطع عند الصرفيمات (morphemes)، لأن الصرفيمات تحمل المعنى بالتعريف. لكن أجزاء الصرف في هذه المحاضرة أظهرت لماذا هذا صعب: التبدّل الصرفي (allomorphy) يغيّر شكل الصرفيم حسب السياق، وnon-concatenative morphology يداخل الجذر العربي مع الوزن بدلًا من وصل شيء بشيء، واللواحق تطمس الحد بين الكلمة والزائدة. تقسيم الصرفيمات يحتاج لغويًا، أو نموذجًا، لكل لغة، ويبقى ملتبسًا حتى مع ذلك. هو مفيد في بعض التطبيقات لكنه ليس النهج الشائع في النماذج اللغوية الحديثة. الطريقة المستقلة عن اللغة هي تعلّم السلاسل الفرعية المتكررة من البيانات دون أي معرفة لغوية على الإطلاق. هذا ما يفعله byte-pair encoding، ويذكر Jurafsky وMartin أن BPE وunigram language modelling هما العائلتان المستخدمتان على نطاق واسع في النماذج اللغوية الحديثة (SLP3، القسم 2.4). تعملان عبر اللغات، وتقللان OOV، وتبقيان فعّالتين، ولهذا خُصّص بقية هذا الجزء لإحداهما.
Quick checkاختبار سريع
Which statement about tokenization granularity is correct?أي عبارة عن مستوى دقة التقطيع صحيحة؟
Recall
Give one reason to prefer characters over words, and one reason to prefer subwords over both.أعطِ سببًا واحدًا لتفضيل الحروف على الكلمات، وسببًا واحدًا لتفضيل الوحدات الفرعية على كليهما.
Here is the smallest corpus that shows the whole idea, borrowed from Jurafsky and Martin: the ten-character string A B D C A B E C A B with the vocabulary {A, B, C, D, E}. Look for the pair of adjacent symbols that occurs most often. It is A B, three times. Replace every A B with a new symbol AB and add it to the vocabulary. Now look again.
إليك أصغر مدوّنة تُظهر الفكرة كلها، مأخوذة من Jurafsky وMartin: السلسلة ذات الحروف العشرة A B D C A B E C A B مع المفردات {A, B, C, D, E}. ابحث عن زوج الرموز المتجاورة الأكثر تكرارًا. إنه A B، ثلاث مرات. استبدل كل A B برمز جديد AB وأضفه إلى المفردات. ثم انظر مجددًا.
Worked exampleمثال محلول
Two merges on a ten-character corpusدمجتان على مدوّنة من عشرة حروف
Merge (A, B)دمج (A, B)
The corpus becomes AB D C AB E C AB, seven symbols instead of ten, and the vocabulary grows to six: {A, B, C, D, E, AB}.تصبح المدوّنة AB D C AB E C AB، سبعة رموز بدلًا من عشرة، وتكبر المفردات إلى ستة: {A, B, C, D, E, AB}.Merge (C, AB)دمج (C, AB)
The most frequent adjacent pair is now C AB, twice. The corpus becomes AB D CAB E CAB, five symbols, and the vocabulary grows to seven with CAB.الزوج المتجاور الأكثر تكرارًا الآن هو C AB، مرتين. تصبح المدوّنة AB D CAB E CAB، خمسة رموز، وتكبر المفردات إلى سبعة بإضافة CAB.Two mergesدمجتان
Vocabulary 5 to 7, corpus 10 to 5 symbols. Each merge adds exactly one vocabulary entry and shortens the corpus by the number of non-overlapping occurrences of the pair it replaces (for pairs of two different symbols, simply the pair count).المفردات من 5 إلى 7، والمدوّنة من 10 إلى 5 رموز. كل دمج يضيف عنصرًا واحدًا بالضبط إلى المفردات ويقصّر المدوّنة بعدد مرات الظهور غير المتداخلة للزوج الذي يستبدله (وللأزواج المكوّنة من رمزين مختلفين، هذا ببساطة عدد الزوج).
That loop is the entire training algorithm of byte-pair encoding. The slide's pseudocode, which is Figure 2.6 of SLP3 adapted from Bostrom and Durrett (2020), reads as follows. Start with V equal to the set of unique characters (or bytes) in the Corpus C. Then repeat k times: find the most frequent pair of adjacent tokens tL, tR in C, form the new token tNEW = tL + tR by concatenation, add it to V, and replace every occurrence of tL tR in C with tNEW. Return V. One iteration of the loop is a Merge.
هذه الحلقة هي خوارزم التدريب الكامل لـ byte-pair encoding. الشيفرة الزائفة في الشريحة، وهي الشكل 2.6 في SLP3 المقتبس من Bostrom and Durrett (2020)، تقول ما يلي. ابدأ بـ V مساوية لمجموعة الحروف (أو البايتات) الفريدة في corpus C. ثم كرّر k مرة: جد زوج الوحدات المتجاورة الأكثر تكرارًا tL, tR في C، وكوّن الوحدة الجديدة tNEW = tL + tR بالوصل، وأضفها إلى V، واستبدل كل ظهور لـ tL tR في C بـ tNEW. أعِد V. التكرار الواحد للحلقة يسمى merge (دمج).
Sennrich, Haddow and Birch, who introduced BPE for neural machine translation, state the consequence plainly: the final symbol vocabulary size is equal to the size of the initial vocabulary plus the number of merge operations, and the number of merges is the only hyperparameter of the algorithm (Sennrich et al., 2016). In the toy example k is 2 or 4. In practice Jurafsky and Martin describe tens of thousands of merges on a very large corpus to produce vocabularies of 50,000, 100,000 or even 200,000 tokens, and GPT-2's vocabulary is 50,257 entries (Radford et al., 2019).
يذكر Sennrich وHaddow وBirch، الذين قدّموا BPE للترجمة الآلية العصبية، النتيجة صراحة: حجم مفردات الرموز النهائي يساوي حجم المفردات الأولية زائد عدد عمليات الدمج، وعدد الدمجات هو المعامل الفائق (hyperparameter) الوحيد للخوارزم (Sennrich et al., 2016). في المثال الصغير k يساوي 2 أو 4. أما عمليًا فيصف Jurafsky وMartin عشرات الآلاف من الدمجات على مدوّنة ضخمة جدًا لإنتاج مفردات من 50,000 أو 100,000 أو حتى 200,000 وحدة، ومفردات GPT-2 فيها 50,257 عنصرًا (Radford et al., 2019).
Two practical details shape the counting. First, merges never cross word boundaries. Sennrich's implementation says it does not consider pairs that cross word boundaries for efficiency, so the corpus is stored as a table of distinct words with their counts, and a pair inside a word that occurs twice in the corpus is counted twice. That is exactly why the slides list the toy corpus as four rows with counts rather than as running text. Second, the base symbols can be characters or bytes. GPT-2 works on UTF-8 bytes because a Unicode Code point vocabulary would start at over 130,000 entries, whereas byte-level BPE starts at exactly 256 and, since every byte is in the vocabulary, there can never be an unknown token (Radford et al., 2019; SLP3, section 2.4).
تفصيلان عمليان يشكّلان طريقة العدّ. أولًا، الدمجات لا تعبر حدود الكلمات أبدًا. ينص تطبيق Sennrich على أنه لا يأخذ في الحسبان الأزواج التي تعبر حدود الكلمات من أجل الكفاءة، لذلك تُخزَّن المدوّنة جدولًا من الكلمات المميزة مع أعدادها، والزوج داخل كلمة تظهر مرتين في المدوّنة يُعدّ مرتين. ولهذا بالضبط تعرض الشرائح المدوّنة الصغيرة أربعة صفوف مع أعدادها بدلًا من نص متصل. ثانيًا، يمكن أن تكون الرموز الأساسية حروفًا أو بايتات. يعمل GPT-2 على بايتات UTF-8 لأن مفردات من code points Unicode كانت ستبدأ بأكثر من 130,000 عنصر، بينما يبدأ byte-level BPE بـ 256 بالضبط، ولأن كل بايت موجود في المفردات لا يمكن أن تظهر وحدة مجهولة أبدًا (Radford et al., 2019؛ SLP3، القسم 2.4).
Where the algorithm came from, and its two halvesمن أين جاء الخوارزم، ونصفاه
The name is older than NLP. Philip Gage published byte pair encoding in 1994 as a data compression method: find the most frequently occurring pair of adjacent bytes in the data, replace all instances with a byte that was not in the original data, and repeat until no further compression is possible (Gage, 1994). Sennrich and colleagues adapted it for word segmentation, and two things changed. The units became characters rather than bytes, and the stopping rule became a fixed k rather than exhaustion, so the merges are no longer a throwaway table for one file but a reusable vocabulary shared by every text the model will ever see.
الاسم أقدم من NLP. نشر Philip Gage خوارزم byte pair encoding عام 1994 طريقةً لضغط البيانات: جد زوج البايتات المتجاورة الأكثر تكرارًا في البيانات، واستبدل كل ظهوراته ببايت لم يكن في البيانات الأصلية، وكرّر حتى لا يعود الضغط ممكنًا (Gage, 1994). كيّفه Sennrich وزملاؤه لتقسيم الكلمات، وتغيّر أمران. صارت الوحدات حروفًا بدلًا من بايتات، وصارت قاعدة التوقف عددًا ثابتًا k بدلًا من الاستنفاد، فلم تعد الدمجات جدولًا يُرمى بعد ملف واحد، بل مفردات قابلة لإعادة الاستخدام يتشاركها كل نص سيراه النموذج.
That reuse is why BPE has two parts. The trainer runs once, over the training corpus, and produces the vocabulary together with the ordered list of merges it performed. The encoder runs every time new text arrives and applies that list. The two must never be confused, and the last concept of this part is devoted to the encoder. The simulator below is the trainer: step through the merges and watch the pair table decide each one, then encode a word of your own in its lower panel; the encoder concept returns to that panel on its own.
إعادة الاستخدام هذه هي سبب وجود جزأين لـ BPE. المدرِّب (trainer) يعمل مرة واحدة على مدوّنة التدريب، وينتج المفردات مع القائمة المرتبة للدمجات التي نفّذها. المرمِّز (encoder) يعمل في كل مرة يصل فيها نص جديد ويطبّق تلك القائمة. يجب ألا يُخلط بينهما أبدًا، والمفهوم الأخير في هذا الجزء مخصص للمرمِّز. المحاكي أدناه هو المدرِّب: تقدّم عبر الدمجات وراقب جدول الأزواج يقرر كل واحدة، ثم رمّز كلمة من اختيارك في لوحته السفلية؛ ويعود مفهوم المرمِّز إلى تلك اللوحة بشكل مستقل.
- 2_new
- 2_renew
- 1set
- 1_reset
Grey chips are the initial symbols, teal chips are learned merges in the order they were learned, and the accent chip is the newest.الرقاقات الرمادية هي الرموز الأولية، والرقاقات الخضراء المزرقة هي عمليات الدمج المتعلَّمة بترتيب تعلُّمها، والرقاقة باللون المميز هي الأحدث.
| Rankالرتبة | Pairالزوج | Countالعدد | First seen atأول ظهور عند | Noteملاحظة |
|---|---|---|---|---|
| 1 | (n, e) | 4 | position 1الموضع 1 | winner, tie broken by ruleالفائز، وحُسم التعادل بالقاعدة |
| 2 | (e, w) | 4 | position 2الموضع 2 | tie at the maximumتعادل عند القيمة القصوى |
| 3 | (_, r) | 3 | position 4الموضع 4 | |
| 4 | (r, e) | 3 | position 5الموضع 5 | |
| 5 | (_, n) | 2 | position 0الموضع 0 | |
| 6 | (e, n) | 2 | position 6الموضع 6 | |
| 7 | (s, e) | 2 | position 10الموضع 10 | |
| 8 | (e, t) | 2 | position 11الموضع 11 | |
| 9 | (e, s) | 1 | position 15الموضع 15 |
- charactersالمحارف_renewed
- outputالناتج_ r e n e w e d (8 tokens)(8 رموز)
The encoder never counts anything. It replays the merge list top to bottom; a merge whose pair does not occur in the word is skipped.المرمِّز لا يعدّ أي شيء. إنه يعيد تطبيق قائمة الدمج من أعلاها إلى أسفلها، ويتخطى كل دمج لا يظهر زوجه في الكلمة.
Quick checkاختبار سريع
In one BPE training step, what exactly does the trainer merge?في خطوة تدريب واحدة من BPE، ما الذي يدمجه المدرِّب بالضبط؟
Recall
State the difference between the BPE trainer and the BPE encoder in one sentence each.اذكر الفرق بين مدرِّب BPE ومرمِّز BPE في جملة واحدة لكل منهما.
Now run the BPE trainer by hand on the slide Corpus, set new new renew reset renew, for k = 4. This is the same example as the current SLP3 draft (example 2.11 in section 2.4), so the tables here match both the slides and the book symbol for symbol. The slides show the corpus and the Vocabulary after each Merge but never the pair counts that decided it, so those are worked out in full below.
الآن شغّل مدرِّب BPE يدويًا على corpus الشريحة، set new new renew reset renew، لعدد k = 4. هذا هو المثال نفسه في مسودة SLP3 الحالية (المثال 2.11 في القسم 2.4)، لذلك تطابق الجداول هنا الشرائح والكتاب رمزًا برمز. تعرض الشرائح المدوّنة وvocabulary بعد كل merge، لكنها لا تعرض أبدًا أعداد الأزواج التي حسمته، لذلك نحسبها كاملة أدناه.
First the setup. Every word except the first carries a leading space marker, drawn as an open box on the slides and written _ here. The first word, set, starts the string, so it has none. Grouping equal words gives four rows with counts: 2 × _ n e w, 2 × _ r e n e w, 1 × s e t and 1 × _ r e s e t. The initial vocabulary is the seven symbols _, e, n, r, s, t, w, and the corpus holds 2 × 4 + 2 × 6 + 3 + 6 = 29 symbols. Pair counts are weighted by row count: a pair that occurs once inside _ n e w counts 2.
أولًا الإعداد. كل كلمة ما عدا الأولى تحمل space marker بادئًا، يُرسم مربعًا مفتوحًا في الشرائح ونكتبه _ هنا. الكلمة الأولى، set، تبدأ السلسلة فلا وسم لها. تجميع الكلمات المتساوية يعطي أربعة صفوف مع أعدادها: 2 × _ n e w و2 × _ r e n e w و1 × s e t و1 × _ r e s e t. المفردات الأولية هي الرموز السبعة _, e, n, r, s, t, w، والمدوّنة تحوي 2 × 4 + 2 × 6 + 3 + 6 = 29 رمزًا. أعداد الأزواج موزونة بعدد الصف: الزوج الذي يظهر مرة واحدة داخل _ n e w يُعدّ 2.
Worked exampleمثال محلول
Four merges on set new new renew reset renewأربع دمجات على set new new renew reset renew
Merge 1: count every adjacent pairالدمج 1: عُدّ كل زوج متجاور
Pairالزوج Countالعدد Noteملاحظة (n, e)(n, e) 44 winner: tied with (e, w), seen first in the corpusالفائز: متعادل مع (e, w)، وظهر أولًا في المدوّنة (e, w)(e, w) 44 tie at the maximumتعادل عند الحد الأقصى (_, r)(_, r) 33 (r, e)(r, e) 33 (_, n)(_, n) 22 (e, n)(e, n) 22 (s, e)(s, e) 22 (e, t)(e, t) 22 (e, s)(e, s) 11 (n, e) occurs once in _ n e w (count 2) and once in _ r e n e w (count 2), so it scores 4. So does (e, w). The pseudocode says nothing about ties; the slide merges n e, which is the pair encountered first when scanning the corpus. The corpus becomes 2 × _ ne w, 2 × _ r e ne w, 1 × s e t, 1 × _ r e s e t and ne joins the vocabulary.
Pairالزوج Countالعدد Noteملاحظة (n, e)(n, e) 44 winner: tied with (e, w), seen first in the corpusالفائز: متعادل مع (e, w)، وظهر أولًا في المدوّنة (e, w)(e, w) 44 tie at the maximumتعادل عند الحد الأقصى (_, r)(_, r) 33 (r, e)(r, e) 33 (_, n)(_, n) 22 (e, n)(e, n) 22 (s, e)(s, e) 22 (e, t)(e, t) 22 (e, s)(e, s) 11 يظهر (n, e) مرة في _ n e w (العدد 2) ومرة في _ r e n e w (العدد 2)، فيحصل على 4. وكذلك (e, w). الشيفرة الزائفة لا تقول شيئًا عن التعادل؛ الشريحة تدمج n e، وهو الزوج الذي يُصادَف أولًا عند مسح المدوّنة. تصبح المدوّنة 2 × _ ne w, 2 × _ r e ne w, 1 × s e t, 1 × _ r e s e t وتنضم ne إلى المفردات.
Merge 2: recount on the new corpusالدمج 2: أعِد العدّ على المدوّنة الجديدة
Pairالزوج Countالعدد Noteملاحظة (ne, w)(ne, w) 44 winner: the only pair at 4 once ne existsالفائز: الزوج الوحيد عند 4 بعد وجود ne (_, r)(_, r) 33 (r, e)(r, e) 33 (_, ne)(_, ne) 22 (e, ne)(e, ne) 22 (s, e)(s, e) 22 (e, t)(e, t) 22 (e, s)(e, s) 11 The old pair (e, w) no longer exists because the e in front of every w is now inside ne. (ne, w) scores 4 alone, so new is merged with no tie. The corpus becomes 2 × _ new, 2 × _ r e new, 1 × s e t, 1 × _ r e s e t.
Pairالزوج Countالعدد Noteملاحظة (ne, w)(ne, w) 44 winner: the only pair at 4 once ne existsالفائز: الزوج الوحيد عند 4 بعد وجود ne (_, r)(_, r) 33 (r, e)(r, e) 33 (_, ne)(_, ne) 22 (e, ne)(e, ne) 22 (s, e)(s, e) 22 (e, t)(e, t) 22 (e, s)(e, s) 11 الزوج القديم (e, w) لم يعد موجودًا لأن الـ e التي تسبق كل w صارت الآن داخل ne. يحصل (ne, w) على 4 وحده، فتُدمج new دون تعادل. تصبح المدوّنة 2 × _ new, 2 × _ r e new, 1 × s e t, 1 × _ r e s e t.
Merge 3: a second tieالدمج 3: تعادل ثانٍ
Pairالزوج Countالعدد Noteملاحظة (_, r)(_, r) 33 winner: tied with (r, e), seen firstالفائز: متعادل مع (r, e)، وظهر أولًا (r, e)(r, e) 33 tie at the maximumتعادل عند الحد الأقصى (_, new)(_, new) 22 (e, new)(e, new) 22 (s, e)(s, e) 22 (e, t)(e, t) 22 (e, s)(e, s) 11 (_, r) and (r, e) both score 3: twice from _ r e new and once from _ r e s e t. The slide merges _ r, again the pair seen first. The corpus becomes 2 × _ new, 2 × _r e new, 1 × s e t, 1 × _r e s e t.
Pairالزوج Countالعدد Noteملاحظة (_, r)(_, r) 33 winner: tied with (r, e), seen firstالفائز: متعادل مع (r, e)، وظهر أولًا (r, e)(r, e) 33 tie at the maximumتعادل عند الحد الأقصى (_, new)(_, new) 22 (e, new)(e, new) 22 (s, e)(s, e) 22 (e, t)(e, t) 22 (e, s)(e, s) 11 يحصل كل من (_, r) و(r, e) على 3: مرتين من _ r e new ومرة من _ r e s e t. الشريحة تدمج _ r، وهو مرة أخرى الزوج الذي يُرى أولًا. تصبح المدوّنة 2 × _ new, 2 × _r e new, 1 × s e t, 1 × _r e s e t.
Merge 4: the tie resolves itselfالدمج 4: التعادل يحل نفسه
Pairالزوج Countالعدد Noteملاحظة (_r, e)(_r, e) 33 winner: the only pair at 3 once _r existsالفائز: الزوج الوحيد عند 3 بعد وجود _r (_, new)(_, new) 22 (e, new)(e, new) 22 (s, e)(s, e) 22 (e, t)(e, t) 22 (e, s)(e, s) 11 With _r in place, (r, e) has disappeared and (_r, e) inherits its count of 3, the unique maximum. Merging it gives _re. Slide 47 shows merges 3 and 4 together for this reason: the second is forced by the first.
Pairالزوج Countالعدد Noteملاحظة (_r, e)(_r, e) 33 winner: the only pair at 3 once _r existsالفائز: الزوج الوحيد عند 3 بعد وجود _r (_, new)(_, new) 22 (e, new)(e, new) 22 (s, e)(s, e) 22 (e, t)(e, t) 22 (e, s)(e, s) 11 مع وجود _r، اختفى (r, e) وورث (_r, e) عدده 3، وهو الحد الأقصى الوحيد. دمجه يعطي _re. تعرض الشريحة 47 الدمجين 3 و4 معًا لهذا السبب: الثاني يفرضه الأول.
After k = 4بعد k = 4
Vocabulary _, e, n, r, s, t, w, ne, new, _r, _re (11 entries, 7 + 4). Corpus 2 × _ new, 2 × _re new, 1 × s e t, 1 × _re s e t, which is 15 symbols instead of 29. Merge list, in order: ne, new, _r, _re.المفردات _, e, n, r, s, t, w, ne, new, _r, _re (11 عنصرًا، 7 + 4). المدوّنة 2 × _ new, 2 × _re new, 1 × s e t, 1 × _re s e t، أي 15 رمزًا بدلًا من 29. قائمة الدمجات بالترتيب: ne, new, _r, _re.
| Mergeالدمج | New token (count)الوحدة الجديدة (العدد) | Corpus symbolsرموز المدوّنة | |V||V| | Corpusالمدوّنة |
|---|---|---|---|---|
| 00 | startالبداية | 2929 | 77 | 2 _ n e w, 2 _ r e n e w, 1 s e t, 1 _ r e s e t2 _ n e w, 2 _ r e n e w, 1 s e t, 1 _ r e s e t |
| 11 | ne (4, tie)ne (4، تعادل) | 2525 | 88 | 2 _ ne w, 2 _ r e ne w, 1 s e t, 1 _ r e s e t2 _ ne w, 2 _ r e ne w, 1 s e t, 1 _ r e s e t |
| 22 | new (4)new (4) | 2121 | 99 | 2 _ new, 2 _ r e new, 1 s e t, 1 _ r e s e t2 _ new, 2 _ r e new, 1 s e t, 1 _ r e s e t |
| 33 | _r (3, tie)_r (3، تعادل) | 1818 | 1010 | 2 _ new, 2 _r e new, 1 s e t, 1 _r e s e t2 _ new, 2 _r e new, 1 s e t, 1 _r e s e t |
| 44 | _re (3)_re (3) | 1515 | 1111 | 2 _ new, 2 _re new, 1 s e t, 1 _re s e t2 _ new, 2 _re new, 1 s e t, 1 _re s e t |
Ties: the pseudocode is silent, so state your ruleالتعادل: الشيفرة الزائفة صامتة، فاذكر قاعدتك
Two of the four steps were decided by a tie, and the algorithm as written never says how to break one. Real implementations do have a rule, and it is worth knowing which. The minimal listing in the Sennrich paper (Algorithm 1) picks the best pair with Python's max(pairs, key=pairs.get), which in modern Python (3.7 and later, where dictionaries keep insertion order) returns the first pair encountered while scanning. The released subword-nmt implementation instead selects with max(stats, key=lambda x: (stats[x], x)), which prefers the lexicographically largest pair among the tied ones. On this corpus that rule agrees with the slides at merge 1, choosing (n, e) because n sorts after e, but at merge 3 it chooses (r, e) over (_, r). The Hugging Face course states the first-encountered convention explicitly: when there is a choice of the most frequent pair, the first one encountered is selected. The 🤗 Tokenizers library breaks ties by internal token ids, and the simulator's alphabetical option takes the smallest pair.
خطوتان من الخطوات الأربع حسمهما تعادل، والخوارزم كما هو مكتوب لا يقول أبدًا كيف يُكسر. التطبيقات الحقيقية لها قاعدة فعلًا، ومن المفيد معرفة أيّها. القائمة المختصرة في ورقة Sennrich (الخوارزم 1) تختار أفضل زوج بـ max(pairs, key=pairs.get) في Python، وهذا في Python الحديثة (3.7 وما بعدها، حيث تحافظ القواميس على ترتيب الإدخال) يعيد أول زوج يُصادَف أثناء المسح. أما تطبيق subword-nmt المنشور فيختار بـ max(stats, key=lambda x: (stats[x], x))، الذي يفضّل الزوج الأكبر معجميًا بين المتعادلين. على هذه المدوّنة تتفق هذه القاعدة مع الشرائح في الدمج 1، فتختار (n, e) لأن n تأتي بعد e في الترتيب، لكنها في الدمج 3 تختار (r, e) بدلًا من (_, r). دورة Hugging Face تنص على اصطلاح الظهور الأول صراحة: عندما يكون هناك خيار بين الأزواج الأكثر تكرارًا، يُختار أول زوج يُصادَف. مكتبة 🤗 Tokenizers تكسر التعادل بمعرّفات الوحدات الداخلية، والخيار الأبجدي في المحاكي يأخذ أصغر زوج.
The simulator lets you switch between first-seen and alphabetical order, and on this corpus the very first merge already differs: alphabetical order picks (e, w) over (n, e), so the vocabulary ends with ew where the slides have ne, even though the corpus rows after four merges are identical. That is exactly why an exam answer must state its rule.
يتيح لك المحاكي التبديل بين ترتيب الظهور الأول والترتيب الأبجدي، وعلى هذه المدوّنة يختلف الدمج الأول نفسه: الترتيب الأبجدي يختار (e, w) بدلًا من (n, e)، فتنتهي المفردات بـ ew حيث في الشرائح ne، رغم أن صفوف المدوّنة بعد أربع دمجات متطابقة. ولهذا بالضبط يجب أن تذكر إجابة الامتحان قاعدتها.
| First pair seen (slides)أول زوج يُرى (الشرائح) | Alphabetical (smallest first)أبجدي (الأصغر أولًا) | |
|---|---|---|
| Merge 1الدمج 1 | ne (tied with ew, seen first)ne (متعادل مع ew، وظهر أولًا) | ew (tied with ne, ew < ne)ew (متعادل مع ne، وew < ne) |
| Merge 2الدمج 2 | new from (ne, w)new من (ne, w) | new from (n, ew)new من (n, ew) |
| Merge 3الدمج 3 | _r (tied with re, seen first)_r (متعادل مع re، وظهر أولًا) | _r (tied with re, _ sorts first)_r (متعادل مع re، و_ تأتي أولًا في الترتيب) |
| Merge 4الدمج 4 | _re_re | _re_re |
| Learned tokensالوحدات المتعلَّمة | ne, new, _r, _rene, new, _r, _re | ew, new, _r, _reew, new, _r, _re |
| Corpus after k = 4المدوّنة بعد k = 4 | 2 × _ new, 2 × _re new, s e t, _re s e t2 × _ new, 2 × _re new, s e t, _re s e t | 2 × _ new, 2 × _re new, s e t, _re s e t2 × _ new, 2 × _re new, s e t, _re s e t |
The order of the rows matters too, because "first encountered" depends on it. The slides list the four rows by count, most frequent first, and so does SLP3. Jurafsky and Martin continue the same trace past the slides: merges five to seven are _new, _renew and se, each decided by a tie at count 2, and merge eight, set, is then forced because (se, t) is the only pair left at 2. The simulator reproduces that order exactly when its rows are listed the same way.
ترتيب الصفوف مهم أيضًا، لأن "أول ما يُصادَف" يعتمد عليه. الشرائح ترتب الصفوف الأربعة حسب العدد، الأكثر تكرارًا أولًا، وكذلك SLP3. يواصل Jurafsky وMartin التتبّع نفسه بعد الشرائح: الدمجات من الخامس إلى السابع هي _new و_renew وse، وكل منها حسمه تعادل عند العدد 2، ثم يُفرض الدمج الثامن، set، لأن (se, t) هو الزوج الوحيد المتبقي عند 2. يعيد المحاكي إنتاج هذا الترتيب بالضبط عندما تُرتب صفوفه بالطريقة نفسها.
What the space marker does to the learned unitsماذا يفعل وسم المسافة بالوحدات المتعلَّمة
The marker is not cosmetic. Because this deck attaches it to the start of a word, the trainer learned _re, a word-initial piece, and that token is different from a re that occurs inside a word, as in _ c a re, which never merges into _re. Jurafsky and Martin put it this way: the system has essentially induced that there is a word-initial prefix re- (SLP3, section 2.4). This leading-marker convention is the one used by GPT-2, whose byte-level tokenizer shows the space as Ġ, and by SentencePiece, which shows it as ▁ (U+2581); in both, the space rides on the following word (Hugging Face tokenizers documentation). It also explains why set in the trace never carries a marker: it is the first word of the string, so no space precedes it, and s e t and _ s e t are different strings to the trainer.
الوسم ليس تجميليًا. لأن هذه الشرائح تلصقه ببداية الكلمة، تعلّم المدرِّب _re، وهي قطعة في بداية الكلمة، وهذه الوحدة تختلف عن re التي تظهر داخل كلمة، كما في _ c a re، التي لا تندمج أبدًا في _re. يعبّر Jurafsky وMartin عن ذلك هكذا: لقد استنتج النظام فعليًا أن هناك سابقة في بداية الكلمة هي re- (SLP3، القسم 2.4). اصطلاح الوسم البادئ هذا هو الذي يستخدمه GPT-2، الذي يُظهر مقطِّعه على مستوى البايت المسافة على شكل Ġ، وSentencePiece، الذي يُظهرها على شكل ▁ (U+2581)؛ وفي كليهما تركب المسافة على الكلمة التالية (توثيق Hugging Face tokenizers). وهذا يفسر أيضًا لماذا لا تحمل set في التتبّع وسمًا أبدًا: إنها الكلمة الأولى في السلسلة فلا تسبقها مسافة، وs e t و_ s e t سلسلتان مختلفتان بالنسبة للمدرِّب.
The original paper did it the other way round. Sennrich, Haddow and Birch appended a special end-of-word symbol to every word so that the original tokenization could be restored after translation, and older SLP3 drafts followed them with the corpus low lowest newer wider new (Sennrich's own listing uses low lower newest widest). Under that convention every word gets a marker, the marker sits at the end, and the prefix would be learned as plain re.
الورقة الأصلية فعلت العكس. ألحق Sennrich وHaddow وBirch رمزًا خاصًا لنهاية الكلمة بكل كلمة حتى يمكن استعادة التقطيع الأصلي بعد الترجمة، وتبعتهم مسودات SLP3 الأقدم بالمدوّنة low lowest newer wider new (القائمة الخاصة بـ Sennrich تستخدم low lower newest widest). وفق هذا الاصطلاح تحصل كل كلمة على وسم، ويقع الوسم في النهاية، وكانت السابقة ستُتعلَّم على شكل re عادية.
| Leading marker (this deck)الوسم البادئ (هذه الشرائح) | End-of-word suffix (Sennrich 2016)لاحقة نهاية الكلمة (Sennrich 2016) | |
|---|---|---|
| Where the marker sitsموضع الوسم | Before the word: _new, _reقبل الكلمة: _new، _re | After the word: new·, set·بعد الكلمة: new·، set· |
| First word of the stringالكلمة الأولى في السلسلة | No marker: set stays s e tبلا وسم: set تبقى s e t | Marker like every word: s e t ·بوسم مثل كل كلمة: s e t · |
| Prefix re- is learned asالسابقة re- تُتعلَّم على شكل | _re, distinct from word-internal re_re، المختلفة عن re الواقعة داخل الكلمة | re, identical to word-internal rere، المطابقة لـ re الواقعة داخل الكلمة |
| Used byيستخدمه | This deck, current SLP3, GPT-2 (Ġ), SentencePiece (▁)هذه الشرائح، وSLP3 الحالي، وGPT-2 (Ġ)، وSentencePiece (▁) | Sennrich et al. 2016, older SLP3 draftsSennrich et al. 2016، ومسودات SLP3 الأقدم |
Quick checkاختبار سريع
After merging ne and new on 'set new new renew reset renew', which pair wins merge 3 under first-seen tie-breaking?بعد دمج ne وnew على 'set new new renew reset renew'، أي زوج يفوز بالدمج 3 تحت قاعدة كسر التعادل بالظهور الأول؟
Recall
After merges ne, new, _r and _re on 'set new new renew reset renew', list the vocabulary and the corpus.بعد الدمجات ne وnew و_r و_re على 'set new new renew reset renew'، اسرد المفردات والمدوّنة.
Recall
Step 1 counts (n, e) = 4 and (e, w) = 4. What does the pseudocode say about the tie, and what do real implementations do?الخطوة 1 تعدّ (n, e) = 4 و(e, w) = 4. ماذا تقول الشيفرة الزائفة عن التعادل، وماذا تفعل التطبيقات الحقيقية؟
Recall
How does the leading space marker change what is learned?كيف يغيّر وسم المسافة البادئ ما يُتعلَّم؟
Training is over. The merge list ne, new, _r, _re is frozen, and a word arrives that the trainer never saw: renewed, with its leading space. The encoder does not count anything. It writes the word as characters and replays the four merges, first to last.
انتهى التدريب. قائمة merge وهي ne, new, _r, _re مجمّدة، وتصل كلمة لم يرها المدرِّب قط: renewed، مع مسافتها البادئة. المرمِّز لا يعدّ أي شيء. إنه يكتب الكلمة حروفًا ويعيد تطبيق الدمجات الأربع، من الأول إلى الأخير.
Worked exampleمثال محلول
Encoding three words with the four learned mergesترميز ثلاث كلمات بالدمجات الأربع المتعلَّمة
_renewed, an unseen word_renewed، كلمة لم تُرَ من قبل
Start from _ r e n e w e d, eight symbols. Merge 1 (n e) applies: _ r e ne w e d. Merge 2 (ne w) applies: _ r e new e d. Merge 3 (_ r) applies: _r e new e d. Merge 4 (_r e) applies: _re new e d. Four tokens, all in the vocabulary, no unknown.ابدأ من _ r e n e w e d، ثمانية رموز. الدمج 1 (n e) ينطبق: _ r e ne w e d. الدمج 2 (ne w) ينطبق: _ r e new e d. الدمج 3 (_ r) ينطبق: _r e new e d. الدمج 4 (_r e) ينطبق: _re new e d. أربع وحدات، كلها في المفردات، ولا وحدة مجهولة._newest, where two merges do not apply_newest، حيث لا ينطبق دمجان
_ n e w e s t becomes _ ne w e s t, then _ new e s t. Merges 3 and 4 look for _ r and _r e, find neither, and are skipped. Output _ new e s t. The marker stays separate because (_, new) was merge 5 in the book's longer run and is not in this list._ n e w e s t تصبح _ ne w e s t، ثم _ new e s t. الدمجان 3 و4 يبحثان عن _ r و_r e، فلا يجدان أيًّا منهما، فيُتخطّيان. الناتج _ new e s t. يبقى الوسم منفصلًا لأن (_, new) كان الدمج 5 في التشغيل الأطول في الكتاب، وليس في هذه القائمة.set at the start of a sentenceset في بداية الجملة
No leading marker, so the input is s e t. None of the four merges mentions s or t, so the output is s e t, three tokens. With k = 8 it would be the single token set.لا وسم بادئ، فالمدخل هو s e t. لا يذكر أي من الدمجات الأربع s أو t، فالناتج s e t، ثلاث وحدات. ومع k = 8 كانت ستصبح الوحدة الواحدة set.The encoder is a replayالمرمِّز إعادة تشغيل
Same list, same order, every input. _renewed is a word the model has never seen, tokenized entirely from pieces it has.القائمة نفسها، والترتيب نفسه، لكل مدخل. _renewed كلمة لم يرها النموذج قط، وقد قُطّعت بالكامل من قطع يعرفها.
Try the same replay on words of your own. The panel below starts from the four slide merges; type newest, reset or an Arabic transliteration, tick sentence-initial to drop the marker, and raise k to watch _new and set collapse into single tokens once merges five to eight exist.
جرّب إعادة التشغيل نفسها على كلمات من اختيارك. تبدأ اللوحة أدناه من دمجات الشريحة الأربع؛ اكتب newest أو reset أو كلمة عربية منقحرة بحروف لاتينية، وفعّل خيار بداية الجملة لإسقاط الوسم، وارفع k لترى _new وset تنضمّان في وحدات مفردة بمجرد وجود الدمجات من الخامس إلى الثامن.
- 1.ne
- 2.new
- 3._r
- 4._re
- charactersالمحارف_renewed
- 1. n+e_renewed
- 2. ne+w_renewed
- 3. _+r_renewed
- 4. _r+e_renewed
- outputالناتج_re new e d (4 tokens)(4 رموز)
The encoder never counts anything. It replays the merge list top to bottom; a merge whose pair does not occur in the word is skipped.المرمِّز لا يعدّ أي شيء. إنه يعيد تطبيق قائمة الدمج من أعلاها إلى أسفلها، ويتخطى كل دمج لا يظهر زوجه في الكلمة.
The rule behind the trace is short. To tokenize a new string, start from characters or bytes, apply the learned merges in the order they were learned, and output the resulting subword sequence. The slide calls this "greedy": each merge fires on every place it matches as soon as its turn comes, the encoder never goes back, and it never searches for the longest vocabulary entry. Jurafsky and Martin are exact about what the encoder does not do: it just runs on the test data the merges learned from the training data, in the order they were learned, and the frequencies in the test data play no role, only the frequencies in the training data (SLP3, section 2.4). Sennrich describes the same procedure: split words into sequences of characters, then apply the learned operations to merge the characters into larger known symbols. Because the list is fixed, the output is deterministic: the same input always yields the same tokens, which is what lets a model trained on one tokenization be served with it later.
القاعدة وراء التتبّع قصيرة. لتقطيع سلسلة جديدة، ابدأ من الحروف أو البايتات، وطبّق الدمجات المتعلَّمة بالترتيب الذي تُعلِّمت به، وأخرج تسلسل الوحدات الفرعية الناتج. تسمي الشريحة هذا "جشعًا" (greedy): كل دمج يُطلَق على كل موضع يطابقه بمجرد أن يحين دوره، والمرمِّز لا يعود إلى الوراء أبدًا، ولا يبحث أبدًا عن أطول عنصر في المفردات. Jurafsky وMartin دقيقان بشأن ما لا يفعله المرمِّز: إنه يشغّل فقط على بيانات الاختبار الدمجات التي تعلّمها من بيانات التدريب، بالترتيب الذي تُعلِّمت به، والتكرارات في بيانات الاختبار لا دور لها، فقط التكرارات في بيانات التدريب (SLP3، القسم 2.4). ويصف Sennrich الإجراء نفسه: قسّم الكلمات إلى تسلسلات من الحروف، ثم طبّق العمليات المتعلَّمة لدمج الحروف في رموز معروفة أكبر. ولأن القائمة ثابتة فالناتج حتمي: المدخل نفسه يعطي دائمًا الوحدات نفسها، وهذا ما يتيح تقديم نموذج دُرِّب على تقطيع معيّن بالتقطيع نفسه لاحقًا.
Order is not a convention but a dependency. Merge 2 joins ne and w, and ne only exists if merge 1 has already run; merge 4 needs _r from merge 3 in the same way. Replaying the list out of order would produce segmentations that never occurred during training, so the model would receive token ids it has no experience of, even though every id is technically in the vocabulary. With tens of thousands of merges, most words in ordinary text are covered by a single token and only rare words break into pieces, which is the interpolation between word and character level that the GPT-2 paper describes (Radford et al., 2019).
الترتيب ليس اصطلاحًا بل اعتمادية. الدمج 2 يضم ne وw، وne لا توجد إلا إذا كان الدمج 1 قد نُفِّذ؛ والدمج 4 يحتاج _r من الدمج 3 بالطريقة نفسها. إعادة تطبيق القائمة بغير ترتيبها ستنتج تقسيمات لم تحدث قط أثناء التدريب، فيتلقى النموذج معرّفات وحدات لا خبرة له بها، رغم أن كل معرّف موجود تقنيًا في المفردات. ومع عشرات الآلاف من الدمجات، تغطي وحدة واحدة معظم الكلمات في النص العادي، ولا تتكسر إلى قطع إلا الكلمات النادرة، وهذا هو التدرّج بين مستوى الكلمة ومستوى الحرف الذي تصفه ورقة GPT-2 (Radford et al., 2019).
| Trainerالمدرِّب (trainer) | Encoderالمرمِّز (encoder) | |
|---|---|---|
| Inputالمدخل | A training corpus with word countsمدوّنة تدريب مع أعداد الكلمات | One new stringسلسلة جديدة واحدة |
| Counts pair frequenciesيعدّ تكرارات الأزواج | Yes, at every stepنعم، في كل خطوة | Neverأبدًا |
| Outputالمخرج | A vocabulary plus an ordered merge listمفردات مع قائمة دمجات مرتبة | A token sequenceتسلسل من الوحدات |
| Runsمتى يعمل | Once, before any model is trainedمرة واحدة، قبل تدريب أي نموذج | On every input, forever afterعلى كل مدخل، إلى الأبد بعد ذلك |
| Hyperparameterالمعامل الفائق (hyperparameter) | k, the number of mergesk، عدد الدمجات | None; the merge list is fixedلا شيء، فقائمة الدمجات ثابتة |
One last coverage detail depends on the base symbols. A character-level BPE trained on English letters still has a hole: the Hugging Face course shows mug encoding as [UNK] ug because m never appeared in its toy corpus, so it is not in the vocabulary at all. A byte-level tokenizer starts from all 256 byte values, so any UTF-8 string, including Arabic, emoji and typos, is encodable and the UNK special token is never needed (Radford et al., 2019; Hugging Face tokenizers documentation). The next part looks at what this does to non-Latin scripts.
تفصيل أخير في التغطية يعتمد على الرموز الأساسية. BPE على مستوى الحرف مدرَّب على الحروف الإنجليزية ما زال فيه ثغرة: دورة Hugging Face تُظهر mug تُرمَّز على شكل [UNK] ug لأن m لم تظهر قط في مدوّنتها الصغيرة، فهي ليست في المفردات أصلًا. أما مقطِّع byte-level فيبدأ من كل قيم البايت الـ 256، لذلك أي سلسلة UTF-8، بما في ذلك العربية والرموز التعبيرية والأخطاء الطباعية، قابلة للترميز، ولا حاجة أبدًا إلى special token UNK (Radford et al., 2019؛ توثيق Hugging Face tokenizers). الجزء التالي ينظر في أثر ذلك على الكتابات غير اللاتينية.
Quick checkاختبار سريع
When BPE encodes new text, what decides which merges are applied?عندما يرمّز BPE نصًا جديدًا، ما الذي يحدد أي الدمجات تُطبَّق؟
Recall
With merges ne, new, _r, _re learned in that order, how is the unseen word '_renewal' encoded, and why can no other segmentation occur?مع الدمجات ne وnew و_r و_re متعلَّمة بهذا الترتيب، كيف تُرمَّز الكلمة غير المرئية '_renewal'، ولماذا لا يمكن أن يحدث تقسيم آخر؟
Recall
Why must the encoder apply merges in the order they were learned?لماذا يجب أن يطبّق المرمِّز الدمجات بالترتيب الذي تُعلِّمت به؟
Recapالخلاصة
If you remember nothing elseإن لم تتذكر شيئاً آخر فتذكّر هذا
- Tokenization converts text into the units a model operates on; the unit choice trades coverage, compactness, meaningfulness and cross-lingual reach.يحوّل التقطيع (tokenization) النص إلى الوحدات التي يعمل عليها النموذج، واختيار الوحدة مفاضلة بين التغطية والإيجاز والدلالة والصلاحية عبر اللغات.
- Words: meaningful but ambiguous, huge vocabularies, OOV. Characters: tiny vocabulary, no OOV, very long sequences. Subwords: the middle ground modern LMs use.الكلمات: ذات معنى لكنها ملتبسة، ومفرداتها ضخمة، وتعاني من مشكلة OOV. الحروف: مفردات صغيرة جدًا ولا OOV، لكن التسلسلات طويلة جدًا. الوحدات الفرعية (subwords): الحل الوسط الذي تستخدمه النماذج اللغوية الحديثة.
- BPE has a trainer and an encoder. The trainer starts from characters or bytes and merges the most frequent adjacent pair k times, so |V| = initial symbols + k.لـ BPE جزءان: مدرِّب (trainer) ومرمِّز (encoder). يبدأ المدرِّب من الحروف أو البايتات ويدمج الزوج المتجاور الأكثر تكرارًا k مرة، لذلك |V| = عدد الرموز الأولية + k.
- On 'set new new renew reset renew' the first four merges are ne (4), new (4), _r (3), _re (3), giving 11 vocabulary items and a corpus of 15 symbols instead of 29.على 'set new new renew reset renew' تكون الدمجات الأربع الأولى ne (4) ثم new (4) ثم _r (3) ثم _re (3)، فينتج 11 عنصرًا في المفردات ومدوّنة من 15 رمزًا بدلًا من 29.
- Two of those four steps were ties. The pseudocode does not break ties; first-seen order gives ne, alphabetical order gives ew, so always state your rule.خطوتان من هذه الخطوات الأربع كانتا تعادلًا. الشيفرة الزائفة لا تحدد كيف يُكسر التعادل؛ ترتيب الظهور الأول يعطي ne والترتيب الأبجدي يعطي ew، فاذكر قاعدتك دائمًا.
- The leading space marker (GPT-2's Ġ, SentencePiece's ▁) makes _re a word-initial token. Sennrich's original code used an end-of-word suffix instead.وسم المسافة البادئ (Ġ في GPT-2 و▁ في SentencePiece) يجعل _re وحدة تقع في بداية الكلمة. أما شيفرة Sennrich الأصلية فاستخدمت لاحقة نهاية الكلمة بدلًا منه.
- The encoder replays merges in learned order and never counts frequencies. '_renewed' becomes _re new e d with no unknown token.يعيد المرمِّز تطبيق الدمجات بترتيب تعلّمها ولا يعدّ أي تكرارات أبدًا. تصبح '_renewed' هي _re new e d دون أي وحدة مجهولة.
- BPE units are frequent substrings, morphemes only by accident.وحدات BPE سلاسل فرعية متكررة، ولا تكون صرفيمات (morphemes) إلا بالمصادفة.
Sourcesالمصادر
- Speech and Language Processing, chapter 2: Words and Tokens (section 2.4, Byte-Pair Encoding)BookJurafsky and Martin, draft of August 19, 2026Same toy corpus as the slides, Figure 2.6 pseudocode, the encoder quote, 50k to 200k vocabulariesالمدوّنة الصغيرة نفسها التي في الشرائح، والشيفرة الزائفة في الشكل 2.6، واقتباس المرمِّز، ومفردات من 50k إلى 200k(opens in a new tab)(يفتح في تبويب جديد)
- Neural Machine Translation of Rare Words with Subword UnitsPaperSennrich, Haddow and Birch, ACL 2016BPE for segmentation, end-of-word symbol, |V| = initial + merges, Algorithm 1 minimal listingBPE للتقسيم، ورمز نهاية الكلمة، و|V| = الأولية + الدمجات، والقائمة المختصرة في الخوارزم 1(opens in a new tab)(يفتح في تبويب جديد)
- subword-nmt: learn_bpe.pyDocsRico SennrichPicks the best pair with max(stats, key=lambda x: (stats[x], x)), so ties go to the lexicographically largest pairيختار أفضل زوج بـ max(stats, key=lambda x: (stats[x], x))، لذلك يذهب التعادل إلى الزوج الأكبر معجميًا(opens in a new tab)(يفتح في تبويب جديد)
- A New Algorithm for Data CompressionArticlePhilip Gage, The C Users Journal 12(2), 1994The original byte pair compression, which stops when no pair repeatsضغط أزواج البايتات الأصلي، الذي يتوقف عندما لا يتكرر أي زوج(opens in a new tab)(يفتح في تبويب جديد)
- Language Models are Unsupervised Multitask Learners (section 2.2)PaperRadford et al., OpenAI, 2019Byte-level BPE: 256 base symbols versus 130,000 code points, vocabulary of 50,257, interpolation between word and character levelBPE على مستوى البايت: 256 رمزًا أساسيًا مقابل 130,000 من code points، ومفردات من 50,257، والتدرّج بين مستوى الكلمة ومستوى الحرف(opens in a new tab)(يفتح في تبويب جديد)
- Byte-Pair Encoding tokenization (LLM course, chapter 6)DocsHugging FaceFirst-encountered tie rule, encoding by replaying merges, [UNK] for an unseen characterقاعدة التعادل بأول ما يُصادَف، والترميز بإعادة تطبيق الدمجات، و[UNK] لحرف غير مرئي(opens in a new tab)(يفتح في تبويب جديد)
- Tokenizers: ComponentsDocsHugging FaceByteLevel pre-tokenizer with the Ġ prefix, Metaspace with ▁ (U+2581), no unknown token neededالمقطِّع المسبق ByteLevel مع البادئة Ġ، وMetaspace مع ▁ (U+2581)، ولا حاجة إلى وحدة مجهولة(opens in a new tab)(يفتح في تبويب جديد)
- Byte Pair Encoding is Suboptimal for Language Model PretrainingPaperBostrom and Durrett, Findings of EMNLP 2020Origin of the pseudocode figure; BPE units versus morphologyمصدر شكل الشيفرة الزائفة، ووحدات BPE مقابل الصرف(opens in a new tab)(يفتح في تبويب جديد)
Part 07: Tokenizers in practice and sentence segmentationالمُقسِّمات (Tokenizers) عمليا وتقسيم الجمل
Pre-tokenizers, byte-level BPE, multilingual fairness, SuperBPE, the design checklist for a real tokenizer, and the related problem of finding sentence boundaries.المُقسِّمات المسبقة (pre-tokenizers)، وBPE على مستوى البايت، والعدالة بين اللغات، وSuperBPE، وقائمة التحقق لتصميم مُقسِّم حقيقي، والمشكلة المرتبطة بإيجاد حدود الجمل.
4 concepts4 مفاهيم, ، slides 49-55الشرائح 49-55
Why this part mattersلماذا يهمّ هذا الجزء
Part 06 gave you the BPE algorithm on a toy corpus. This part shows what happens between that algorithm and the tokenizer inside GPT-4o or Llama 3, and why the answer matters for an Arabic NLP researcher more than for most people. An English-centric tokenizer can double or triple the cost of Arabic input and shortens the context window a model can spend on it, and every choice that causes that was made by a designer before training started.
We start from one real sentence and account for every split. That takes us through the pre-tokenizer, byte-level BPE and the reason a token can cut an Arabic letter in half. We then measure who pays for a shared vocabulary, look at SuperBPE, which lets merges cross spaces, and compress the whole design space into a checklist. The part closes with sentence segmentation, the first step of any parsing or translation pipeline, where one glyph, the period, can end a sentence, close an abbreviation or sit inside a number.
أعطاك الجزء 06 خوارزمية BPE على مدوّنة نصية صغيرة للتجربة. هذا الجزء يبيّن ما يحدث بين تلك الخوارزمية وبين الـ tokenizer الموجود داخل GPT-4o أو Llama 3، ولماذا يهمّ الجواب باحثًا في معالجة اللغة العربية أكثر مما يهمّ معظم الناس. فالـ tokenizer المتمحور حول الإنجليزية قد يضاعف تكلفة المدخلات العربية مرتين أو ثلاثًا، ويقلّص نافذة السياق التي يستطيع النموذج إنفاقها عليها، وكل قرار يسبّب ذلك اتخذه مصمّم قبل أن يبدأ التدريب.
نبدأ من جملة حقيقية واحدة ونفسّر كل قطع فيها. هذا يمرّ بنا على الـ pre-tokenizer، وعلى byte-level BPE، وعلى سبب قدرة الـ token على قطع حرف عربي إلى نصفين. ثم نقيس من يدفع ثمن المفردات المشتركة، وننظر في SuperBPE الذي يسمح لعمليات الدمج بعبور المسافات، ونضغط فضاء التصميم كله في قائمة مراجعة. ويُختم الجزء بتقسيم النص إلى جمل (sentence segmentation)، وهو الخطوة الأولى في أي خط تحليل نحوي أو ترجمة، حيث يمكن لرمز واحد، هو النقطة، أن ينهي جملة، أو يغلق اختصارًا، أو يقع داخل عدد.
By the end you canفي نهاية هذا الجزء ستستطيع
- Read a real tokenization such as the slide sentence and explain every split by a pre-tokenizer rule or a BPE merge.أن تقرأ تقطيعًا حقيقيًا مثل جملة الشريحة وتفسّر كل قطع فيه إما بقاعدة من قواعد الـ pre-tokenizer أو بعملية دمج (merge) في BPE.
- State the pros and the con of byte-level BPE with a concrete byte split of an Arabic letter.أن تذكر مزايا byte-level BPE وعيبه، مع مثال ملموس لتقطيع حرف عربي على مستوى البايتات.
- Compute a tokenization premium and name three costs of over-segmenting a low-resource language.أن تحسب tokenization premium وتسمّي ثلاث تكاليف لتقطيع لغة قليلة الموارد إلى أجزاء كثيرة (over-segmentation).
- Explain what SuperBPE changes in the BPE curriculum and what it trades away.أن تشرح ما الذي يغيّره SuperBPE في منهج تدريب BPE وما الذي يتنازل عنه مقابل ذلك.
- Walk the tokenizer design checklist and give one consequence for each choice.أن تمرّ على قائمة قرارات تصميم الـ tokenizer وتعطي نتيجة واحدة لكل قرار.
- Disambiguate a period with rule-based, statistical and Punkt-style evidence.أن تحسم معنى النقطة باستخدام القواعد اليدوية، والأدلة الإحصائية، وأدلة على طريقة Punkt.
Type the sentence Anyhow, she's seen Jane's 224123 flowers anyhow! into the tiktokenizer web app and pick GPT-4o. You get thirteen tokens, and Jurafsky and Martin use exactly this figure in SLP3 to introduce tokenizers in practice. Three of those tokens are worth staring at before any theory: Anyhow at the start is two tokens, Any and how, while the same word at the end is one token, ·anyhow. Jane's becomes ·Jane plus 's, but she's stays whole. And 224123 becomes 224 and 123, with a lone space token in front of it.
اكتب الجملة Anyhow, she's seen Jane's 224123 flowers anyhow! في تطبيق الويب tiktokenizer واختر GPT-4o. ستحصل على ثلاثة عشر token، وهذا بالضبط الشكل الذي يستخدمه Jurafsky وMartin في SLP3 لتقديم الـ tokenizers في التطبيق العملي. ثلاثة من هذه الـ tokens تستحق التأمل قبل أي نظرية: Anyhow في البداية صارت token اثنين، Any وhow، بينما الكلمة نفسها في النهاية token واحد، ·anyhow. وكلمة Jane's صارت ·Jane زائد 's، لكن she's بقيت كاملة. والعدد 224123 صار 224 و 123، ويسبقه token مستقل لمسافة وحدها.
| Tokenizerالـ Tokenizer | Vocabularyالمفردات | Tokensعدد الـ Tokens | Piecesالقطع |
|---|---|---|---|
| o200k (GPT-4o)o200k (GPT-4o) | 200K200K | 1313 | Any | how | , | ·she's | ·seen | ·Jane | 's | · | 224 | 123 | ·flowers | ·anyhow | !Any | how | , | ·she's | ·seen | ·Jane | 's | · | 224 | 123 | ·flowers | ·anyhow | ! |
| cl100k (GPT-4)cl100k (GPT-4) | ~100K~100K | 1414 | Any | how | , | ·she | 's | ·seen | ·Jane | 's | · | 224 | 123 | ·flowers | ·anyhow | !Any | how | , | ·she | 's | ·seen | ·Jane | 's | · | 224 | 123 | ·flowers | ·anyhow | ! |
| gpt2gpt2 | 50,25750,257 | 1414 | Any | how | , | ·she | 's | ·seen | ·Jane | 's | ·224 | 123 | ·flowers | ·any | how | !Any | how | , | ·she | 's | ·seen | ·Jane | 's | ·224 | 123 | ·flowers | ·any | how | ! |
Every one of these splits has a mechanical explanation, and none of it is in the BPE trainer from part 06. A shipping BPE tokenizer is a pipeline. Hugging Face documents it as four stages: normalization, pre-tokenization, the model (BPE, unigram or WordPiece), and post-processing that adds special tokens. The slide lists the families: most modern tokenizers are BPE-like, with unigram (Kudo 2018) and WordPiece (Schuster and Nakajima 2012) as the variants, and almost all of them sit behind a regex-based Pre-tokenizer.
لكل واحد من هذه التقطيعات تفسير آلي، ولا شيء منها موجود في مدرِّب BPE من الجزء 06. الـ BPE tokenizer المستخدم في المنتجات الحقيقية هو خط معالجة. توثّقه Hugging Face في أربع مراحل: التطبيع (normalization)، ثم pre-tokenization، ثم النموذج (BPE أو unigram أو WordPiece)، ثم معالجة لاحقة (post-processing) تضيف الرموز الخاصة. وتسرد الشريحة العائلات: معظم الـ tokenizers الحديثة شبيهة بـ BPE، مع unigram (Kudo 2018) و WordPiece (Schuster and Nakajima 2012) كنسختين بديلتين، وكلها تقريبًا تعمل خلف pre-tokenizer مبني على التعابير النمطية (regex).
The pre-tokenizer sets the fencesالـ pre-tokenizer يضع الأسوار
The pre-tokenizer is a Regular expression that cuts the text into pieces before any merge is counted. GPT-2 uses one pattern, and cl100k and o200k are tightened variants of it. Its alternatives are tried left to right at every position, which is why the order in the table below matters.
الـ pre-tokenizer هو regular expression يقطع النص إلى قطع قبل أن تُحسب أي عملية دمج. يستخدم GPT-2 نمطًا واحدًا، و cl100k و o200k نسختان مشدّدتان منه. تُجرَّب بدائله من اليسار إلى اليمين عند كل موضع، ولهذا يهمّ الترتيب في الجدول التالي.
The six alternatives of the GPT-2 pre-tokenizer regex, in orderالبدائل الستة في regex الـ pre-tokenizer الخاص بـ GPT-2، بالترتيب
- 's|'t|'re|'ve|'m|'ll|'d
- A clitic contraction becomes its own piece, so 's is split off Janeيصبح الاختصار الملحق (clitic) قطعة مستقلة، لذلك تنفصل 's عن Jane
- ?\p{L}+
- An optional space followed by letters: a word, with its leading space glued onمسافة اختيارية تتبعها حروف: كلمة، ومسافتها السابقة ملتصقة بها
- ?\p{N}+
- An optional space followed by any run of digits, unbounded in GPT-2; cl100k and o200k replace it with \p{N}{1,3}, three digits and no spaceمسافة اختيارية تتبعها سلسلة أرقام بأي طول، بلا حد في GPT-2؛ ويستبدلها cl100k و o200k بالنمط \p{N}{1,3}، أي ثلاثة أرقام كحد أقصى ودون مسافة
- ?[^\s\p{L}\p{N}]+
- An optional space followed by punctuation or symbols, so ! and , are piecesمسافة اختيارية تتبعها علامات ترقيم أو رموز، لذلك تكون ! و , قطعًا مستقلة
- \s+(?!\S)
- Runs of whitespace that are not followed by a non-space, which keeps one space for the next wordسلاسل المسافات البيضاء التي لا يتبعها حرف غير مسافة، وهذا يترك مسافة واحدة للكلمة التالية
- \s+
- Any remaining whitespace, such as newlinesأي مسافات بيضاء متبقية، مثل فواصل الأسطر
On We're 350 dogs! Um, lunch? this regex yields We, 're, ·350, ·dogs, !, ·Um, ,, ·lunch, ?, the example SLP3 prints as Figure 2.15. The consequence for BPE is the single most useful rule of this part. Pair counts during training and merges during encoding are computed inside each piece. A pair whose two halves sit in different pieces is never a candidate, so the pre-tokenizer sets an upper bound: the final tokens are always parts of its pieces, never unions of them.
على الجملة We're 350 dogs! Um, lunch? ينتج هذا الـ regex القطع We، 're، ·350، ·dogs، !، ·Um، ,، ·lunch، ?، وهو المثال الذي يطبعه SLP3 في Figure 2.15. والنتيجة بالنسبة لـ BPE هي أهم قاعدة في هذا الجزء. عدّ الأزواج أثناء التدريب وتطبيق عمليات الدمج (merges) أثناء الترميز يحدثان داخل كل قطعة على حدة. الزوج الذي يقع نصفاه في قطعتين مختلفتين لا يكون مرشحًا أبدًا، لذلك يضع الـ pre-tokenizer حدًا أعلى: الـ tokens النهائية دائمًا أجزاء من قطعه، ولا تكون أبدًا اتحادًا لقطعتين أو أكثر.
Now the three observations explain themselves. The leading space is part of the word piece, so ·anyhow and Anyhow are different byte strings. The lowercase, space-prefixed form is common in running text and earned a merge up to a whole token; the capitalized, sentence-initial form is rarer and stops at Any plus how. Position matters because the space marker is inside the piece. Second, the Clitic 's: under GPT-2 and cl100k the first regex alternative cuts every contraction into its own piece, so ·she and 's can never merge. o200k attaches the contraction to the word alternative, so the piece is ·she's, and since she's is a very frequent English word it has a token of its own, while ·Jane's does not and falls back to ·Jane plus 's. SLP3 states the same asymmetry: clitics are segmented off proper nouns like Jane but counted as part of frequent words like she's. Third, the digits: cl100k and o200k replace ·?\p{N}+ with \p{N}{1,3}, which caps any digit run at three per piece and, because the new alternative has no optional space, leaves the space before 224123 as a piece of its own (token id 220 in both vocabularies).
الآن تفسّر الملاحظات الثلاث نفسها بنفسها. المسافة السابقة جزء من قطعة الكلمة، لذلك ·anyhow و Anyhow سلسلتا بايتات مختلفتان. الشكل الصغير المسبوق بمسافة شائع في النص الجاري، فاستحق عمليات دمج أوصلته إلى token كامل؛ أما الشكل الذي يبدأ بحرف كبير في أول الجملة فأندر، فيتوقف عند Any زائد how. الموضع يهمّ لأن علامة المسافة (space marker) موجودة داخل القطعة. ثانيًا، الـ clitic 's: في GPT-2 و cl100k يقطع البديل الأول في الـ regex كل اختصار (contraction) إلى قطعة خاصة به، فلا يمكن أبدًا دمج ·she و 's. أما o200k فيلحق الاختصار ببديل الكلمة، فتكون القطعة ·she's، وبما أن she's كلمة إنجليزية شائعة جدًا فلها token خاص بها، بينما ·Jane's ليس لها، فترجع إلى ·Jane زائد 's. ويذكر SLP3 عدم التماثل نفسه: الـ clitics تُفصل عن أسماء العلم مثل Jane لكنها تُحسب جزءًا من الكلمات الشائعة مثل she's. ثالثًا، الأرقام: يستبدل cl100k و o200k النمط ·?\p{N}+ بالنمط \p{N}{1,3}، الذي يحدّ أي سلسلة أرقام بثلاثة في القطعة الواحدة، ولأن البديل الجديد لا يتضمن مسافة اختيارية، تبقى المسافة قبل 224123 قطعة مستقلة (رقم الـ token هو 220 في المفردتين كلتيهما).
Recall
What does a pre-tokenizer do, and why do BPE merges normally not cross its pieces?ماذا يفعل الـ pre-tokenizer، ولماذا لا تعبر عمليات الدمج في BPE قطعه في العادة؟
Vocabulary size is a parameter, not a resultحجم المفردات معامل يُختار، لا نتيجة تخرج من الخوارزمية
The Vocabulary of a BPE tokenizer is its base symbols plus one entry per merge, and the trainer stops after k merges. Nothing in the algorithm chooses k. The slide gives a typical range of 30k to 100k; real systems now go further, and SLP3 quotes 50,000, 100,000 or even 200,000.
المفردات (vocabulary) في BPE tokenizer هي رموزه الأساسية زائد مدخل واحد لكل عملية دمج، والمدرِّب يتوقف بعد k عملية دمج. لا شيء في الخوارزمية يختار k. تعطي الشريحة مدى نموذجيًا من 30k إلى 100k؛ والأنظمة الحقيقية اليوم تذهب أبعد من ذلك، ويذكر SLP3 50,000 أو 100,000 أو حتى 200,000.
Vocabulary sizes shipped with well-known modelsأحجام المفردات التي تأتي مع نماذج معروفة
- GPT-2 (byte-level BPE)
- 50,25750,257
- BERT base (WordPiece)
- 30,52230,522
- Llama 3 (BPE)
- 128K128K
- GPT-4o, o200k (byte-level BPE)
- 200K200K
A larger vocabulary buys shorter sequences and more whole-word tokens, at the cost of a bigger embedding table and rarer training examples per token. The number is chosen, and the next concept shows that who benefits from that budget is also chosen.
المفردات الأكبر تشتري تسلسلات أقصر و tokens أكثر تمثل كلمات كاملة، مقابل جدول embeddings أكبر وأمثلة تدريب أندر لكل token. الرقم يُختار، والمفهوم التالي يبيّن أن من يستفيد من هذه الميزانية يُختار أيضًا.
Byte-level BPE: 256 symbols and no unknown characterByte-level BPE: 256 رمزًا ولا يوجد حرف مجهول
The base symbols of the toy BPE in part 06 were characters. Radford et al. (2019) explain why GPT-2 did not do that: a base vocabulary of Unicode code points would exceed 130,000 entries before a single merge, while a byte-level version needs only 256. So GPT-2 runs merges over the UTF-8 bytes of the text. That is Byte-level tokenization, and its three advantages on the slide follow from one fact: every string in every script is a sequence of bytes from a set of 256, so there is no OOV character, any script works, and noisy text with typos or stray symbols still tokenizes. GPT-2 also adds a rule that prevents merges across character categories, with an exception for spaces, so that dog., dog! and dog? do not each become a token.
الرموز الأساسية في BPE التجريبي في الجزء 06 كانت حروفًا. ويشرح Radford et al. (2019) لماذا لم يفعل GPT-2 ذلك: مفردات أساسية من نقاط الترميز (code points) في Unicode ستتجاوز 130,000 مدخل قبل أي عملية دمج، بينما النسخة القائمة على البايتات تحتاج 256 فقط. لذلك يجري GPT-2 عمليات الدمج على بايتات UTF-8 للنص. هذا هو byte-level tokenization، ومزاياه الثلاث على الشريحة تنبع من حقيقة واحدة: كل سلسلة في كل نظام كتابة هي تسلسل من بايتات تنتمي إلى مجموعة من 256، فلا يوجد حرف OOV (خارج المفردات)، وأي نظام كتابة يعمل، والنص المليء بالأخطاء الإملائية أو الرموز الشاردة يُقطَّع رغم ذلك. ويضيف GPT-2 أيضًا قاعدة تمنع الدمج عبر فئات الحروف المختلفة، مع استثناء للمسافات، حتى لا تصبح كل من dog. و dog! و dog? token مستقلًا.
The con on the slide, that tokens may be less interpretable, is not abstract for Arabic. Arabic letters live in U+0600 to U+06FF, inside the two-byte range of UTF-8, so every letter is two bytes and a merge boundary can fall between them.
العيب المذكور على الشريحة، أن الـ tokens قد تكون أقل قابلية للتفسير، ليس أمرًا مجردًا بالنسبة للعربية. فالحروف العربية تقع في المدى من U+0600 إلى U+06FF، داخل نطاق البايتين في UTF-8، لذلك كل حرف بايتان، ويمكن أن يقع حدّ الدمج بينهما.
Worked exampleمثال محلول
One Arabic word through three byte-level tokenizersكلمة عربية واحدة عبر ثلاثة tokenizers على مستوى البايت
Code pointsنقاط الترميز
كتاب is four code points: U+0643 kaf, U+062A ta, U+0627 alif, U+0628 ba.كتاب أربع نقاط ترميز: U+0643 الكاف، U+062A التاء، U+0627 الألف، U+0628 الباء.UTF-8 bytesبايتات UTF-8
Each is two bytes: D9 83, D8 AA, D8 A7, D8 A8. Eight bytes, so the base encoding is eight symbols.كل منها بايتان: D9 83، D8 AA، D8 A7، D8 A8. ثمانية بايتات، فالترميز الأساسي ثمانية رموز.Apply each vocabulary's mergesطبّق عمليات الدمج الخاصة بكل مفردات
Tokenizerالـ Tokenizer Tokensعدد الـ Tokens Byte groupsمجموعات البايتات What a human seesما يراه الإنسان gpt2gpt2 55 D9 | 83 | D8 AA | D8 A7 D8 | A8D9 | 83 | D8 AA | D8 A7 D8 | A8 Kaf split in two, fourth token straddles alif and the lead byte of baالكاف مقسومة إلى نصفين، والـ token الرابع يمتد على الألف والبايت الأول من الباء cl100kcl100k 33 D9 83 | D8 AA | D8 A7 D8 A8D9 83 | D8 AA | D8 A7 D8 A8 Every token is whole lettersكل token يتكون من حروف كاملة o200ko200k 11 D9 83 D8 AA D8 A7 D8 A8D9 83 D8 AA D8 A7 D8 A8 The whole word is one tokenالكلمة كلها token واحد Interpretability is repaired by merges, not by the baseقابلية التفسير تصلحها عمليات الدمج، لا الأساس
Under gpt2 the letter kaf is D9 in one token and 83 in another, and the fourth token holds alif plus half of ba. The larger vocabularies had enough Arabic in training to merge whole letters and then the whole word. The base alphabet never changed; the merge budget did.في gpt2 يكون حرف الكاف D9 في token و 83 في token آخر، والـ token الرابع يحمل الألف زائد نصف الباء. أما المفردات الأكبر فقد رأت في التدريب ما يكفي من العربية لتدمج حروفًا كاملة ثم الكلمة كلها. الأبجدية الأساسية لم تتغير؛ الذي تغيّر هو ميزانية الدمج.
Try both ideas yourself. The playground below runs the GPT-2 regex on any sentence, replays a small merge list inside each piece and reports which merges the fences blocked, and shows the UTF-8 bytes with the token brackets measured above.
جرّب الفكرتين بنفسك. الأداة التفاعلية أدناه تشغّل regex الخاص بـ GPT-2 على أي جملة، وتعيد تطبيق قائمة دمج صغيرة داخل كل قطعة وتخبرك بعمليات الدمج التي منعتها الأسوار، وتعرض بايتات UTF-8 مع أقواس الـ tokens التي قسناها أعلاه.
GPT-2 rules: digits unbounded, with the leading space attached, contractions split into their own piece. Vocabulary about 50,257 tokens.قواعد GPT-2: الأرقام بلا حد، مع إلصاق المسافة السابقة بها، والاختصارات مثل 's تُفصل في قطعة خاصة بها. حجم المفردات نحو 50,257 رمز.
The regex is the GPT-2 pattern with the digit and contraction rules switched per preset. Non-ASCII characters enter the merge stage as their UTF-8 bytes, exactly as in byte-level BPE. The merge list is a short illustrative one, not the real vocabulary, so token counts in the Pieces and Merges views can differ from tiktoken by a token or two. The byte brackets and the token count shown with them are real measurements.التعبير النمطي هو نمط GPT-2، مع تبديل قاعدتي الأرقام والاختصارات بحسب الإعداد المختار. تدخل المحارف غير ASCII مرحلة الدمج على شكل بايتات UTF-8، تمامًا كما في byte-level BPE. قائمة الدمج هنا قصيرة وتوضيحية وليست المفردات الحقيقية، لذلك قد يختلف عدد الرموز في عرضي القطع والدمج عن tiktoken برمز أو رمزين. أما أقواس البايتات وعدد الرموز المعروض معها فهي قياسات حقيقية.
Quick checkاختبار سريع
Why do BPE merges normally stop at the boundaries a pre-tokenizer produces?لماذا تتوقف عمليات الدمج في BPE عادةً عند الحدود التي ينتجها الـ pre-tokenizer؟
Quick checkاختبار سريع
In byte-level BPE, what can happen to a two-byte character such as Arabic kaf?في byte-level BPE، ماذا يمكن أن يحدث لحرف من بايتين مثل الكاف العربية؟
Recall
Give two pros and one con of byte-level BPE, with a concrete example of the con.اذكر ميزتين وعيبًا واحدًا لـ byte-level BPE، مع مثال ملموس على العيب.
Take one meaning and write it twice. The book is on the table. is six words and a period, and its Arabic translation الكتاب على الطاولة. is three words and a period. Run both through cl100k and the English costs seven tokens while the Arabic costs twelve. Same meaning, half the words, nearly twice the tokens.
خذ معنى واحدًا واكتبه مرتين. The book is on the table. ست كلمات ونقطة، وترجمتها العربية الكتاب على الطاولة. ثلاث كلمات ونقطة. مرّر الاثنتين عبر cl100k فتكلّف الإنجليزية سبعة tokens بينما تكلّف العربية اثني عشر. المعنى نفسه، ونصف عدد الكلمات، وتقريبًا ضعف عدد الـ tokens.
| Textالنص | Wordsالكلمات | cl100k tokenstokens في cl100k | o200k tokenstokens في o200k | Tokens per word (cl100k)tokens لكل كلمة (cl100k) |
|---|---|---|---|---|
| The book is on the table.The book is on the table. | 66 | 77 | 77 | 1.171.17 |
| الكتاب على الطاولة.الكتاب على الطاولة. | 33 | 1212 | 66 | 4.04.0 |
The o200k column shows the fix: a 200K vocabulary trained on more multilingual text spent merges on Arabic, so كتاب became one token and the Arabic sentence dropped to 6 tokens. The premium comes from how the budget was spent, not from the script.
عمود o200k يبيّن الحل: مفردات بحجم 200K دُرّبت على نص متعدد اللغات أكثر أنفقت عمليات دمج على العربية، فصارت كتاب token واحدًا ونزلت الجملة العربية إلى 6 tokens. الـ premium ينتج عن طريقة إنفاق الميزانية، لا عن نظام الكتابة نفسه.
The cause is the merge budget of the previous concept. BPE spends its k merges where the frequencies are, and English dominates the training text of most large models. English words therefore become single tokens while Arabic words fragment into letter-sized byte tokens. SLP3 puts it plainly: multilingual tokenizers tend to use most of their tokens for English, and other languages get poorer representations. The shared Vocabulary is a budget, and a shared budget favors whoever was most frequent when it was allocated. That is the slide's first two bullets in one sentence: shared vocabularies favor high-resource languages, so low-resource languages are over-segmented into longer sequences.
السبب هو ميزانية الدمج من المفهوم السابق. ينفق BPE عمليات الدمج الـ k حيث توجد الترددات العالية، والإنجليزية تهيمن على نصوص تدريب معظم النماذج الكبيرة. لذلك تصبح الكلمات الإنجليزية tokens مفردة، بينما تتفتت الكلمات العربية إلى tokens بحجم حرف أو بايت. ويقولها SLP3 بوضوح: الـ tokenizers متعددة اللغات تميل إلى استخدام معظم tokens الخاصة بها للإنجليزية، وتحصل اللغات الأخرى على تمثيلات أضعف. المفردات (vocabulary) المشتركة ميزانية، والميزانية المشتركة تحابي من كان الأكثر ترددًا وقت توزيعها. هذا هو البندان الأولان في الشريحة في جملة واحدة: المفردات المشتركة تحابي اللغات عالية الموارد، لذلك تُقطَّع اللغات قليلة الموارد تقطيعًا زائدًا (over-segmented) إلى تسلسلات أطول.
Petrov et al. (2023) turn this into a number. Take parallel sentences, tokenize both, and divide the length for language A by the length for language B. They call the ratio the tokenization premium of A relative to B.
يحوّل Petrov et al. (2023) هذا إلى رقم. خذ جملًا متوازية، وقطّع الاثنتين، واقسم الطول في اللغة A على الطول في اللغة B. يسمّون هذه النسبة tokenization premium للغة A نسبةً إلى B.
| Languageاللغة | GPT-2 / RoBERTa tokenizertokenizer الخاص بـ GPT-2 / RoBERTa | ChatGPT / GPT-4 (cl100k)ChatGPT / GPT-4 (cl100k) | ByT5 (bytes)ByT5 (بايتات) |
|---|---|---|---|
| Portugueseالبرتغالية | 1.941.94 | 1.481.48 | n/aغير متاح |
| Germanالألمانية | 2.142.14 | 1.581.58 | n/aغير متاح |
| Chinese (Simplified)الصينية (المبسطة) | 3.213.21 | 1.911.91 | 0.930.93 |
| Standard Arabicالعربية الفصحى | 4.404.40 | 3.043.04 | 1.601.60 |
| Burmeseالبورمية (Burmese) | 16.8916.89 | 11.7011.70 | 3.513.51 |
| Shanلغة الشان (Shan) | 18.7618.76 | 15.0515.05 | 3.943.94 |
Arabic pays 4.40 times the English token count under the GPT-2 vocabulary and 3.04 under cl100k. Shan and Burmese pay over fifteen and eleven times. The ByT5 column shows that even byte and character models, which have no merges at all, are unequal because scripts differ in bytes per character: Petrov et al. report up to fifteen times difference for subword models and over four times between the byte encodings of Burmese or Tibetan and Chinese. Ahia et al. (2023) measured the same effect on ChatGPT across 22 languages, with some needing five times as many tokens as others, and name two causes: how much of the language was in the pretraining data, and inherent properties of the language and its script. In their analysis of the BLOOMZ tokenizer they flag Arabic as an outlier with more tokens than some other mid-resourced languages.
تدفع العربية 4.40 ضعف عدد tokens الإنجليزية تحت مفردات GPT-2، و 3.04 تحت cl100k. وتدفع لغتا Shan و Burmese أكثر من خمسة عشر وأحد عشر ضعفًا على الترتيب. ويبيّن عمود ByT5 أن حتى نماذج البايتات والحروف، التي لا تملك أي عمليات دمج (merges) على الإطلاق، غير متساوية لأن أنظمة الكتابة تختلف في عدد البايتات لكل حرف: يذكر Petrov et al. فرقًا يصل إلى خمسة عشر ضعفًا في نماذج الـ subword، وأكثر من أربعة أضعاف بين ترميزات البايت للغة Burmese أو Tibetan واللغة الصينية. وقاس Ahia et al. (2023) الأثر نفسه على ChatGPT عبر 22 لغة، فبعضها احتاج خمسة أضعاف الـ tokens التي احتاجتها لغات أخرى، وسمّوا سببين: كم كان حجم اللغة في بيانات التدريب المسبق، والخصائص الذاتية للغة ونظام كتابتها. وفي تحليلهم لـ tokenizer الخاص بـ BLOOMZ أشاروا إلى العربية كحالة شاذة تحتاج tokens أكثر من بعض اللغات الأخرى متوسطة الموارد.
Three bills for one over-segmented sentenceثلاث فواتير لجملة واحدة مقطّعة تقطيعًا زائدًا
- Compute. Every layer processes every token, so three times the tokens is at least three times the work, and self-attention, whose cost grows with the square of sequence length, makes long inputs worse still.الحساب. كل طبقة تعالج كل token، فثلاثة أضعاف الـ tokens تعني ثلاثة أضعاف العمل على الأقل، والـ self-attention، الذي تنمو تكلفته مع مربع طول التسلسل، يجعل المدخلات الطويلة أسوأ من ذلك.
- Context. A window of fixed token length holds a third as many Arabic words as English words. Ahia et al. note that fewer in-context examples fit, which directly lowers few-shot quality.السياق. النافذة ذات الطول الثابت بالـ tokens تتسع لثلث عدد الكلمات العربية مقارنة بالكلمات الإنجليزية. ويلاحظ Ahia et al. أن عدد الأمثلة التي تتسع لها النافذة (in-context examples) يقلّ، وهذا يخفض جودة الـ few-shot مباشرة.
- Money and quality. APIs bill per token, so Ahia et al. conclude that speakers of many languages are overcharged while obtaining poorer results, and SLP3 adds that fragmented tokens give poorer representations of meaning.المال والجودة. واجهات الـ API تحاسب لكل token، لذلك يخلص Ahia et al. إلى أن متحدثي لغات كثيرة يدفعون أكثر بينما يحصلون على نتائج أضعف، ويضيف SLP3 أن الـ tokens المفتتة تعطي تمثيلات أضعف للمعنى.
Premium under ArabicBERT, relative to Arabic (Petrov et al. 2023, Section 4.2)الـ premium تحت ArabicBERT نسبةً إلى العربية (Petrov et al. 2023، القسم 4.2)
- Kanuri (Arabic script)الكانورية (بالحرف العربي)
- 1.271.27
- Acehnese (Arabic script)الأتشيهية (بالحرف العربي)
- 1.731.73
- Englishالإنجليزية
- 1.821.82
The slide's third bullet, that tokenizer design affects fairness and performance, is an engineering decision you can make differently.
البند الثالث في الشريحة، أن تصميم الـ tokenizer يؤثر في العدالة والأداء، هو قرار هندسي يمكنك أن تتخذه بشكل مختلف.
Quick checkاختبار سريع
Under an English-heavy vocabulary, why does Arabic text become more tokens than its English translation?تحت مفردات تهيمن عليها الإنجليزية، لماذا يصبح النص العربي tokens أكثر من ترجمته الإنجليزية؟
Recall
Why does a low-resource language get longer token sequences under a shared vocabulary, and what are two consequences?لماذا تحصل اللغة قليلة الموارد على تسلسلات tokens أطول تحت مفردات مشتركة، وما نتيجتان لذلك؟
SuperBPE: letting merges cross the spaceSuperBPE: السماح لعمليات الدمج بعبور المسافة
If fences limit how much a vocabulary can compress, one way to compress more is to remove a fence late in training. Liu et al. (2025) call this SuperBPE: a pretokenization curriculum for BPE that first learns subwords under the ordinary whitespace fences, then continues with merges that are allowed to bridge whitespace and produce superwords. The figure on the slide is their example. Ordinary BPE gives By | the | way | , | I | am | a | fan | of | the | Milky | Way | ., thirteen tokens. SuperBPE gives By the way | , I am | a | fan | of the | Milky Way | ., seven.
إذا كانت الأسوار تحدّ من مقدار ما تستطيع المفردات ضغطه، فإحدى طرق الضغط أكثر هي إزالة سور في مرحلة متأخرة من التدريب. يسمّي Liu et al. (2025) هذا SuperBPE: منهج pretokenization متدرّج لـ BPE يتعلّم أولًا الـ subwords تحت أسوار المسافات المعتادة، ثم يواصل بعمليات دمج مسموح لها بعبور المسافات فتنتج كلمات فائقة (superwords). الشكل في الشريحة هو مثالهم. يعطي BPE العادي By | the | way | , | I | am | a | fan | of | the | Milky | Way | .، أي ثلاثة عشر token. ويعطي SuperBPE By the way | , I am | a | fan | of the | Milky Way | .، أي سبعة.
The gain is the slide's stated goal, efficiency. At a 200K vocabulary SuperBPE beats ordinary BPE on every measure the authors report, so the extra training stage pays for itself.
المكسب هو الهدف المعلن في الشريحة: الكفاءة. عند مفردات بحجم 200K يتفوق SuperBPE على BPE العادي في كل مقياس ذكره المؤلفون، فمرحلة التدريب الإضافية تدفع ثمنها بنفسها.
SuperBPE at 200K vs BPE (Liu et al. 2025)SuperBPE عند 200K مقارنة بـ BPE (Liu et al. 2025)
- Token reduction vs BPEانخفاض عدد الـ tokens مقارنة بـ BPE
- 33%33%
- Average over 30 downstream tasksالمتوسط على 30 مهمة لاحقة
- +4.0 points+4.0 نقطة
- MMLU
- +8.2 points+8.2 نقطة
- Inference computeحساب الاستدلال (inference)
- -27%-27%
SLP3 mentions BoundlessBPE (Schmidt et al. 2025) as a sibling method with the same idea.
يذكر SLP3 طريقة BoundlessBPE (Schmidt et al. 2025) كطريقة شقيقة تقوم على الفكرة نفسها.
The tradeoff is the slide's third bullet, Compositionality. Under ordinary BPE, Way in Milky Way and way in By the way share visible structure with every other use of the word. Once Milky Way is one token, the model must learn its relation to way from scratch, and a rare phrase that almost matches a superword is split in an unfamiliar way. Fewer tokens means less shared structure across tokens.
المقايضة هي البند الثالث في الشريحة: التركيبية (compositionality). تحت BPE العادي، تشترك Way في Milky Way و way في By the way في بنية ظاهرة مع كل استخدام آخر للكلمة. وبمجرد أن تصبح Milky Way token واحدًا، يجب على النموذج أن يتعلّم علاقتها بـ way من الصفر، والعبارة النادرة التي تكاد تطابق كلمة فائقة تُقطَّع بطريقة غير مألوفة. tokens أقل تعني بنية مشتركة أقل بين الـ tokens.
Every surprise in this part came from a switch someone set before training: whether the space belongs to the next word, whether digits are capped, whether contractions split, how many merges to make, which languages got the budget. The slide collects those switches into a checklist. Treat each line as a question with a consequence, because that is how an exam or a design review will ask it.
كل مفاجأة في هذا الجزء جاءت من مفتاح ضبطه شخص ما قبل التدريب: هل المسافة تنتمي إلى الكلمة التالية، وهل الأرقام محدودة، وهل تُفصل الاختصارات، وكم عملية دمج تُجرى، وأي اللغات حصلت على الميزانية. تجمع الشريحة هذه المفاتيح في قائمة مراجعة. تعامل مع كل سطر كسؤال له نتيجة، لأن هذه هي الطريقة التي سيُطرح بها في الامتحان أو في مراجعة تصميم.
The tokenizer design checklist, each choice with its consequenceقائمة مراجعة تصميم الـ tokenizer، كل قرار مع نتيجته
- Pre-tokenizationالـ pre-tokenization
- Split on whitespace, and what happens to the space? Drop it (BERT), glue it onto the next piece (·world in GPT-2) or keep it as an explicit symbol (▁ in SentencePiece). The answer decides whether ·anyhow and anyhow can ever share a token, fixes the fences that merges cannot cross, and decides whether detokenization can restore the original text exactly. SuperBPE removes the fence in its second stage.هل نقسم على المسافات، وماذا يحدث للمسافة؟ نرميها (BERT)، أو نلصقها بالقطعة التالية (·world في GPT-2)، أو نحتفظ بها كرمز صريح (▁ في SentencePiece). الجواب يحدد هل يمكن أن تشترك ·anyhow و anyhow في token واحد أصلًا، ويثبّت الأسوار التي لا تستطيع عمليات الدمج عبورها، ويحدد هل يستطيع الـ detokenization استعادة النص الأصلي بدقة. ويزيل SuperBPE هذا السور في مرحلته الثانية.
- Normalizationالتطبيع (normalization)
- NFC or NFD, lowercasing, accent stripping? BERT uncased runs NFD, lowercase and strip-accents, so Héllò becomes hello and case and diacritics are gone for good. GPT-style tokenizers keep them, at the cost of separate entries for Apple and apple.NFC أم NFD، وهل نحوّل إلى أحرف صغيرة، وهل نزيل علامات التشكيل؟ نسخة BERT uncased تطبّق NFD ثم التحويل إلى أحرف صغيرة ثم إزالة علامات التشكيل، فتصبح Héllò هي hello وتضيع حالة الأحرف وعلامات التشكيل نهائيًا. أما الـ tokenizers على طريقة GPT فتحتفظ بها، مقابل مدخلين منفصلين لـ Apple و apple.
- Special tokensالرموز الخاصة (special tokens)
- <BOS>, <EOS>, <UNK>, <PAD>. A byte-level tokenizer never needs <UNK>. GPT-2 has one special token, <|endoftext|> at id 50256; BERT adds [CLS] and [SEP] in post-processing.<BOS>، <EOS>، <UNK>، <PAD>. الـ tokenizer الذي يعمل على مستوى البايت (byte-level) لا يحتاج أبدًا إلى <UNK>. لدى GPT-2 رمز خاص واحد، <|endoftext|> برقم 50256؛ ويضيف BERT الرمزين [CLS] و [SEP] في المعالجة اللاحقة.
- Numbersالأرقام
- Cap digit runs (\p{N}{1,3}) or split every digit? Decides whether 224123 is two tokens or six, and shapes how well the model does arithmetic on numbers it has never seen whole.هل نحدّ سلاسل الأرقام (\p{N}{1,3}) أم نفصل كل رقم على حدة؟ هذا يحدد هل يكون 224123 token اثنين أم ستة، ويؤثر في جودة الحساب الذي يجريه النموذج على أعداد لم يرها كاملة من قبل.
- URLs and emojiالروابط والـ emoji
- Byte fallback keeps them representable: gpt2 encodes 😀 (F0 9F 98 80) as F0 9F 98 plus 80. A URL becomes a long run of punctuation and word pieces unless a rule keeps it whole.الرجوع إلى البايتات (byte fallback) يُبقيها قابلة للتمثيل: يرمّز gpt2 الرمز 😀 (F0 9F 98 80) على شكل F0 9F 98 زائد 80. والرابط (URL) يصبح سلسلة طويلة من علامات الترقيم وأجزاء الكلمات ما لم توجد قاعدة تُبقيه كاملًا.
- Multilingual coverage and biasالتغطية متعددة اللغات والانحياز
- How much of the vocabulary budget each language gets. An English-heavy budget gives Arabic a premium of 3.04 under cl100k and Shan 15.05, which is the fairness cost of the previous concept.كم تحصل كل لغة من ميزانية المفردات. الميزانية التي تهيمن عليها الإنجليزية تعطي العربية premium قدره 3.04 تحت cl100k، ولغة Shan 15.05، وهذه هي تكلفة العدالة في المفهوم السابق.
Three answers to the spaces questionثلاث إجابات عن سؤال المسافات
The slide's pre-tokenization line asks one question with three real answers. Once the text is split on whitespace, what happens to the space? The choice fixes the Space marker (end-of-word marker) convention the model will live with, and it decides whether detokenization can recover the original string.
سطر الـ pre-tokenization في الشريحة يطرح سؤالًا واحدًا له ثلاث إجابات حقيقية. بعد تقسيم النص على المسافات، ماذا يحدث للمسافة؟ هذا القرار يثبّت اصطلاح علامة المسافة (space marker) الذي سيعيش معه النموذج، ويحدد ما إذا كان الـ detokenization قادرًا على استعادة السلسلة الأصلية.
| Tokenizerالـ Tokenizer | Piecesالقطع | Where the space goesأين تذهب المسافة | Detokenizationالـ Detokenization |
|---|---|---|---|
| BERTBERT | Hello | worldHello | world | Space discardedتُرمى المسافة | Not reversible: detokenization cannot say where the spaces wereغير قابل للعكس: لا يستطيع الـ detokenization أن يعرف أين كانت المسافات |
| GPT-2GPT-2 | Hello | ·worldHello | ·world | Space glued onto the next pieceتلتصق المسافة بالقطعة التالية | Reversible: every piece carries its leading spaceقابل للعكس: كل قطعة تحمل مسافتها السابقة |
| SentencePieceSentencePiece | ▁Hello | ▁world▁Hello | ▁world | Space kept as an explicit ▁ symbolتُحفظ المسافة كرمز صريح ▁ | Losslessly reversible: replace ▁ by a space and the original text is restoredقابل للعكس دون أي فقد: استبدل ▁ بمسافة فيعود النص الأصلي كما كان |
BERT throws the space away, which keeps the alphabet small but makes the token stream lossy: don't and the three tokens don, ', t cannot be told apart from a hyphenless spelling once the spaces are gone. GPT-2 glues the space onto the following piece, so ·world and world are different entries and the original spacing is recoverable. SentencePiece keeps the space as an explicit ▁ symbol, which is exactly reversible: swapping ▁ back to a space restores the input byte for byte. It also means the regex fences from the first concept apply to a text where spaces are ordinary symbols, so SentencePiece can in principle learn a merge that crosses what used to be a word boundary.
يرمي BERT المسافة، وهذا يبقي الأبجدية صغيرة لكنه يجعل تدفق الـ tokens فاقدًا للمعلومات: don't والـ tokens الثلاثة don و ' و t لا يمكن التمييز بينها وبين كتابة بلا شرطة بمجرد أن تختفي المسافات. أما GPT-2 فيلصق المسافة بالقطعة التالية، فتكون ·world و world مدخلين مختلفين ويمكن استعادة المسافات الأصلية. ويحتفظ SentencePiece بالمسافة كرمز صريح ▁، وهذا قابل للعكس تمامًا: استبدال ▁ بمسافة يعيد المدخل بايتًا ببايت. ويعني ذلك أيضًا أن أسوار الـ regex من المفهوم الأول تنطبق على نص تكون فيه المسافات رموزًا عادية، لذلك يمكن لـ SentencePiece من حيث المبدأ أن يتعلّم عملية دمج تعبر ما كان في السابق حدًا بين كلمتين.
Quick checkاختبار سريع
Which checklist choice makes Héllò and hello identical?أي قرار في القائمة يجعل Héllò و hello متطابقتين؟
The rule that ties the list together is that all of it is frozen with the model. The Unicode normalization form, the case folding decision, the Special tokens and the Pre-tokenizer regex are recorded in the tokenizer file, and Hugging Face's pipeline documentation warns that changing the normalizer or the pre-tokenizer requires retraining the tokenizer, which in turn means the embeddings of the language model no longer match. You cannot fix an English-centric tokenizer after the fact; you choose it before the first gradient step.
القاعدة التي تربط القائمة كلها هي أن كل ما فيها يُجمَّد مع النموذج. شكل التطبيع في Unicode (Unicode normalization)، وقرار توحيد حالة الأحرف (case folding)، و الرموز الخاصة (special tokens)، و regex الـ pre-tokenizer، كلها مسجلة في ملف الـ tokenizer، وتحذّر وثائق خط المعالجة في Hugging Face من أن تغيير الـ normalizer أو الـ pre-tokenizer يتطلب إعادة تدريب الـ tokenizer، وهذا بدوره يعني أن الـ embeddings في النموذج اللغوي لم تعد متطابقة معه. لا يمكنك إصلاح tokenizer متمحور حول الإنجليزية بعد الحدث؛ أنت تختاره قبل أول خطوة gradient.
Recall
Name four items of the tokenizer design checklist and one consequence for any one of them.سمِّ أربعة بنود من قائمة تصميم الـ tokenizer ونتيجة واحدة لأي واحد منها.
Here is a passage with six periods, one question mark and one exclamation mark: Dr. Ahmad arrived at 5 p.m. on Monday. He paid 3.50 riyals. Was it enough? Yes! It contains four sentences. A splitter that cuts at every period would produce seven fragments and would glue the last two sentences together. Decide for yourself which marks end a sentence before reading the rules.
إليك مقطعًا فيه ست نقاط، وعلامة استفهام واحدة، وعلامة تعجب واحدة: Dr. Ahmad arrived at 5 p.m. on Monday. He paid 3.50 riyals. Was it enough? Yes! يحتوي على أربع جمل. الأداة التي تقطع عند كل نقطة ستنتج سبع شظايا، وستلصق الجملتين الأخيرتين معًا. قرّر بنفسك أي العلامات تنهي جملة قبل أن تقرأ القواعد.
Click a punctuation mark to cycle it through sentence boundary, not a boundary, and undecided. Then check. Each verdict names the rule and the feature that decided it.انقر على علامة ترقيم لتتنقل بين ثلاث حالات: حد جملة، وليست حدًا، ولم يُحسم. ثم تحقّق. يذكر كل حكم القاعدة والسمة التي حسمته.
Dr Ahmad arrived at 5 pm on Monday He paid 350 riyals Was it enough Yes
A double bar marks a sentence boundary, a middle dot marks a period that belongs to its word or number. After checking, an accent ring means correct and a teal ring with strikethrough means wrong or undecided.يدل الشريط المزدوج على حد جملة، وتدل النقطة الوسطى على نقطة تنتمي إلى كلمتها أو عددها. بعد التحقق، تعني الحلقة باللون المميز إجابة صحيحة، وتعني الحلقة الخضراء المزرقة مع الشطب إجابة خاطئة أو غير محسومة.
Sentence segmentation is the task of finding sentence boundaries, and the slide names its usual customers: parsing and machine translation, both of which take one sentence at a time. SLP3 states the difficulty exactly. Question marks and exclamation points are relatively unambiguous markers of sentence boundaries. The period is ambiguous between a sentence boundary and an abbreviation marker such as Dr. or Inc., and it can even do both at once: when a sentence ends in Inc., one period marks the abbreviation and the boundary. Kiss and Strunk (2006) list the period's other jobs too: initials, ordinal numbers and ellipses, and in their corpora abbreviations account for up to 30% of the candidate boundaries.
تقسيم النص إلى جمل (sentence segmentation) هو مهمة إيجاد حدود الجمل، وتسمّي الشريحة المستفيدين المعتادين منه: التحليل النحوي (parsing) والترجمة الآلية، وكلاهما يأخذ جملة واحدة في كل مرة. ويحدد SLP3 الصعوبة بدقة. علامات الاستفهام والتعجب مؤشرات غير غامضة نسبيًا على حدود الجمل. أما النقطة فغامضة بين أن تكون حدًا لجملة وأن تكون علامة اختصار مثل Dr. أو Inc.، بل يمكنها أن تؤدي الدورين معًا: حين تنتهي جملة بـ Inc.، تعلّم نقطة واحدة الاختصار والحد معًا. ويسرد Kiss and Strunk (2006) وظائف النقطة الأخرى أيضًا: الأحرف الأولى من الأسماء، والأعداد الترتيبية، وعلامات الحذف (ellipses)، وفي مدوّناتهم تشكّل الاختصارات ما يصل إلى 30% من الحدود المرشحة.
Rules, lexicons and the joint solutionالقواعد، وقواميس الاختصارات، والحل المشترك
The slide's rule-based heuristics combine punctuation with capitalization patterns, an abbreviation list and quote or bracket balancing. Each rule is a feature that votes on one candidate mark.
القواعد اليدوية في الشريحة تجمع علامات الترقيم مع أنماط الأحرف الكبيرة، وقائمة اختصارات، وموازنة علامات الاقتباس والأقواس. كل قاعدة سمة (feature) تصوّت على علامة مرشحة واحدة.
Rule-based features and what they decideسمات النهج القائم على القواعد وما تحسمه
- Punctuation plus capitalizationعلامات الترقيم مع الأحرف الكبيرة
- A period followed by whitespace and a capitalized token suggests a boundary; a lowercase next token argues against oneالنقطة التي تتبعها مسافة ثم token يبدأ بحرف كبير توحي بوجود حد؛ أما الـ token التالي الذي يبدأ بحرف صغير فيرجّح عدم وجوده
- Abbreviation listقائمة الاختصارات
- If the token before the period is Dr, Inc, p.m. or another listed abbreviation, the period belongs to the wordإذا كان الـ token قبل النقطة Dr أو Inc أو p.m. أو اختصارًا آخر في القائمة، فالنقطة تنتمي إلى الكلمة
- Quote and bracket balancingموازنة علامات الاقتباس والأقواس
- A closing quote or bracket after the mark still belongs to the sentence that is endingعلامة الاقتباس أو القوس الذي يغلق بعد العلامة ما زال ينتمي إلى الجملة التي تنتهي
- Digit on both sidesأرقام على الجانبين
- 3.50 and 3.14 are numbers, so a word tokenizer keeps them whole and the segmenter never sees the period3.50 و 3.14 أعداد، لذلك يُبقيها tokenizer الكلمات كاملة ولا يرى مقسّم الجمل النقطة أبدًا
Notice the conflict in the exercise. After Dr. comes Ahmad, capitalized, so the capitalization rule votes for a boundary and only the abbreviation lexicon overrules it. After p.m. comes on, lowercase, so both rules agree. This is why the slide says segmentation is often done jointly with Tokenization and abbreviation lexicons: if the tokenizer has already kept Dr., p.m. and 3.50 as single tokens, the segmenter never has to look at those periods. Stanford CoreNLP states its rule in exactly that form: a sentence ends when a sentence-ending punctuation mark is not already grouped with other characters into a token, optionally followed by closing quotes or brackets. SLP3 notes the abbreviation dictionary can be hand-built or machine-learned.
لاحظ التعارض في التمرين. بعد Dr. تأتي Ahmad بحرف كبير، فتصوّت قاعدة الأحرف الكبيرة لصالح وجود حد، ولا يلغيها إلا قاموس الاختصارات. وبعد p.m. تأتي on بحرف صغير، فتتفق القاعدتان. لهذا تقول الشريحة إن التقسيم إلى جمل يُجرى غالبًا بالاشتراك مع tokenization وقواميس الاختصارات: إذا كان الـ tokenizer قد أبقى Dr. و p.m. و 3.50 كـ tokens مفردة، فلن يحتاج مقسّم الجمل إلى النظر في تلك النقاط أبدًا. ويصوغ Stanford CoreNLP قاعدته بهذا الشكل بالضبط: تنتهي الجملة حين تكون علامة إنهاء الجملة غير مجمّعة مسبقًا مع حروف أخرى في token واحد، وقد تتبعها اختياريًا علامات اقتباس أو أقواس إغلاق. ويلاحظ SLP3 أن قاموس الاختصارات يمكن بناؤه يدويًا أو تعلّمه آليًا.
Learning the boundaryتعلّم الحد
The statistical approach on the slide replaces hand-tuned votes with a classifier that learns the probability of a boundary from annotated data. Its features are the same evidence the rules used: the token before the mark, whether it is in an abbreviation list, its length, whether the next token is capitalized, whether the next token is a frequent sentence starter, and, in neural models, the surrounding context as a whole. Kiss and Strunk (2006) went one step further and removed the annotation. Their Punkt system, the default sentence tokenizer in NLTK, is unsupervised and language independent. It treats an abbreviation as a very tight collocation of a truncated word and a final period, which can be detected from raw text by asking whether the word occurs with a period far more often than chance, helped by the facts that abbreviations are usually short and sometimes contain internal periods. It also learns frequent sentence starters and collocations across a period. Its measured results on newspaper text are in the table.
النهج الإحصائي في الشريحة يستبدل الأصوات المضبوطة يدويًا بمصنِّف (classifier) يتعلّم احتمال وجود حد من بيانات موسومة. سماته هي الأدلة نفسها التي استخدمتها القواعد: الـ token الذي يسبق العلامة، وهل هو في قائمة الاختصارات، وطوله، وهل الـ token التالي يبدأ بحرف كبير، وهل هو من الكلمات الشائعة في بدايات الجمل، وفي النماذج العصبية السياق المحيط ككل. وذهب Kiss and Strunk (2006) خطوة أبعد فأزالا الحاجة إلى الوسم. نظامهما Punkt، وهو مقسّم الجمل الافتراضي في NLTK، غير موجَّه (unsupervised) ومستقل عن اللغة. يعامل الاختصار كتلازم (collocation) شديد الإحكام بين كلمة مقتطعة ونقطة نهائية، ويمكن اكتشافه من النص الخام بالسؤال عمّا إذا كانت الكلمة تظهر مع نقطة أكثر بكثير مما تتوقعه الصدفة، ويساعده في ذلك أن الاختصارات عادةً قصيرة وأحيانًا تحتوي على نقاط داخلية. ويتعلّم أيضًا الكلمات الشائعة في بدايات الجمل والتلازمات التي تعبر النقطة. ونتائجه المقيسة على نصوص الصحف موجودة في الجدول.
Punkt boundary detection results (Kiss and Strunk 2006)نتائج Punkt في اكتشاف حدود الجمل (Kiss and Strunk 2006)
- Mean accuracy, 11 languagesمتوسط الدقة على 11 لغة
- 98.74%98.74%
- Boundary error, Englishخطأ تحديد الحدود، الإنجليزية
- 1.65%1.65%
- Boundary error, Germanخطأ تحديد الحدود، الألمانية
- 0.35%0.35%
| Approachالنهج | How it decidesكيف يقرر | Needsما يحتاجه | Strengths and limitsنقاط القوة والحدود |
|---|---|---|---|
| Rule-basedقائم على القواعد | Hand-written heuristics and a hand-built abbreviation listقواعد مكتوبة يدويًا وقائمة اختصارات مبنية يدويًا | Noneلا شيء | Fast and transparent; brittle on new domains and languagesسريع وشفاف؛ هشّ أمام المجالات واللغات الجديدة |
| Statistical (supervised)إحصائي (موجَّه) | P(boundary | context)P(boundary | context) | Annotated sentence boundariesحدود جمل موسومة يدويًا | Adapts to a domain; needs labeled data per languageيتكيّف مع المجال؛ يحتاج بيانات موسومة لكل لغة |
| Punkt (unsupervised)Punkt (غير موجَّه) | Abbreviations as tight collocations of a truncated word and a period, plus sentence startersالاختصارات كتلازمات محكمة بين كلمة مقتطعة ونقطة، إضافة إلى الكلمات التي تبدأ بها الجمل | Raw text onlyنص خام فقط | Language independent; 98.74% mean accuracy over eleven languagesمستقل عن اللغة؛ متوسط دقة 98.74% على إحدى عشرة لغة |
Quick checkاختبار سريع
Which punctuation mark is hardest for sentence segmentation, and why?أي علامة ترقيم هي الأصعب في تقسيم النص إلى جمل، ولماذا؟
Recall
Why is the period harder than the question mark for sentence segmentation, and what are two features a classifier would use?لماذا تكون النقطة أصعب من علامة الاستفهام في تقسيم النص إلى جمل، وما سمتان يستخدمهما المصنِّف؟
Recall
What does Punkt learn without any labeled data?ماذا يتعلّم Punkt دون أي بيانات موسومة؟
Recapالخلاصة
If you remember nothing elseإن لم تتذكر شيئاً آخر فتذكّر هذا
- A production tokenizer is a pipeline: normalization, regex pre-tokenization, a BPE, unigram or WordPiece model, then special-token post-processing.الـ tokenizer المستخدم فعليًا خط معالجة (pipeline): تطبيع (normalization)، ثم pre-tokenization بتعبير نمطي (regex)، ثم نموذج BPE أو unigram أو WordPiece، ثم معالجة لاحقة تضيف الرموز الخاصة (special tokens).
- Merges live inside pre-tokenizer pieces. The leading space belongs to the piece, so Any|how at the start and ·anyhow later are different byte strings.عمليات الدمج تحدث داخل قطع الـ pre-tokenizer فقط. والمسافة السابقة للكلمة جزء من القطعة، لذلك Any|how في بداية الجملة و ·anyhow لاحقًا سلسلتا بايتات مختلفتان.
- cl100k and o200k cap digit runs at three per piece, and vocabulary size is a design parameter: 50,257 for GPT-2, 30,522 for BERT, 128K for Llama 3, 200K for GPT-4o.يحدّ cl100k و o200k سلاسل الأرقام بثلاثة أرقام في القطعة الواحدة، وحجم المفردات معامل تصميمي: 50,257 في GPT-2، و30,522 في BERT، و128K في Llama 3، و200K في GPT-4o.
- Byte-level BPE starts from 256 symbols, so nothing is out of vocabulary, but a token may cut a multi-byte character: gpt2 splits kaf into D9 and 83.يبدأ byte-level BPE من 256 رمزًا، فلا يوجد شيء خارج المفردات، لكن الـ token قد يقطع حرفًا متعدد البايتات: gpt2 يقسم الكاف إلى D9 و 83.
- Shared vocabularies favor English. Under cl100k Arabic pays a premium of 3.04 and Shan 15.05 (Petrov et al. 2023); longer sequences cost compute, context and money.المفردات المشتركة تحابي الإنجليزية. تحت cl100k تدفع العربية premium قدره 3.04 ولغة Shan قدره 15.05 (Petrov et al. 2023)؛ والتسلسلات الأطول تكلّف حسابًا وسياقًا ومالًا.
- SuperBPE adds a second stage whose merges cross spaces: up to 33% fewer tokens at 200K, at the price of compositionality.يضيف SuperBPE مرحلة ثانية تعبر فيها عمليات الدمج المسافات: ما يصل إلى 33% tokens أقل عند حجم 200K، مقابل خسارة في التركيبية (compositionality).
- Every checklist switch is frozen with the model: pre-tokenization, normalization, special tokens, numbers and URLs, multilingual coverage.كل مفتاح في قائمة التصميم يُجمَّد مع النموذج: الـ pre-tokenization، والتطبيع، والرموز الخاصة، والأرقام والروابط، والتغطية متعددة اللغات.
- The period is ambiguous and the question mark and exclamation mark mostly are not. Abbreviation lexicons, capitalization, decimal checks or Punkt's collocation test decide.النقطة غامضة، أما علامة الاستفهام وعلامة التعجب فغالبًا ليستا كذلك. يحسم الأمر قاموس الاختصارات، أو حالة الأحرف الكبيرة، أو فحص الأعداد العشرية، أو اختبار التلازم (collocation) في Punkt.
Sourcesالمصادر
- Speech and Language Processing, 3rd edition draft, chapter 2: Words and TokensBookJurafsky and Martin, StanfordGPT-4o tokenization of the slide sentence (2.4.3), the GPT-2 regex output (2.6.9), sentence segmentation (2.8.1)تقطيع GPT-4o لجملة الشريحة (2.4.3)، ومخرجات regex الخاص بـ GPT-2 (2.6.9)، وتقسيم النص إلى جمل (2.8.1)(opens in a new tab)(يفتح في تبويب جديد)
- Language Models are Unsupervised Multitask LearnersPaperRadford et al., OpenAI, 2019Section 2.2: byte-level BPE, 130,000 code points versus 256 bytes, the character-category merge ruleالقسم 2.2: byte-level BPE، و130,000 نقطة ترميز مقابل 256 بايتًا، وقاعدة الدمج حسب فئات الحروف(opens in a new tab)(يفتح في تبويب جديد)
- tiktoken encoding definitionsDocsOpenAI, GitHubPre-tokenizer regexes and vocabulary sizes of gpt2, cl100k_base and o200k_baseتعابير regex الخاصة بالـ pre-tokenizer وأحجام المفردات في gpt2 و cl100k_base و o200k_base(opens in a new tab)(يفتح في تبويب جديد)
- TiktokenizerDocstiktokenizer.vercel.appVisualizes tokenizations, the tool named on slide 49يعرض التقطيعات بصريًا، وهو الأداة المذكورة في الشريحة 49(opens in a new tab)(يفتح في تبويب جديد)
- Neural Machine Translation of Rare Words with Subword UnitsPaperSennrich, Haddow and Birch, ACL 2016BPE for subword tokenizationBPE للتقطيع إلى subwords(opens in a new tab)(يفتح في تبويب جديد)
- Subword Regularization: Improving Neural Network Translation Models with Multiple Subword CandidatesPaperKudo, ACL 2018The unigram language model tokenizerالـ tokenizer القائم على نموذج لغة unigram(opens in a new tab)(يفتح في تبويب جديد)
- Japanese and Korean Voice SearchPaperSchuster and Nakajima, ICASSP 2012WordPieceWordPiece(opens in a new tab)(يفتح في تبويب جديد)
- Language Model Tokenizers Introduce Unfairness Between LanguagesPaperPetrov, La Malfa, Torr and Bibi, NeurIPS 2023Tokenization premium definition and Table 1 numbers; ByT5 and ArabicBERT premiumsتعريف tokenization premium وأرقام الجدول 1؛ وقيم الـ premium في ByT5 و ArabicBERT(opens in a new tab)(يفتح في تبويب جديد)
- Do All Languages Cost the Same? Tokenization in the Era of Commercial Language ModelsPaperAhia et al., EMNLP 202322 languages on ChatGPT and BLOOMZ; overcharged while obtaining poorer results; Arabic as an outlier under the BLOOMZ tokenizer22 لغة على ChatGPT و BLOOMZ؛ دفع أكثر مقابل نتائج أضعف؛ والعربية حالة شاذة تحت tokenizer الخاص بـ BLOOMZ(opens in a new tab)(يفتح في تبويب جديد)
- SuperBPE: Space Travel for Language ModelsPaperLiu et al., 2025Two-stage pretokenization curriculum; 33% fewer tokens at 200K; +4.0% average, +8.2% MMLU, 27% less inference computeمنهج pretokenization من مرحلتين؛ tokens أقل بنسبة 33% عند 200K؛ و+4.0% في المتوسط، و+8.2% في MMLU، وحساب استدلال أقل بنسبة 27%(opens in a new tab)(يفتح في تبويب جديد)
- The tokenization pipelineDocsHugging Face tokenizers documentationNormalization, pre-tokenization, model, post-processing; BERT vocabulary of 30,522; retraining after changing componentsالتطبيع، والـ pre-tokenization، والنموذج، والمعالجة اللاحقة؛ مفردات BERT بحجم 30,522؛ وإعادة التدريب بعد تغيير المكوّنات(opens in a new tab)(يفتح في تبويب جديد)
- Introducing Meta Llama 3DocsMeta AI128K token vocabularyمفردات من 128K token(opens in a new tab)(يفتح في تبويب جديد)
- Unsupervised Multilingual Sentence Boundary DetectionPaperKiss and Strunk, Computational Linguistics 32(4), 2006Punkt: abbreviations as collocations; 98.74% mean accuracy over eleven languagesPunkt: الاختصارات كتلازمات (collocations)؛ ومتوسط دقة 98.74% على إحدى عشرة لغة(opens in a new tab)(يفتح في تبويب جديد)
- nltk.tokenize.punktDocsNLTK documentationThe unsupervised Punkt sentence tokenizer shipped with NLTKمقسّم الجمل Punkt غير الموجَّه المرفق مع NLTK(opens in a new tab)(يفتح في تبويب جديد)
Part 08: Regular expressions: the core syntaxالتعابير النمطية (Regex): الصياغة الأساسية
From ELIZA's pattern rules to the building blocks of regular expressions: literals, bracket classes, ranges, negation, quantifiers, wildcards, anchors and the backslash aliases.من قواعد الأنماط في ELIZA إلى اللبنات الأساسية للتعابير النمطية: الحروف الحرفية (literals)، وفئات الأقواس، والنطاقات، والنفي، والمكممات (quantifiers)، والرمز العام (wildcard)، والمرتكزات (anchors)، واختصارات الشرطة المائلة العكسية.
4 concepts4 مفاهيم, ، slides 56-65الشرائح 56-65
Why this part mattersلماذا يهمّ هذا الجزء
Every tokenizer you will build or inspect, every corpus cleaning script for Arabic or English, every date or number normalizer, and every exam question on this chapter runs through the same ten or so symbols. The GPT-2 pre-tokenizer later in this lecture is one regular expression. Edit distance in the next parts starts from tokens that a regex produced.
This part builds the core syntax from the ground up, starting with the program that made pattern matching famous. ELIZA held conversations in 1966 using nothing but keyword rules and text substitution, and people believed it understood them. From there we take the symbols one family at a time: literals and disjunction, bracket classes, quantifiers and the wildcard, anchors and the backslash aliases. The next part adds precedence, groups, substitution and lookahead on top of exactly this vocabulary, so every table here is worth being able to reproduce from memory. A live tester at the end of the part loads every example row from the slides so you can check each first match yourself.
كل tokenizer ستبنيه أو تفحصه، وكل سكربت لتنظيف مدوّنة نصوص عربية أو إنجليزية، وكل أداة لتوحيد صيغ التواريخ أو الأرقام، وكل سؤال امتحان عن هذا الفصل، يمر كله عبر الرموز العشرة تقريبًا نفسها. الـ pre-tokenizer الخاص بـ GPT-2 الذي سيأتي لاحقًا في هذه المحاضرة هو تعبير نمطي واحد. ومسافة التحرير (edit distance) في الأجزاء القادمة تبدأ من وحدات (tokens) أنتجها regex.
يبني هذا الجزء الصياغة الأساسية من الصفر، بدءًا بالبرنامج الذي جعل مطابقة الأنماط مشهورة. فقد أجرى ELIZA محادثات عام 1966 بلا شيء سوى قواعد كلمات مفتاحية واستبدال نصوص، وصدّق الناس أنه يفهمهم. ثم نأخذ الرموز عائلةً عائلة: الحروف الحرفية والاختيار، وفئات الأقواس، والمكمِّمات والرمز الشامل، والمراسي واختصارات الشرطة المائلة العكسية. الجزء التالي يضيف الأولوية والمجموعات والاستبدال والنظر للأمام (lookahead) فوق هذه المفردات بالضبط، لذلك يستحق كل جدول هنا أن تقدر على إعادة كتابته من الذاكرة. وفي نهاية الجزء أداة اختبار حية تحمّل كل مثال من الشرائح لتتحقق من كل مطابقة أولى بنفسك.
By the end you canفي نهاية هذا الجزء ستستطيع
- Explain how ELIZA produced replies from keyword substitution rules and name the Eliza effect.اشرح كيف كان ELIZA يولّد ردوده من قواعد استبدال تطلقها كلمات مفتاحية، وسمِّ ظاهرة Eliza effect.
- Read and write literals, concatenation, disjunction and bracket classes, including ranges and negation.اقرأ واكتب الحروف الحرفية (literals) والتسلسل (concatenation) والاختيار (disjunction) وفئات الأقواس، بما فيها النطاقات والنفي.
- Apply * + ? {n} {m,n} and the wildcard, and predict greedy versus lazy matches on a given string.طبّق * + ? {n} {m,n} والرمز الشامل (wildcard)، وتنبأ بالمطابقة الجشعة (greedy) مقابل الكسولة (lazy) على نص معطى.
- Use ^ $ \b to match whole words and line-based formats, and explain why anchors consume no characters.استخدم ^ $ \b لمطابقة كلمات كاملة وصيغ قائمة على الأسطر، واشرح لماذا لا تستهلك المراسي (anchors) أي حرف.
- Expand each alias \d \D \w \W \s \S and state where Python and JavaScript flavors differ.افرد كل اختصار \d \D \w \W \s \S إلى فئته، وبيّن أين تختلف نسختا Python و JavaScript.
In 1966 Joseph Weizenbaum at MIT published a program that imitated a Rogerian psychotherapist, the kind of therapist who reflects the patient's own words back as questions. He called it ELIZA. Read the exchange below as a patient would have, one line at a time.
في عام 1966 نشر Joseph Weizenbaum في MIT برنامجًا يقلّد معالجًا نفسيًا من مدرسة Rogerian، وهو نوع من المعالجين يعكس كلمات المريض نفسها ويعيدها إليه على هيئة أسئلة. سمّاه ELIZA. اقرأ المحادثة أدناه كما كان سيقرؤها مريض، سطرًا بعد سطر.
| Speakerالمتحدث | Lineالسطر |
|---|---|
| Userالمستخدم | I need some help, that much seems certain.I need some help, that much seems certain. |
| ELIZAELIZA | WHAT WOULD IT MEAN TO YOU IF YOU GOT SOME HELPWHAT WOULD IT MEAN TO YOU IF YOU GOT SOME HELP |
| Userالمستخدم | Perhaps I could learn to get along with my mother.Perhaps I could learn to get along with my mother. |
| ELIZAELIZA | TELL ME MORE ABOUT YOUR FAMILYTELL ME MORE ABOUT YOUR FAMILY |
| Userالمستخدم | My mother takes care of me.My mother takes care of me. |
| ELIZAELIZA | WHO ELSE IN YOUR FAMILY TAKES CARE OF YOUWHO ELSE IN YOUR FAMILY TAKES CARE OF YOU |
| Userالمستخدم | My father.My father. |
| ELIZAELIZA | YOUR FATHERYOUR FATHER |
| Userالمستخدم | You are like my father in some ways.You are like my father in some ways. |
It reads like attention. It is not. The whole program is a list of keywords, and for each keyword a small set of decomposition rules that split the input around the keyword, paired with reassembly rules that build a reply out of the pieces. Weizenbaum wrote the rules in his own notation. A decomposition rule such as (0 YOU 0 ME) means "an indefinite number of words, then YOU, then an indefinite number of words, then ME", and its reassembly rule (WHAT MAKES YOU THINK I 3 YOU) inserts the third component, whatever words stood between YOU and ME, into a fixed frame (Weizenbaum, 1966, p. 38). The dictionary he had built "so far" contained about 50 keywords. Nothing is parsed, nothing is understood, and the program has no memory of what "mother" means beyond the fact that it is filed under FAMILY.
تبدو كأنها إصغاء واهتمام، وليست كذلك. البرنامج كله قائمة من الكلمات المفتاحية، ولكل كلمة مفتاحية مجموعة صغيرة من قواعد التفكيك (decomposition rules) التي تقسم المُدخل حول الكلمة المفتاحية، ومعها قواعد إعادة التركيب (reassembly rules) التي تبني ردًا من القطع. كتب Weizenbaum القواعد بترميزه الخاص. قاعدة تفكيك مثل (0 YOU 0 ME) تعني «عدد غير محدد من الكلمات، ثم YOU، ثم عدد غير محدد من الكلمات، ثم ME»، وقاعدة إعادة التركيب المرافقة لها (WHAT MAKES YOU THINK I 3 YOU) تُدخل المكوّن الثالث، أي الكلمات التي وقعت بين YOU وME أيًا كانت، في إطار ثابت (Weizenbaum, 1966, p. 38). والقاموس الذي كان قد بناه «حتى الآن» ضم نحو 50 كلمة مفتاحية. لا يُحلَّل شيء نحويًا، ولا يُفهم شيء، والبرنامج لا يعرف عن معنى «mother» شيئًا سوى أنها مصنّفة تحت FAMILY.
Jurafsky and Martin rewrite the same idea in modern regular expression syntax, and this is the version to remember. After the input is uppercased and pronouns are swapped (I'M becomes YOU ARE, MY becomes YOUR), rules like these run in order until one fires (SLP3, section 2.6.7):
يعيد Jurafsky وMartin كتابة الفكرة نفسها بصياغة regular expression الحديثة، وهذه هي النسخة التي يجب أن تتذكرها. بعد تحويل المُدخل إلى حروف كبيرة وتبديل الضمائر (I'M تصبح YOU ARE، وMY تصبح YOUR)، تُجرَّب قواعد كهذه بالترتيب حتى تنطلق إحداها (SLP3, section 2.6.7):
- re.sub(r".* YOU ARE (DEPRESSED|SAD) .*", r"I AM SORRY TO HEAR YOU ARE \1", input)re.sub(r".* YOU ARE (DEPRESSED|SAD) .*", r"I AM SORRY TO HEAR YOU ARE \1", input)
- re.sub(r".* ALWAYS .*", r"CAN YOU THINK OF A SPECIFIC EXAMPLE", input)re.sub(r".* ALWAYS .*", r"CAN YOU THINK OF A SPECIFIC EXAMPLE", input)
Worked exampleمثال محلول
One ELIZA reply, step by stepرد واحد من ELIZA خطوة بخطوة
User typesالمستخدم يكتب
He says I'm depressed much of the time.He says I'm depressed much of the time.Uppercaseالتحويل إلى حروف كبيرة
HE SAYS I'M DEPRESSED MUCH OF THE TIME.HE SAYS I'M DEPRESSED MUCH OF THE TIME.Swap pronounsتبديل الضمائر
I'M becomes YOU ARE: HE SAYS YOU ARE DEPRESSED MUCH OF THE TIME.I'M تصبح YOU ARE: HE SAYS YOU ARE DEPRESSED MUCH OF THE TIME.Try the rules in orderجرّب القواعد بالترتيب
The pattern .* YOU ARE (DEPRESSED|SAD) .* matches: .* swallows HE SAYS, the literal YOU ARE matches, the parenthesized alternative picks DEPRESSED, and the trailing .* swallows the rest.النمط .* YOU ARE (DEPRESSED|SAD) .* يطابق: .* يبتلع HE SAYS، والنص الحرفي YOU ARE يطابق، والبديل بين القوسين يختار DEPRESSED، و.* الأخيرة تبتلع الباقي.Reassembleإعادة التركيب
The replacement I AM SORRY TO HEAR YOU ARE \1 copies whatever the parentheses captured into the slot marked \1.نص الاستبدال I AM SORRY TO HEAR YOU ARE \1 ينسخ ما التقطه القوسان، أيًا كان، إلى الخانة المعلَّمة بـ \1.Resultالنتيجة
I AM SORRY TO HEAR YOU ARE DEPRESSED, which is the reply SLP3 derives in section 2.6.7 and the fourth reply in Weizenbaum's opening transcript. Swap DEPRESSED for SAD in the input and the same rule prints SAD.I AM SORRY TO HEAR YOU ARE DEPRESSED، وهو الرد الذي يستنتجه SLP3 في القسم 2.6.7، وهو أيضًا الرد الرابع في محادثة Weizenbaum الافتتاحية. استبدل DEPRESSED بـ SAD في المُدخل وستطبع القاعدة نفسها SAD.
| Weizenbaum (1966)Weizenbaum (1966) | Meaningالمعنى | Modern regexالـ regex الحديث |
|---|---|---|
| 0 in a decomposition rule0 في قاعدة تفكيك | An indefinite number of wordsعدد غير محدد من الكلمات | .*.* |
| A positive integer n in a decomposition ruleعدد صحيح موجب n في قاعدة تفكيك | Exactly n wordsn كلمة بالضبط | ((?:\S+ ){n}), one group holding exactly n words((?:\S+ ){n})، مجموعة واحدة تحمل n كلمة بالضبط |
| 3 in a reassembly rule3 في قاعدة إعادة تركيب | Insert the third component the decomposition foundأدخِل المكوّن الثالث الذي وجده التفكيك | \1 style backreference to a capture groupإحالة خلفية (backreference) بأسلوب \1 إلى مجموعة التقاط |
| Keyword dictionary, about 50 entriesقاموس الكلمات المفتاحية، نحو 50 مدخلًا | Which rule set to try, ranked by keywordأي مجموعة قواعد تُجرَّب، مرتبةً حسب الكلمة المفتاحية | A cascade of re.sub calls tried in orderسلسلة من استدعاءات re.sub تُجرَّب بالترتيب |
The parentheses and the \1 are a capture group and a Backreference, which the next part treats properly. For now the point is the shape of the machine: a keyword selects a rule, a pattern with wildcards splits the sentence, a frame reassembles the pieces. Weizenbaum's paper opens with the exchange "Men are all alike." answered by "IN WHAT WAY", and the reply is not about men at all: a rule keyed on the wording of the input prints a fixed question with no slot to fill.
القوسان و\1 هما capture group (مجموعة التقاط) وbackreference (إحالة خلفية)، وسيعالجهما الجزء التالي كما ينبغي. المهم الآن هو شكل الآلة: كلمة مفتاحية تختار قاعدة، ونمط فيه رموز شاملة يقسم الجملة، وإطار يعيد تركيب القطع. تبدأ ورقة Weizenbaum بالحوار «Men are all alike.» الذي يجاب عنه بـ «IN WHAT WAY»، والرد لا علاقة له بالرجال أصلًا: قاعدة مرتبطة بصياغة المُدخل تطبع سؤالًا ثابتًا ليس فيه خانة تُملأ.
Why people believed itلماذا صدّقه الناس
Crude as the rules were, SLP3 notes that many people who talked to ELIZA came to believe that it really understood them, and that this led researchers to think for the first time about the impact of chatbots on their users (Weizenbaum, 1976). The effect now carries the program's name. The Eliza effect is the tendency to unconsciously assume that computer behaviors are analogous to human behaviors. Douglas Hofstadter defines its specific form as our susceptibility to read far more understanding than is warranted into strings of symbols strung together by computers (Hofstadter, 1995). The standard illustration is not a chatbot at all but a cash machine that prints THANK YOU at the end of a transaction, which a naive observer might take for real gratitude. ELIZA exploited the same reflex at conversational scale: because it echoed your own words, every reply seemed relevant, and relevance felt like understanding.
رغم بساطة القواعد، يذكر SLP3 أن كثيرًا ممن تحدثوا مع ELIZA صاروا يعتقدون أنه يفهمهم فعلًا، وأن هذا دفع الباحثين إلى التفكير لأول مرة في أثر روبوتات المحادثة على مستخدميها (Weizenbaum, 1976). وصار الأثر يحمل اسم البرنامج. فـ Eliza effect هو الميل اللاواعي إلى افتراض أن سلوك الحاسوب مماثل لسلوك البشر. ويعرّف Douglas Hofstadter شكله الخاص بأنه قابليتنا لأن نقرأ فهمًا أكبر بكثير مما يُبرَّر في سلاسل رموز صفّها الحاسوب بعضها بجانب بعض (Hofstadter, 1995). والمثال المعتاد ليس روبوت محادثة أصلًا، بل جهاز صرف آلي يطبع THANK YOU في نهاية العملية، قد يظنه مراقب ساذج امتنانًا حقيقيًا. استغل ELIZA الردّ الغريزي نفسه على مستوى المحادثة: لأنه يردد كلماتك أنت، بدا كل رد في محله، والملاءمة بدت فهمًا.
What regex is for in an NLP pipelineما فائدة regex في خط معالجة NLP
A regular expression is fast, flexible pattern matching for text. It needs no training data, and it is precise in a way a learned model cannot be: a pattern either matches or it does not, and you can read off why. The slide lists four jobs, and it is worth having a concrete example ready for each.
التعبير النمطي (regular expression) مطابقة أنماط سريعة ومرنة للنصوص. لا يحتاج إلى بيانات تدريب، وهو دقيق بطريقة لا يقدر عليها نموذج متعلَّم: النمط إما أن يطابق أو لا يطابق، وتستطيع أن تقرأ السبب مباشرة. تسرد الشريحة أربع مهام، ومن المفيد أن يكون لديك مثال ملموس جاهز لكل منها.
Four jobs regex does in NLP (slide 57), with an example eachأربع مهام يؤديها الـ regex في NLP (الشريحة 57)، مع مثال لكل منها
- Tokenization and pre-tokenizationالتقطيع والتقطيع المسبق
- Split text into words, numbers and punctuation before a BPE tokenizer merges inside each piece. The GPT-2 pre-tokenizer in the next part is one regex.قسّم النص إلى كلمات وأرقام وعلامات ترقيم قبل أن يدمج BPE tokenizer داخل كل قطعة. الـ pre-tokenizer الخاص بـ GPT-2 في الجزء التالي هو regex واحد.
- Normalizationالتوحيد
- Recognize dates and numbers in any of their surface forms and rewrite them to one canonical form, such as dd-mm-yyyy.تعرّف على التواريخ والأرقام في أي صيغة ظاهرة لها، وأعد كتابتها بصيغة قياسية واحدة، مثل dd-mm-yyyy.
- Filtering and cleaningالترشيح والتنظيف
- Drop lines that are all punctuation, strip HTML tags, remove boilerplate, detect a script you do not want in a training corpus.احذف الأسطر المكوّنة كلها من علامات ترقيم، وانزع وسوم HTML، وأزل النصوص القالبية المكررة (boilerplate)، واكتشف نظام كتابة لا تريده في مدوّنة التدريب.
- Feature extractionاستخراج السمات
- Does the token contain a digit, start with a capital, end in -ing? Each answer is a binary feature a classifier can use.هل تحتوي الوحدة (token) على رقم، أو تبدأ بحرف كبير، أو تنتهي بـ -ing؟ كل إجابة سمة ثنائية يستطيع المصنِّف استخدامها.
The slide's last line matters more than it looks: regex is language- and task-dependent. A class like [a-z] says nothing about Arabic letters. A word boundary \b assumes words are made of letters, digits and underscores separated by something else, which fails outright for Chinese, where there are no spaces, and quietly misbehaves for Arabic under an ASCII-only definition of "letter". Recall the typology in part 04: an isolating language and a templatic one need different patterns for the same task, and a pattern tuned for tweets will not fit legal text. Regex gives you precision; it does not give you generality for free.
السطر الأخير في الشريحة أهم مما يبدو: الـ regex يعتمد على اللغة وعلى المهمة. فئة مثل [a-z] لا تقول شيئًا عن الحروف العربية. وword boundary (حد الكلمة) \b يفترض أن الكلمات مكوّنة من حروف وأرقام وشرطات سفلية يفصل بينها شيء آخر، وهذا يفشل تمامًا في الصينية حيث لا مسافات، ويسيء التصرف بصمت في العربية إذا كان تعريف «الحرف» مقصورًا على ASCII. تذكّر التصنيف اللغوي في الجزء 04: اللغة العازلة (isolating) واللغة القالبية (templatic) تحتاجان إلى أنماط مختلفة للمهمة نفسها، والنمط المضبوط للتغريدات لن يناسب النصوص القانونية. الـ regex يمنحك الدقة، لكنه لا يمنحك العمومية مجانًا.
Quick checkاختبار سريع
Which mechanism produced ELIZA's reply YOUR FATHER from the input My father?أي آلية أنتجت رد ELIZA وهو YOUR FATHER على المُدخل My father؟
Recall
Why did ELIZA convince people, in two sentences: one about the program and one about the people?لماذا أقنع ELIZA الناس؟ أجب بجملتين: واحدة عن البرنامج وواحدة عن الناس.
Start with the simplest pattern there is. The regex Buttercup matches the substring Buttercup in "I'm called little Buttercup" and nowhere else (SLP3, section 2.6.1). Each letter is a literal that matches itself, and writing letters one after another means "this, then this, then this". That is concatenation, and abc matches exactly the three characters abc in that order.
ابدأ بأبسط نمط ممكن. الـ regex Buttercup يطابق السلسلة الجزئية Buttercup في «I'm called little Buttercup» ولا يطابق في أي مكان آخر (SLP3, section 2.6.1). كل حرف هنا حرف حرفي (literal) يطابق نفسه، وكتابة الحروف واحدًا بعد آخر تعني «هذا، ثم هذا، ثم هذا». هذا هو التسلسل (concatenation)، وabc يطابق الحروف الثلاثة abc بهذا الترتيب بالضبط.
Two more operators complete the algebra on slide 58. The vertical bar is disjunction: a|b matches either a or b. Parentheses group and define scope, so gupp(y|ies) matches guppy or guppies, while guppy|ies would match guppy or the bare string ies, because the bar has the lowest precedence of all and splits the whole pattern into two halves (SLP3, section 2.6.4). Regex is case sensitive throughout: s does not match S. Concatenation, disjunction and the Kleene star, which the next concept introduces, are the three operations that define regular languages in theory of computation. Parentheses only set scope, and classes, ranges, +, ? and counted repetition are all shorthand built from those three.
عاملان آخران يكملان الجبر في الشريحة 58. الخط العمودي هو الاختيار (disjunction): a|b يطابق a أو b. والأقواس تجمّع وتحدد النطاق، فـ gupp(y|ies) يطابق guppy أو guppies، بينما guppy|ies يطابق guppy أو السلسلة المجردة ies، لأن الخط العمودي له أدنى precedence (أولوية) على الإطلاق فيقسم النمط كله إلى نصفين (SLP3, section 2.6.4). والـ regex حساس لحالة الأحرف في كل مكان: s لا يطابق S. التسلسل والاختيار ونجمة Kleene، التي يقدمها المفهوم التالي، هي العمليات الثلاث التي تعرّف اللغات النظامية (regular languages) في نظرية الحوسبة. الأقواس تحدد النطاق فقط، أما الفئات والنطاقات و+ و? والتكرار المعدود فكلها اختصارات مبنية من تلك العمليات الثلاث.
The square-bracket classفئة الأقواس المربعة
Disjunction between single characters is so common that it has its own notation. A Character class in square brackets matches exactly one character from the set it lists. This is the fix for case sensitivity: [mM]ary matches Mary or mary. Read every row of the next three tables as the slides present them, pattern, meaning, and the first match marked in the example string.
الاختيار بين حروف مفردة شائع جدًا لدرجة أن له ترميزًا خاصًا. الـ character class (فئة الحروف) بين أقواس مربعة تطابق حرفًا واحدًا بالضبط من المجموعة التي تسردها. وهذا هو حل مشكلة حساسية حالة الأحرف: [mM]ary يطابق Mary أو mary. اقرأ كل صف في الجداول الثلاثة التالية كما تعرضه الشرائح: النمط، ومعناه، والمطابقة الأولى معلَّمة في نص المثال.
| Patternالنمط | Matchesيطابق | First match in the exampleالمطابقة الأولى في المثال |
|---|---|---|
| [mM]ary[mM]ary | Mary or maryMary أو mary | Mary Ann stopped by Mona'sMary Ann stopped by Mona's |
| [abc][abc] | a, b or ca أو b أو c | In uomini, in soldatiIn uomini, in soldati |
| [1234567890][1234567890] | Any digitأي رقم | plenty of 7 to 5plenty of 7 to 5 |
Look closely at the second row. "In uomini" contains no a, b or c, so the first match is the a in soldati, eighteen characters in. A class matches one character, so a bracket never matches "abc" as a word; SLP3 asks why [catdog] does not mean cat or dog, and the answer is the same: it is one character drawn from c, a, t, d, o, g. Listing every digit is tedious, so a dash inside brackets gives a range in code point order: [0-9], [a-z], [A-Z], but also [2-5] or [b-g].
انظر جيدًا إلى الصف الثاني. «In uomini» لا يحتوي على a ولا b ولا c، فتكون المطابقة الأولى هي a في soldati، بعد ثمانية عشر حرفًا. الفئة تطابق حرفًا واحدًا، لذلك لا تطابق الأقواس أبدًا «abc» ككلمة. ويسأل SLP3 لماذا لا يعني [catdog] «cat أو dog»، والجواب نفسه: إنه حرف واحد مأخوذ من c, a, t, d, o, g. سرد كل الأرقام ممل، لذلك تعطي الشرطة داخل الأقواس نطاقًا (range) بترتيب نقاط الترميز (code point): [0-9] و[a-z] و[A-Z]، وأيضًا [2-5] أو [b-g].
| Patternالنمط | Matchesيطابق | First match in the exampleالمطابقة الأولى في المثال |
|---|---|---|
| [A-Z][A-Z] | An upper case letterحرف كبير | we should call it 'Drenched Blossoms'we should call it 'Drenched Blossoms' |
| [a-z][a-z] | A lower case letterحرف صغير | my beans were impatient to be hoed!my beans were impatient to be hoed! |
| [0-9][0-9] | A single digitرقم واحد | Chapter 1: Down the Rabbit HoleChapter 1: Down the Rabbit Hole |
The caret is the last bracket operator, and it is the one that trips people. When the caret is the first character inside brackets, the class is negated and matches any single character not in the set. Anywhere else inside brackets it is an ordinary caret. Python's documentation states both halves: the caret "has no special meaning if it's not the first character in the set", and [^^] matches any character except a caret.
علامة الإقحام ^ (caret) هي آخر عوامل الأقواس، وهي التي يتعثر فيها الناس. حين تكون ^ أول حرف داخل الأقواس، تُنفى الفئة وتطابق أي حرف واحد ليس في المجموعة. وفي أي موضع آخر داخل الأقواس هي حرف ^ عادي. وتوثيق Python يذكر النصفين: العلامة ^ «ليس لها معنى خاص إذا لم تكن الحرف الأول في المجموعة»، و[^^] يطابق أي حرف عدا ^.
| Patternالنمط | Matchesيطابق | First match in the exampleالمطابقة الأولى في المثال |
|---|---|---|
| [^A-Z][^A-Z] | Not an upper case letterليس حرفًا كبيرًا | Oyfn pripetchikOyfn pripetchik |
| [^Ss][^Ss] | Neither S nor sلا S ولا s | I have no exquisite reason for'tI have no exquisite reason for't |
| [^.][^.] | Not a periodليس نقطة | our resident Djinnour resident Djinn |
| [e^][e^] | Either e or a carete أو علامة ^ | look up ^ nowlook up ^ now |
| a^ba^b | The pattern a^b, as the slide claimsالنمط a^b، كما تدّعي الشريحة | look up a^b now (no match)look up a^b now (no match) |
| a\^ba\^b | The literal string a^b, escapedالسلسلة الحرفية a^b، مهروبة | look up a^b nowlook up a^b now |
Notice also that the third row needed no backslash. Inside brackets, special characters other than the backslash lose their special meaning; the Python documentation gives [(+*)] as a class that matches any of the literal characters (, +, * and ). So [^.] means "not a period" with a plain period, while outside brackets a bare period is the wildcard from the next concept and a literal period must be written \.. The two contexts have different grammars, and reading a pattern means always knowing which one you are in.
لاحظ أيضًا أن الصف الثالث لم يحتج إلى شرطة مائلة عكسية. داخل الأقواس تفقد الحروف الخاصة معناها الخاص، عدا الشرطة المائلة العكسية نفسها. ويعطي توثيق Python المثال [(+*)] كفئة تطابق أيًا من الحروف الحرفية ( و+ و* و). إذن [^.] تعني «ليس نقطة» بنقطة عادية، بينما النقطة المجردة خارج الأقواس هي الرمز الشامل من المفهوم التالي، والنقطة الحرفية هناك يجب أن تُكتب \.. للسياقين قواعد مختلفة، وقراءة أي نمط تعني أن تعرف دائمًا في أيهما أنت.
Quick checkاختبار سريع
Where must a caret sit to negate a bracket character class?أين يجب أن توضع علامة ^ كي تنفي فئة حروف بين أقواس؟
Recall
Why does [^.] need no backslash while a bare . outside brackets matches any character?لماذا لا تحتاج [^.] إلى شرطة مائلة عكسية، بينما النقطة المجردة خارج الأقواس تطابق أي حرف؟
British and American spelling give the cleanest first example. You want one regex for color and colour. The u is optional, and colou?r says exactly that: the question mark makes the character before it appear zero or one times (SLP3, section 2.6.2). The same trick covers a plural: koalas?.
التهجئة البريطانية والأمريكية تعطي أوضح مثال أول. تريد regex واحدًا لـ color وcolour. حرف u اختياري، وcolou?r يقول ذلك بالضبط: علامة الاستفهام تجعل الحرف الذي قبلها يظهر صفر مرة أو مرة واحدة (SLP3, section 2.6.2). والحيلة نفسها تغطي الجمع: koalas?.
Now try sheep. Their language is baa!, baaa!, baaaa!, any number of a's of at least two. The Kleene star gives zero or more of the previous element, so baaa*! works: two literal a's, then any number more. The Kleene plus gives one or more, so baa+! says the same thing more readably. Both reject b!. Note what ba*! would do: with zero a's allowed, it accepts b!, which no sheep says. This is the recurring hazard of the star: it also matches nothing.
جرّب الآن الخراف. لغتها baa! وbaaa! وbaaaa!، أي عدد من حروف a لا يقل عن اثنين. نجمة Kleene تعطي صفرًا أو أكثر من العنصر السابق، لذلك يعمل baaa*!: حرفا a حرفيان، ثم أي عدد إضافي. وزائد Kleene يعطي واحدًا أو أكثر، فيقول baa+! الشيء نفسه بوضوح أكبر. وكلاهما يرفض b!. لاحظ ماذا كان سيفعل ba*!: بما أنه يسمح بصفر من a، فهو يقبل b!، وهذا ما لا يقوله أي خروف. هذا هو الخطر المتكرر في النجمة: إنها تطابق اللاشيء أيضًا.
Quantifiers and the wildcard (slides 62 and 63, SLP3 Fig 2.11)المكمِّمات والرمز الشامل (الشريحتان 62 و63، SLP3 Fig 2.11)
- *
- Zero or more occurrences of the previous character or expression. baa* matches ba, baa, baaa and so on.صفر أو أكثر من تكرارات الحرف أو التعبير السابق. baa* يطابق ba وbaa وbaaa وهكذا.
- +
- One or more occurrences. baa+ requires at least one a after the first, so it rejects ba.تكرار واحد أو أكثر. baa+ يشترط حرف a واحدًا على الأقل بعد الأول، لذلك يرفض ba.
- ?
- Zero or one occurrence, meaning optional. colou?r matches both color and colour.صفر أو تكرار واحد، أي أن العنصر اختياري. colou?r يطابق color وcolour كليهما.
- {n}
- Exactly n occurrences. a{3} matches aaa and nothing shorter or longer.n تكرار بالضبط. a{3} يطابق aaa ولا شيء أقصر أو أطول.
- {m,n}
- Between m and n occurrences, inclusive. a{2,4} accepts aa, aaa and aaaa.بين m وn تكرار، شاملًا الحدين. a{2,4} يقبل aa وaaa وaaaa.
- {m,} and {,n}{m,} و {,n}
- At least m, or at most n. Omitting m sets a lower bound of zero and omitting n sets no upper bound (Python re documentation). JavaScript, and so the tester below, needs {0,n}: a bare {,n} is treated as literal text.m على الأقل، أو n على الأكثر. حذف m يجعل الحد الأدنى صفرًا، وحذف n يلغي الحد الأعلى (توثيق Python re). أما JavaScript، ومعها أداة الاختبار أدناه، فتحتاج إلى {0,n}: الصيغة المجردة {,n} تُعامَل كنص حرفي.
- .
- Any single character except a newline in most flavors.أي حرف واحد عدا السطر الجديد في معظم النسخ (flavors).
- .*
- Any string of zero or more characters: the wildcard under the star.أي سلسلة من صفر حرف أو أكثر: الرمز الشامل تحت النجمة.
A Quantifier applies to whatever is immediately before it: one character, one class, or one parenthesized group. So [0-9]+ is an integer of one or more digits, and on "Chapter 12 of 3" it finds 12 at 8 and 3 at 14. SLP3 asks why not [0-9]*, and the sheep already answered: the star matches the empty string, so [0-9]* would "match" at every position of a text with no digits at all. Reach for + whenever at least one is required.
الـ quantifier (المكمِّم) ينطبق على ما يسبقه مباشرة: حرف واحد، أو فئة واحدة، أو مجموعة واحدة بين أقواس. إذن [0-9]+ عدد صحيح من رقم واحد أو أكثر، وعلى «Chapter 12 of 3» يجد 12 عند 8 و3 عند 14. ويسأل SLP3 لماذا لا نستخدم [0-9]*، والخراف أجابت بالفعل: النجمة تطابق السلسلة الفارغة، فـ [0-9]* كان «سيطابق» عند كل موضع في نص لا أرقام فيه إطلاقًا. استخدم + كلما كان المطلوب واحدًا على الأقل.
The wildcardالرمز الشامل
The period matches any single character. In Python's default mode that is any character except a newline, and the DOTALL flag lifts the exception; in JavaScript the dot excludes the line terminators and the s flag lifts it (Python re documentation; MDN). Under a star it becomes the most powerful and most dangerous idiom in the language: .* is any string of zero or more characters. a.*b is an a, then anything, then a b, and rose.*rose finds two roses with anything between.
النقطة تطابق أي حرف واحد. في الوضع الافتراضي لـ Python هذا يعني أي حرف عدا السطر الجديد، والعلَم DOTALL يرفع هذا الاستثناء. وفي JavaScript تستثني النقطة فواصل الأسطر، والعلَم s يرفع ذلك (توثيق Python re، وMDN). وتحت النجمة تصبح أقوى عبارة في اللغة وأخطرها: .* أي سلسلة من صفر حرف أو أكثر. a.*b هو a ثم أي شيء ثم b، وrose.*rose يجد كلمتي rose بينهما أي شيء.
Greedy versus lazyالجشع مقابل الكسول
Here is the question that decides whether .* does what you meant. Run <.*> on the string <a><b>. You probably wanted the first tag. You get the whole string, because regular expressions always match the largest string they can; SLP3 says the patterns are greedy. The star grabs everything up to the end and then backs off only as far as needed for the final > to match, which is the last one. Adding a question mark after a quantifier makes it lazy: *? and +? match as little as possible, expanding only when the rest of the pattern cannot otherwise succeed (MDN, Python re documentation).
هذا هو السؤال الذي يحدد هل يفعل .* ما قصدته. شغّل <.*> على السلسلة <a><b>. على الأرجح أردت الوسم الأول، لكنك تحصل على السلسلة كلها، لأن التعابير النمطية تطابق دائمًا أطول سلسلة ممكنة، ويقول SLP3 إن الأنماط greedy (جشعة). النجمة تأخذ كل شيء حتى النهاية ثم تتراجع فقط بالقدر اللازم كي تطابق > الأخيرة في النمط، وهي آخر > في النص. وإضافة علامة استفهام بعد المكمِّم تجعله كسولًا (lazy): *? و+? تطابقان أقل قدر ممكن، ولا تتوسعان إلا حين لا يستطيع باقي النمط أن ينجح بغير ذلك (MDN، توثيق Python re).
| Patternالنمط | Stringالسلسلة | Matchesالمطابقات | Length of first matchطول المطابقة الأولى |
|---|---|---|---|
| <.*><.*> | <a><b><a><b> | one match, <a><b> at 0مطابقة واحدة، <a><b> عند 0 | 66 |
| <.*?><.*?> | <a><b><a><b> | two matches, <a> at 0 and <b> at 3مطابقتان، <a> عند 0 و<b> عند 3 | 33 |
| a.*ba.*b | xaxbxbxxaxbxbx | one match, axbxb at 1مطابقة واحدة، axbxb عند 1 | 55 |
| a.*?ba.*?b | xaxbxbxxaxbxbx | one match, axb at 1مطابقة واحدة، axb عند 1 | 33 |
Worked exampleمثال محلول
Predicting a.*b against a.*?b on xaxbxbxالتنبؤ بنتيجة a.*b مقابل a.*?b على xaxbxbx
Find where a match can startحدّد أين يمكن أن تبدأ المطابقة
The only a is at index 1, so both patterns start there.حرف a الوحيد عند الموضع 1، لذلك يبدأ النمطان كلاهما من هناك.Greedyالجشع
.* takes everything to the end, xbxbx, then gives back one character at a time until a b can match. The last b is at index 5, so the match is axbxb, indices 1 to 5..* يأخذ كل شيء حتى النهاية، xbxbx، ثم يعيد حرفًا واحدًا في كل مرة حتى يمكن أن يطابق b. آخر b عند الموضع 5، فتكون المطابقة axbxb، من الموضع 1 إلى 5.Lazyالكسول
.*? starts by taking nothing and tries b at index 2; it is an x, so the star extends by one. Now b at index 3 matches. The match is axb, indices 1 to 3..*? يبدأ بأخذ لا شيء ويجرب b عند الموضع 2، فيجده x، فتمتد النجمة بحرف واحد. الآن b عند الموضع 3 يطابق. المطابقة هي axb، من الموضع 1 إلى 3.Resultالنتيجة
Greedy: axbxb (5 characters). Lazy: axb (3 characters). Same start, different end.الجشع: axbxb (5 أحرف). الكسول: axb (3 أحرف). البداية نفسها، والنهاية مختلفة.
Quick checkاختبار سريع
Which span does the lazy pattern a.*?b match first inside the string xaxbxbx?ما المدى الذي يطابقه النمط الكسول a.*?b أولًا داخل السلسلة xaxbxbx؟
Quick checkاختبار سريع
What does the star quantifier require of the element before it?ماذا يشترط مكمِّم النجمة على العنصر الذي قبله؟
Recall
Predict the first match of a.*b and of a.*?b on the string xaxbxbx, with indices.تنبأ بالمطابقة الأولى لكل من a.*b و a.*?b على السلسلة xaxbxbx، مع المواضع.
Everything so far matched characters. The last two regex tools match positions. ^The matches The only at the start of a line, $ finds a trailing space at the end of one, and ^The dog\.$ matches a line that is exactly "The dog." and nothing else (SLP3, section 2.6.3).
كل ما سبق كان يطابق حروفًا. أما آخر أداتين في الـ regex فتطابقان مواضع. ^The يطابق The فقط في بداية السطر، و $ يجد مسافة زائدة في نهاية السطر، و^The dog\.$ يطابق سطرًا هو «The dog.» بالضبط ولا شيء غيره (SLP3, section 2.6.3).
These are anchors, and the crucial property is that they consume nothing. An anchor matches the empty string at a position that satisfies a condition, so the\b the can match "the the": the boundary sits between the e and the space without using up either. In Python, ^ matches the start of the string, and in MULTILINE mode also immediately after each newline; $ matches the end of the string or just before the final newline, and in MULTILINE mode before every newline (Python re documentation). JavaScript's m flag does the same job, which is why the tester below has one.
هذه هي anchors (المراسي)، وخاصيتها الحاسمة أنها لا تستهلك شيئًا. المرساة تطابق السلسلة الفارغة عند موضع يحقق شرطًا، لذلك يمكن لـ the\b the أن يطابق «the the»: الحد يقع بين e والمسافة دون أن يستهلك أيًا منهما. في Python تطابق ^ بداية السلسلة، وفي وضع MULTILINE تطابق أيضًا مباشرة بعد كل سطر جديد. وتطابق $ نهاية السلسلة أو ما قبل السطر الجديد الأخير مباشرة، وفي وضع MULTILINE تطابق قبل كل سطر جديد (توثيق Python re). والعلَم m في JavaScript يؤدي المهمة نفسها، ولهذا يوجد في أداة الاختبار أدناه.
That is what "line-based formats" on the slide means in practice: real files are one record per line, and the multiline flag turns ^ and $ into per-line assertions. A comments filter on a corpus file, and a date extractor on a log, are the same pattern shape.
هذا ما تعنيه عبارة «الصيغ القائمة على الأسطر» (line-based formats) في الشريحة عمليًا: الملفات الحقيقية سجل واحد في كل سطر، والعلَم متعدد الأسطر يحوّل ^ و$ إلى شروط على مستوى كل سطر. مرشّح التعليقات على ملف مدوّنة، ومستخرج التواريخ من سجل (log)، لهما شكل النمط نفسه.
| Patternالنمط | Text (one record per line)النص (سجل واحد في كل سطر) | Matches with mالمطابقات مع m | Matches without mالمطابقات بدون m |
|---|---|---|---|
| ^#.*$^#.*$ | # comment, text line, # another# comment، text line، # another | 2 matches: # comment and # another, each at the start of its line2 مطابقتان: # comment و# another، كل منهما في بداية سطرها | 00 |
| ^\d{4}-\d{2}-\d{2}^\d{4}-\d{2}-\d{2} | 2026-09-16 boot, user logged in, 2026-09-17 shutdown2026-09-16 boot، user logged in، 2026-09-17 shutdown | 2 matches: the timestamps opening lines 1 and 32 مطابقتان: الطابعان الزمنيان في بداية السطرين 1 و3 | 11 |
Without the flag, ^ sees only the start of the whole string, so the comments filter finds nothing and the date pattern catches only a first line that happens to begin with a timestamp. With the flag, each newline resets ^ and $, which is exactly how you scan a log or strip comment lines from a file. Flip the m flag on the ^The preset in the tester below to feel the difference.
بدون العلَم، لا ترى ^ إلا بداية السلسلة كلها، فلا يجد مرشّح التعليقات شيئًا، ولا يلتقط نمط التاريخ إلا سطرًا أول يصادف أنه يبدأ بطابع زمني. ومع العلَم، كل سطر جديد يعيد ضبط ^ و$، وهذا بالضبط ما تفعله حين تمسح سجلًا أو تحذف أسطر التعليقات من ملف. بدّل العلَم m على المثال الجاهز ^The في أداة الاختبار أدناه لتشعر بالفرق.
| Anchorالمرساة | Position it assertsالموضع الذي تشترطه | Exampleمثال |
|---|---|---|
| ^^ | Start of the string, or of a line with the multiline flagبداية السلسلة، أو بداية السطر مع العلَم متعدد الأسطر | ^The finds The at index 0 of "The dog"^The يجد The عند الموضع 0 في «The dog» |
| $$ | End of the string, or of a line with the multiline flagنهاية السلسلة، أو نهاية السطر مع العلَم متعدد الأسطر | \.$ finds the period at index 7 of "The dog."\.$ يجد النقطة عند الموضع 7 في «The dog.» |
| \b\b | Between a word character and a non-word character, or a string edgeبين حرف كلمة وحرف ليس من حروف الكلمة، أو عند طرف السلسلة | \bthe\b finds the at index 0 of "the other theme"\bthe\b يجد the عند الموضع 0 في «the other theme» |
| \B\B | Any position that is not a word boundaryأي موضع ليس حد كلمة | \Bthe finds the inside other\Bthe يجد the داخل other |
The word boundaryحد الكلمة
The slide says \b is useful for matching whole words, and the canonical example is the word "the". Plain the also matches inside other and theme. \bthe\b requires a boundary on each side, so on "the other theme" it lights only the first word. A word character is a letter, a digit or an underscore, and the boundary is the seam between such a character and anything else, or a string edge (Python re documentation). Python's own examples make the rule vivid: r'\bat\b' matches at, at., (at) and the at in "as at ay", but not attempt or atlas.
تقول الشريحة إن \b مفيد لمطابقة الكلمات الكاملة، والمثال الكلاسيكي هو الكلمة «the». النمط المجرد the يطابق أيضًا داخل other وtheme. أما \bthe\b فيشترط boundary (حدًا) على كل جانب، فعلى «the other theme» لا يضيء إلا الكلمة الأولى. حرف الكلمة (word character) هو حرف أبجدي أو رقم أو شرطة سفلية، والحد هو الفاصل بين حرف كهذا وأي شيء آخر، أو طرف السلسلة (توثيق Python re). وأمثلة Python نفسها توضح القاعدة: r'\bat\b' يطابق at وat. و(at) وat في «as at ay»، لكنه لا يطابق attempt ولا atlas.
Digits count as word characters too, which produces the example SLP3 uses to check that you have understood the definition rather than memorized "letters". \b99\b matches in "There are 99 bottles" and in "$99", because a dollar sign is not a word character, but not in "299", because the 2 is. On "There are 299 bottles, $99 each" it finds exactly one match, the 99 at index 24.
الأرقام تُعدّ حروف كلمة أيضًا، ومن هنا يأتي المثال الذي يستخدمه SLP3 ليتحقق أنك فهمت التعريف بدل أن تحفظ «حروفًا أبجدية». \b99\b يطابق في «There are 99 bottles» وفي «$99»، لأن علامة الدولار ليست حرف كلمة، لكنه لا يطابق في «299»، لأن 2 حرف كلمة. وعلى «There are 299 bottles, $99 each» يجد مطابقة واحدة بالضبط، هي 99 عند الموضع 24.
SLP3 tells the story of the word "the" as a precision and recall exercise. the misses The at the start of a sentence, a false negative, so you write [tT]he. Now it hits other and there, false positives, so you write \b[tT]he\b. Every regex you write for a real corpus goes through the same two-sided tuning, and the boundary is usually the second fix.
يروي SLP3 قصة الكلمة «the» كتمرين في الدقة (precision) والاستدعاء (recall). النمط the يفوّت The في بداية الجملة، وهذا سلبي كاذب (false negative)، فتكتب [tT]he. الآن يصيب other وthere، وهذه إيجابيات كاذبة (false positives)، فتكتب \b[tT]he\b. كل regex تكتبه لمدوّنة حقيقية يمر بهذا الضبط نفسه من الجهتين، والحد عادةً هو الإصلاح الثاني.
The six aliasesالاختصارات الستة
Some classes are needed so often that they get a backslash shorthand. Slide 65 lists six, in three complementary pairs. Each lower case alias is a class, and its upper case partner is the negation of that class.
بعض الفئات نحتاجها كثيرًا لدرجة أنها تحصل على اختصار بشرطة مائلة عكسية. تسرد الشريحة 65 ستة منها، في ثلاثة أزواج متتامة. كل اختصار بحرف صغير فئة، وشريكه بحرف كبير هو نفي تلك الفئة.
| Aliasالاختصار | Expansionالتوسعة | Matchesيطابق | First match in the exampleالمطابقة الأولى في المثال |
|---|---|---|---|
| \d\d | [0-9][0-9] | Any digitأي رقم | Party of 5Party of 5 |
| \D\D | [^0-9][^0-9] | Any non-digitأي حرف ليس رقمًا | Blue moonBlue moon |
| \w\w | [a-zA-Z0-9_][a-zA-Z0-9_] | Any alphanumeric or underscoreأي حرف أبجدي أو رقم أو شرطة سفلية | DaiyuDaiyu |
| \W\W | [^\w][^\w] | A non-alphanumericحرف ليس أبجديًا ولا رقمًا | !!!!!!!! |
| \s\s | [ \r\t\n\f][ \r\t\n\f] | Whitespace: space, tab, newlineمسافة بيضاء: مسافة، أو جدولة (tab)، أو سطر جديد | in Concordin Concord |
| \S\S | [^\s][^\s] | Non-whitespaceليس مسافة بيضاء | in Concordin Concord |
The expansions in the table are the SLP3 definitions, and they are ASCII. Real engines differ at the edges, and the differences matter for Arabic. In Python 3, a pattern on a str treats \d as any Unicode decimal digit, including Arabic-Indic digits, \w as any Unicode alphanumeric plus the underscore, so Arabic letters count, and \s as anything str.isspace() accepts, which includes the non-breaking space; the ASCII flag switches all three back to the table above, with \s as [ \t\n\r\f\v] (Python re documentation). JavaScript keeps \w at letters, digits and underscore and \d at [0-9], while its \s covers all Unicode whitespace and line terminators (MDN). So a boundary such as \b, which is defined in terms of \w, falls in different places for the same Arabic sentence in the two languages. This is the "language-dependent" warning from slide 57 in its most practical form.
التوسعات في الجدول هي تعريفات SLP3، وهي ASCII. المحركات الحقيقية تختلف عند الأطراف، وهذه الفروق مهمة للعربية. في Python 3، النمط المطبَّق على str يعامل \d كأي رقم عشري في Unicode، بما فيها الأرقام العربية الهندية (٠١٢٣)، ويعامل \w كأي حرف أو رقم في Unicode مع الشرطة السفلية، فتُحسب الحروف العربية، ويعامل \s كأي شيء يقبله str.isspace()، بما فيه المسافة غير القابلة للكسر (non-breaking space). والعلَم ASCII يعيد الثلاثة إلى ما في الجدول أعلاه، مع \s بمعنى [ \t\n\r\f\v] (توثيق Python re). أما JavaScript فتُبقي \w على الحروف اللاتينية والأرقام والشرطة السفلية، و\d على [0-9]، بينما يغطي \s فيها كل مسافات Unicode وفواصل الأسطر (MDN). لذلك فإن حدًا مثل \b، المعرَّف بدلالة \w، يقع في أماكن مختلفة للجملة العربية نفسها في اللغتين. وهذا هو تحذير «الاعتماد على اللغة» من الشريحة 57 في أكثر صوره عملية.
A backslash works both waysالشرطة المائلة العكسية تعمل في الاتجاهين
Inside a pattern, a backslash before a special character makes it literal: \. is a period, \^ is a caret. The same backslash before an ordinary letter creates an alias such as \d or \b. The full table of escaped specials, from K\*A\*P\*L\*A\*N to the raw-string question, comes in the next part.
داخل النمط، الشرطة المائلة العكسية قبل حرف خاص تجعله حرفيًا: \. نقطة، و\^ علامة ^. والشرطة نفسها قبل حرف عادي تنشئ اختصارًا مثل \d أو \b. الجدول الكامل للحروف الخاصة المهروبة، من K\*A\*P\*L\*A\*N إلى سؤال السلاسل الخام (raw string)، يأتي في الجزء التالي.
Quick checkاختبار سريع
Which pattern matches the standalone word the but not other or theme?أي نمط يطابق الكلمة المستقلة the ولا يطابق other ولا theme؟
Quick checkاختبار سريع
Which alias expands to the class [a-zA-Z0-9_]?أي اختصار يتوسع إلى الفئة [a-zA-Z0-9_]؟
Recall
Expand \w and \s, and name their negations.وسّع \w و \s، وسمِّ نفي كل منهما.
Recall
What are the three meanings of the caret, and which one does Python or JavaScript apply to a caret outside brackets?ما المعاني الثلاثة للعلامة ^، وأيها تطبقه Python أو JavaScript على ^ خارج الأقواس؟
Recall
Write a regex for a word starting with a capital letter and say what each piece does.اكتب regex لكلمة تبدأ بحرف كبير، واشرح ما تفعله كل قطعة.
Check every row yourselfتحقق من كل صف بنفسك
The tester below loads every example from slides 59 to 65, the greedy and lazy pairs, and the ELIZA rule with its captured group. Load a preset, read the first match, then edit the pattern and watch the highlight move. Try a^b to see the erratum with your own eyes, and switch the m flag off on the ^The preset to see anchors change meaning.
أداة الاختبار أدناه تحمّل كل مثال من الشرائح 59 إلى 65، وأزواج الجشع والكسول، وقاعدة ELIZA مع مجموعتها الملتقطة. حمّل مثالًا جاهزًا، واقرأ المطابقة الأولى، ثم عدّل النمط وراقب التظليل وهو يتحرك. جرّب a^b لترى الخطأ في الشريحة بعينيك، وأطفئ العلَم m على المثال الجاهز ^The لترى المراسي يتغير معناها.
HE SAYS YOU ARE DEPRESSED MUCH OF THE TIME.- Matchالتطابق 1at indexعند الموضع 0HE SAYS YOU ARE DEPRESSED MUCH OF THE TIME.$1 = DEPRESSED
The tester runs the browser's JavaScript RegExp engine. Its \s and \d follow the ECMAScript definitions, and . excludes the four line terminators unless s is on, so a Python result can differ by a character in edge cases. Patterns that would match the empty string, such as a*, advance one character per empty match.يشغّل المختبر محرك RegExp الخاص بـJavaScript في المتصفح. يتبع \s و\d فيه تعريفات ECMAScript، ولا تطابق . محارف نهاية السطر الأربعة إلا إذا فُعِّل s، لذلك قد تختلف نتيجة Python بمحرف واحد في الحالات الطرفية. والأنماط التي قد تطابق سلسلة فارغة، مثل a*، تتقدم محرفًا واحدًا عند كل تطابق فارغ.
Recapالخلاصة
If you remember nothing elseإن لم تتذكر شيئاً آخر فتذكّر هذا
- ELIZA is a cascade of keyword-triggered decomposition and reassembly rules: .* YOU ARE (DEPRESSED|SAD) .* becomes I AM SORRY TO HEAR YOU ARE \1. The Eliza effect names our habit of reading understanding into such echoes.ELIZA سلسلة من قواعد التفكيك (decomposition) وإعادة التركيب (reassembly) تطلقها كلمات مفتاحية: النمط .* YOU ARE (DEPRESSED|SAD) .* يصبح I AM SORRY TO HEAR YOU ARE \1. وظاهرة Eliza effect هي ميلنا إلى أن نقرأ فهمًا في مثل هذا الصدى.
- NLP uses regex for tokenization and pre-tokenization, normalization of dates and numbers, filtering and cleaning, and feature extraction. Regex is language- and task-dependent.تستخدم NLP التعابير النمطية (regex) في التقطيع (tokenization) والتقطيع المسبق (pre-tokenization)، وفي توحيد صيغ التواريخ والأرقام (normalization)، وفي الترشيح والتنظيف، وفي استخراج السمات (feature extraction). والـ regex يعتمد على اللغة وعلى المهمة.
- Literals match themselves, abc is concatenation, a|b is disjunction, parentheses set scope. [mM], [a-z] and [^0-9] each match exactly one character.الحروف الحرفية تطابق نفسها، و abc تسلسل، و a|b اختيار، والأقواس تحدد النطاق. كل من [mM] و [a-z] و [^0-9] يطابق حرفًا واحدًا بالضبط.
- The caret has three faces: an anchor outside brackets, negation when first inside brackets, a literal elsewhere inside brackets. In Python and JavaScript a caret outside brackets is always an anchor, so a literal needs \^.للعلامة ^ ثلاثة وجوه: مرساة خارج الأقواس، ونفي إذا جاءت أولًا داخل الأقواس، وحرف عادي في أي موضع آخر داخل الأقواس. في Python و JavaScript تكون ^ خارج الأقواس مرساة دائمًا، لذلك يحتاج الحرف العادي إلى \^.
- * is zero or more, + one or more, ? zero or one, {n} exactly n, {m,n} between m and n. The dot is any character except a newline, so .* is any string.* تعني صفرًا أو أكثر، و + واحدًا أو أكثر، و ? صفرًا أو واحدًا، و {n} عدد n بالضبط، و {m,n} بين m و n. والنقطة أي حرف عدا السطر الجديد، لذلك .* تعني أي سلسلة نصية.
- Quantifiers are greedy. *? and +? are lazy: <.*> eats all of <a><b>, <.*?> stops at <a> and then finds <b>.المكمِّمات (quantifiers) جشعة. أما *? و +? فكسولة: <.*> يبتلع كامل <a><b>، بينما <.*?> يتوقف عند <a> ثم يجد <b>.
- ^ and $ anchor line edges, \b is a zero-width word boundary. \bthe\b matches the but not other, and \b99\b matches in $99 but not in 299.^ و $ تثبّتان طرفي السطر، و \b حد كلمة عرضه صفر. النمط \bthe\b يطابق the ولا يطابق other، و \b99\b يطابق في $99 ولا يطابق في 299.
- \d is [0-9], \D is [^0-9], \w is [a-zA-Z0-9_], \W is [^\w], \s is [ \r\t\n\f], \S is [^\s]. Escape a literal special character with a backslash.\d هي [0-9]، و \D هي [^0-9]، و \w هي [a-zA-Z0-9_]، و \W هي [^\w]، و \s هي [ \r\t\n\f]، و \S هي [^\s]. لمطابقة حرف خاص كما هو، اسبقه بشرطة مائلة عكسية.
Sourcesالمصادر
- Speech and Language Processing, 3rd edition draft, chapter 2: Words and TokensBookJurafsky and Martin, StanfordDraft of August 19, 2026. Section 2.6 and Figs 2.8 to 2.14 are the tables on these slides; section 2.6.7 gives the ELIZA rules, and the opening page reports ELIZA's reception, citing Weizenbaum (1976).مسودة 19 أغسطس 2026. القسم 2.6 والأشكال من 2.8 إلى 2.14 هي جداول هذه الشرائح، والقسم 2.6.7 يعطي قواعد ELIZA، والصفحة الافتتاحية تذكر كيف استُقبل ELIZA مستشهدةً بـ Weizenbaum (1976).(opens in a new tab)(يفتح في تبويب جديد)
- ELIZA: A Computer Program for the Study of Natural Language Communication Between Man and MachinePaperCommunications of the ACM 9(1):36-45, January 1966 (doi:10.1145/365153.365168)Transcript on pp. 36-37, decomposition and reassembly rules and the 50-keyword dictionary on p. 38.المحادثة في الصفحتين 36 و37، وقواعد التفكيك وإعادة التركيب وقاموس الكلمات المفتاحية الخمسين في الصفحة 38.(opens in a new tab)(يفتح في تبويب جديد)
- re: Regular expression operationsDocsPython documentationDot and DOTALL, quantifiers, the <a> b <c> non-greedy example, MULTILINE, \b, aliases in Unicode and ASCII mode, sets and [^^].النقطة و DOTALL، والمكمِّمات، ومثال عدم الجشع <a> b <c>، و MULTILINE، و \b، والاختصارات في وضعي Unicode و ASCII، والمجموعات و [^^].(opens in a new tab)(يفتح في تبويب جديد)
- QuantifierDocsMDN Web DocsGreedy versus lazy, and the /a*?/ example.الجشع مقابل الكسول، ومثال /a*?/.(opens in a new tab)(يفتح في تبويب جديد)
- WildcardDocsMDN Web DocsThe dot excludes line terminators unless the s flag is set.النقطة تستثني فواصل الأسطر ما لم يُضبط العلَم s.(opens in a new tab)(يفتح في تبويب جديد)
- Character class escapeDocsMDN Web DocsJavaScript definitions of \d, \w and \s.تعريفات JavaScript لـ \d و \w و \s.(opens in a new tab)(يفتح في تبويب جديد)
- Mastering Regular Expressions, 3rd editionBookO'Reilly (Jeffrey Friedl), 2006Backtracking and greediness in depth.التراجع (backtracking) والجشع بتعمق.(opens in a new tab)(يفتح في تبويب جديد)
- ELIZA effectArticleWikipediaThe slide's wording comes from an earlier revision of this article, whose current lead describes the effect as a tendency to project human traits onto rudimentary computer programs. The quoted definition of the specific form and the cash machine example are from Hofstadter, Fluid Concepts and Creative Analogies, Basic Books, 1995.صياغة الشريحة مأخوذة من نسخة سابقة لهذه المقالة، أما مقدمتها الحالية فتصف الأثر بأنه ميل إلى إسقاط صفات بشرية على برامج حاسوبية بدائية. والتعريف المقتبس للشكل الخاص ومثال جهاز الصرف الآلي مأخوذان من Hofstadter، كتاب Fluid Concepts and Creative Analogies، دار Basic Books، عام 1995.(opens in a new tab)(يفتح في تبويب جديد)
Part 09: Regular expressions in practiceالتعابير النمطية عمليا
Escaping, precedence and groups, substitutions with backreferences, lookarounds, the cheat sheets, the GPT-2 pre-tokenizer regex, and the engineering habits that keep patterns correct and fast.الهروب (escaping)، والأسبقية والمجموعات، والاستبدال مع المراجع الخلفية (backreferences)، والنظر حول النمط (lookarounds)، وأوراق المراجعة، وتعبير المُقسِّم المسبق في GPT-2، والعادات الهندسية التي تبقي الأنماط صحيحة وسريعة.
6 concepts6 مفاهيم, ، slides 66-78الشرائح 66-78
Why this part mattersلماذا يهمّ هذا الجزء
Part 08 gave you the alphabet of regular expressions. This part is about using it under real conditions: patterns that must match a literal period, patterns that must reorder a date, patterns that must enforce three rules at once, and one pattern that quietly decides how every GPT-2 style tokenizer sees text.
Most BPE tokenizers you will train or inspect, GPT-2's included, start with a regex pre-tokenizer, every cleaning script for an Arabic corpus is a chain of substitutions, and the exam asks you to work precedence, substitution and lookahead by hand. The cheat sheets on slides 73 to 75 are here as reference tables you can come back to, and the workbench lets you test every claim in the browser.
أعطاك الجزء 08 أبجدية التعابير النمطية (regular expressions). أما هذا الجزء فيتناول استخدامها في ظروف حقيقية: أنماط يجب أن تطابق نقطة حرفية، وأنماط يجب أن تعيد ترتيب تاريخ، وأنماط يجب أن تفرض ثلاث قواعد في آن واحد، ونمط واحد يحدّد بصمت كيف يرى كل tokenizer على طريقة GPT-2 النص.
معظم الـ tokenizers من نوع BPE التي ستدرّبها أو تفحصها، ومنها tokenizer الخاص بـ GPT-2، تبدأ بـ pre-tokenizer مبني على regex، وكل سكربت لتنظيف مدوّنة عربية هو سلسلة من عمليات الاستبدال، والامتحان يطلب منك أن تحلّ مسائل الأولوية والاستبدال والـ lookahead يدويًا. أوراق الملخّص (cheat sheets) في الشرائح 73 إلى 75 موجودة هنا كجداول مرجعية يمكنك الرجوع إليها، ومنصة التجربة (workbench) تتيح لك اختبار كل ادعاء في المتصفح.
By the end you canفي نهاية هذا الجزء ستستطيع
- Escape metacharacters and predict what (cat|dog)s versus cat|dogs matches using the precedence ladder.أن تُهرّب (escape) المحارف الخاصة (metacharacters) وتتوقع ما يطابقه النمط (cat|dog)s مقابل النمط cat|dogs باستخدام سُلّم الأولوية (precedence).
- Write a capture-group substitution that reorders a date and a backreference that finds a doubled word.أن تكتب استبدالًا بمجموعات الالتقاط (capture groups) يعيد ترتيب تاريخ، ومرجعًا خلفيًا (backreference) يجد كلمة مكرّرة.
- Write a lookahead-based password check and explain why lookahead consumes nothing.أن تكتب فحصًا لكلمة المرور مبنيًا على الـ lookahead، وتشرح لماذا لا يستهلك الـ lookahead أي نص.
- Explain each alternative of the GPT-2 pre-tokenizer on a given string and why it needs \p{L}.أن تشرح كل بديل في الـ pre-tokenizer الخاص بـ GPT-2 على نص معطى، ولماذا يحتاج إلى \p{L}.
- Recognize catastrophic backtracking, give an example, and name two ways to make a pattern Unicode-aware.أن تتعرّف على التراجع الكارثي (catastrophic backtracking) وتعطي مثالًا عليه، وتسمّي طريقتين لجعل النمط واعيًا بـ Unicode.
Suppose you want to find every mention of Dr. in a corpus. The obvious pattern Dr. also matches Drs and Dry, because a period in a pattern means any character. Written as Dr\., it matches only the period. That is the whole idea of escaping: fourteen characters, . ^ $ * + ? ( ) [ ] { } | \, mean something to the engine, and a backslash returns them to their plain selves.
لنفترض أنك تريد إيجاد كل ذكر لـ Dr. في مدوّنة نصية. الـ pattern البديهي Dr. يطابق أيضًا Drs وDry، لأن النقطة داخل النمط تعني أي محرف. وعندما يُكتب بالشكل Dr\. فإنه يطابق النقطة فقط. هذه هي فكرة الـ escaping (التهريب) كاملة: أربعة عشر محرفًا، . ^ $ * + ? ( ) [ ] { } | \، لها معنى خاص عند المحرّك، والـ backslash يعيدها إلى طبيعتها العادية.
Escapes from SLP3 Figure 2.14, plus the two that run the other wayمحارف التهريب من الشكل 2.14 في SLP3، مضافًا إليها الاثنان اللذان يعملان في الاتجاه المعاكس
- \*
- an asterisk, as in K*A*P*L*A*Nنجمة، كما في K*A*P*L*A*N
- \.
- a period, as in Dr. Livingston, I presumeنقطة، كما في Dr. Livingston, I presume
- \?
- a question mark, as in Why don't they come and lend a hand?علامة استفهام، كما في Why don't they come and lend a hand?
- \n
- a newline (the backslash gives a plain letter a special meaning)سطر جديد (newline)، وهنا يعطي الـ backslash حرفًا عاديًا معنى خاصًا
- \t
- a tab (same direction: plain letter, special meaning)مسافة جدولة (tab)، في الاتجاه نفسه: حرف عادي يأخذ معنى خاصًا
Notice that the backslash works in both directions. \. turns a special character into a literal one, while \n and \t turn plain letters into a newline and a tab. When a pattern needs a literal backslash it doubles: \\. In Python, write patterns as raw strings, r'...', so the string literal does not eat the backslashes before the regex engine sees them (Python re documentation).
لاحظ أن الـ backslash يعمل في الاتجاهين. \. يحوّل محرفًا خاصًا إلى محرف حرفي، بينما \n و\t يحوّلان حرفين عاديين إلى سطر جديد (newline) ومسافة جدولة (tab). وعندما يحتاج النمط إلى backslash حرفي فإنه يُضاعَف: \\. في Python اكتب الأنماط كسلاسل خام (raw strings)، r'...'، حتى لا تلتهم السلسلة الحرفية الـ backslashes قبل أن يراها محرّك الـ regex (توثيق Python re).
The precedence ladderسُلّم الأولوية (precedence)
Escaping decides what a character means. Precedence decides how the operators bind, and it is where most wrong answers come from. Take the pattern cat|dogs and run it on the string cats dogs cat dog. Students expect cats and dogs. The engine returns cat (inside cats), dogs, and cat again, because the disjunction operator | has the lowest precedence of all: it splits the entire expression into cat on one side and dogs on the other. Parentheses fence the alternation in, so (cat|dog)s reads as cat or dog, then s, and returns cats and dogs.
الـ escaping يحدّد ما يعنيه المحرف. أما الـ precedence (الأولوية) فتحدّد كيف ترتبط العوامل (operators)، ومنها تأتي معظم الإجابات الخاطئة. خذ النمط cat|dogs وشغّله على النص cats dogs cat dog. يتوقع الطلاب cats وdogs. لكن المحرّك يُرجع cat (داخل cats)، وdogs، ثم cat مرة أخرى، لأن عامل الاختيار (disjunction) | له أدنى أولوية على الإطلاق: فهو يقسم التعبير كله إلى cat في جهة وdogs في الجهة الأخرى. الأقواس تحصر الاختيار داخلها، فيُقرأ (cat|dog)s على أنه cat أو dog، ثم s، ويُرجع cats وdogs.
| Patternالنمط | Reads asيُقرأ على أنه | Matchesالمطابقات |
|---|---|---|
| cat|dogscat|dogs | cat, or dogscat، أو dogs | cat, dogs, catcat, dogs, cat |
| (cat|dog)s(cat|dog)s | cat or dog, then scat أو dog، ثم s | cats, dogscats, dogs |
SLP3 (section 2.6.4) gives the full ladder. Parentheses bind tightest, then the counters (the quantifiers), then plain sequences and anchors, and last of all the disjunction. This is why the* matches theeeee and not thethe: the star applies to the single letter e, not to the whole sequence. It is why the|any matches the or any but never thany. And it is why guppy|ies fails to match guppies: it means guppy or ies, so the fix is gupp(y|ies).
يعطي SLP3 (القسم 2.6.4) السُّلّم كاملًا. الأقواس هي الأشد ارتباطًا، ثم العدّادات (أي الـ quantifiers)، ثم التتابعات العادية والـ anchors (المراسي)، وفي الأخير الاختيار (disjunction). لهذا يطابق the* النص theeeee وليس thethe: فالنجمة تنطبق على الحرف e وحده، لا على التتابع كله. ولهذا يطابق the|any إما the أو any لكنه لا يطابق thany أبدًا. ولهذا أيضًا يفشل guppy|ies في مطابقة guppies: فهو يعني guppy أو ies، والحل هو gupp(y|ies).
Operator precedence, highest first (SLP3, section 2.6.4)أولوية العوامل، من الأعلى إلى الأدنى (SLP3، القسم 2.6.4)
- 1 Parenthesis1 الأقواس
- ( )
- 2 Counters2 العدّادات (quantifiers)
- * + ? {}
- 3 Sequences and anchors3 التتابعات والمراسي (anchors)
- the, ^my end$
- 4 Disjunction4 الاختيار (disjunction)
- |
The same ladder explains a subtler example from SLP3. Column [0-9]+ * matches one column label such as Column 1 followed by any number of spaces, because the star applies only to the final space. To repeat over a whole row of labels, Column 1 Column 2 Column 3, the sequence has to be fenced first. SLP3 writes (Column [0-9]+ +)*, which needs a space after every label, so on this row it stops before Column 3; (Column [0-9]+ *)* allows zero trailing spaces and takes the whole row.
السُّلّم نفسه يفسّر مثالًا أدقّ من SLP3. النمط Column [0-9]+ * يطابق عنوان عمود واحدًا مثل Column 1 متبوعًا بأي عدد من المسافات، لأن النجمة تنطبق على المسافة الأخيرة فقط. ولتكرار المطابقة على صف كامل من العناوين، Column 1 Column 2 Column 3، يجب أن يُحصر التتابع بين أقواس أولًا. يكتب SLP3 النمط (Column [0-9]+ +)*، الذي يتطلّب مسافة بعد كل عنوان، لذلك يتوقف على هذا الصف قبل Column 3؛ أما (Column [0-9]+ *)* فيسمح بصفر مسافات في النهاية ويأخذ الصف كله.
Grouping without rememberingالتجميع دون تذكّر
Parentheses do two jobs at once. They set the scope of an operator, and they create a capture group that stores whatever the group matched. Sometimes you want only the first job. Thenon-capturing form (?:...) groups without allocating a register, which keeps the numbering of the groups you do care about stable. SLP3 (2.17) uses it to skip fourteen dates and capture only the fifteenth: (?:\d\d/\d\d/\d\d\d\d\s+){14}(\d\d/\d\d/\d\d\d\d). The repeated dates are grouped so that the counter {14} applies to the whole date, and only the last date lands in group 1.
تؤدي الأقواس وظيفتين في الوقت نفسه. فهي تحدّد نطاق العامل، وتُنشئ capture group (مجموعة التقاط) تخزّن ما طابقته المجموعة. وأحيانًا تريد الوظيفة الأولى فقط. الصيغة غير الملتقِطة (non-capturing) (?:...) تجمّع دون حجز سجلّ (register)، وهذا يُبقي ترقيم المجموعات التي تهمّك ثابتًا. يستخدمها SLP3 (2.17) لتخطّي أربعة عشر تاريخًا والتقاط الخامس عشر فقط: (?:\d\d/\d\d/\d\d\d\d\s+){14}(\d\d/\d\d/\d\d\d\d). التواريخ المتكررة مجمّعة حتى ينطبق العدّاد {14} على التاريخ كاملًا، ولا يقع في المجموعة 1 إلا التاريخ الأخير.
Recall
Why does guppy|ies fail to match guppies, and what is the fix?لماذا يفشل النمط guppy|ies في مطابقة guppies، وما الحل؟
Quick checkاختبار سريع
Which whole word does the pattern cat|dogs match but (cat|dog)s never matches?ما الكلمة الكاملة التي يطابقها النمط cat|dogs ولا يطابقها النمط (cat|dog)s أبدًا؟
Real patterns are assembled from small pieces, tested, and grown. Start with an email address. It has a local part, an at sign and a domain, so the very simplified pattern on slide 69 is three pieces glued together: [A-Za-z0-9._]+@[A-Za-z0-9._]+. A character class of letters, digits, dots and underscores, repeated at least once, on both sides of the @. The same compose-then-test loop gives a course-code ID pattern in one line: two to four uppercase letters, an optional space, three digits, [A-Z]{2,4}\s?\d{3}, which accepts ICS 582 and COE558 and rejects ICS58 (only two digits) and ICSSS 582 (five letters). The habit is the same in both: build the smallest piece that covers the positives, then run it against the nearest negatives.
الأنماط الحقيقية تُركَّب من قطع صغيرة، وتُختبَر، ثم تُوسَّع. ابدأ بعنوان بريد إلكتروني. له جزء محلي (local part)، وعلامة @، ونطاق (domain)، لذلك فالنمط المبسّط جدًا في الشريحة 69 هو ثلاث قطع ملصقة معًا: [A-Za-z0-9._]+@[A-Za-z0-9._]+. أي character class (فئة محارف) من الحروف والأرقام والنقاط والشرطات السفلية (underscores)، مكرّرة مرة واحدة على الأقل، على جانبي الـ @. وحلقة التركيب ثم الاختبار نفسها تعطي نمطًا لرمز المقرر في سطر واحد: من حرفين إلى أربعة أحرف كبيرة، ثم مسافة اختيارية، ثم ثلاثة أرقام، [A-Z]{2,4}\s?\d{3}، وهو يقبل ICS 582 وCOE558 ويرفض ICS58 (رقمان فقط) وICSSS 582 (خمسة أحرف). والعادة واحدة في الحالتين: ابنِ أصغر قطعة تغطي الأمثلة الموجبة، ثم شغّلها على أقرب الأمثلة السالبة.
| Addressالعنوان | What matchedما طوبِق | Verdictالحكم |
|---|---|---|
| m.alraimi@kfupm.edu.sam.alraimi@kfupm.edu.sa | m.alraimi@kfupm.edu.sam.alraimi@kfupm.edu.sa | whole address, fineالعنوان كاملًا، سليم |
| first-last@x.comfirst-last@x.com | last@x.comlast@x.com | hyphen is not in the class, the local part is truncatedالشرطة ليست ضمن الفئة، فيُبتر الجزء المحلي |
| a+b@y.orga+b@y.org | b@y.orgb@y.org | plus is not in the class eitherعلامة الجمع ليست ضمن الفئة أيضًا |
| me@localhostme@localhost | me@localhostme@localhost | accepted although there is no top-level domainمقبول رغم عدم وجود نطاق علوي (top-level domain) |
The table is an error analysis, and it exposes two failure modes that pull in opposite directions. The class is too narrow: hyphens and plus signs are legal in local parts, so the pattern silently truncates them and matches the wrong substring. That is a recall problem: real addresses the pattern should catch, it catches only in part. The domain side is too loose: it accepts me@localhost, which has no top-level domain. That is a precision problem: strings the pattern should reject, it accepts. Widening the class to [A-Za-z0-9._+-]+ raises recall; requiring a dot followed by at least two letters at the end, \.[A-Za-z]{2,}$, raises precision. Each fix is one small piece, tested on representative samples, and the point of slide 69 is to iterate this way rather than to write a pattern that fits the one address in front of you.
هذا الجدول تحليل للأخطاء (error analysis)، ويكشف نمطَي فشل يسحبان في اتجاهين متعاكسين. الفئة ضيّقة أكثر من اللازم: الشرطات (-) وعلامات الجمع (+) مسموحة في الجزء المحلي، فيبترها النمط بصمت ويطابق سلسلة جزئية خاطئة. هذه مشكلة recall (الاستدعاء): عناوين حقيقية كان يجب أن يلتقطها النمط، لكنه لا يلتقطها إلا جزئيًا. وجانب النطاق متساهل أكثر من اللازم: فهو يقبل me@localhost، الذي لا يحتوي على نطاق علوي (top-level domain). هذه مشكلة precision (الدقة): سلاسل كان يجب أن يرفضها النمط، لكنه يقبلها. توسيع الفئة إلى [A-Za-z0-9._+-]+ يرفع الـ recall؛ واشتراط نقطة يتبعها حرفان على الأقل في النهاية، \.[A-Za-z]{2,}$، يرفع الـ precision. كل إصلاح قطعة صغيرة واحدة، تُختبر على عيّنات ممثِّلة، والمغزى من الشريحة 69 هو أن تكرّر العمل بهذه الطريقة بدلًا من كتابة نمط يناسب العنوان الوحيد الذي أمامك.
Capture, then reuseالتقط، ثم أعد الاستخدام
Once a pattern matches, each capture group has stored a substring, and a substitution can put them back in any order. Slide 70 shows the classic sed notation s/(\d{4})-(\d{2})-(\d{2})/$2$3$1/. Work it on an ISO date.
بمجرد أن يطابق النمط، تكون كل capture group قد خزّنت سلسلة جزئية، ويمكن لعملية الاستبدال أن تعيدها بأي ترتيب. تعرض الشريحة 70 صيغة sed الكلاسيكية s/(\d{4})-(\d{2})-(\d{2})/$2$3$1/. طبّقها على تاريخ بصيغة ISO.
Worked exampleمثال محلول
Reordering 2026-01-25إعادة ترتيب 2026-01-25
Name the groupsسمِّ المجموعات
(\d{4})-(\d{2})-(\d{2}) matches four digits, a hyphen, two digits, a hyphen, two digits. Group 1 is 2026, group 2 is 01, group 3 is 25. The hyphens are matched but not captured.(\d{4})-(\d{2})-(\d{2}) يطابق أربعة أرقام، ثم شرطة، ثم رقمين، ثم شرطة، ثم رقمين. المجموعة 1 هي 2026، والمجموعة 2 هي 01، والمجموعة 3 هي 25. الشرطات تُطابَق لكنها لا تُلتقط.Apply the slide's replacementطبّق استبدال الشريحة
$2$3$1 writes group 2, then 3, then 1 with nothing between them: 01252026. The separators vanished because a replacement only contains what you write into it.$2$3$1 يكتب المجموعة 2، ثم 3، ثم 1 بلا أي شيء بينها: 01252026. اختفت الفواصل لأن الاستبدال لا يحتوي إلا على ما تكتبه فيه.Write the separators yourselfاكتب الفواصل بنفسك
Python syntax: re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1', s) gives 01/25/2026. Swapping the first two references, \3/\2/\1, gives 25/01/2026.بصيغة Python: re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1', s) يعطي 01/25/2026. وبتبديل أول مرجعين، \3/\2/\1، تحصل على 25/01/2026.Three replacements, three outputsثلاثة استبدالات، ثلاثة مخرجات
The pattern never changes. Only the replacement string decides the order and the separators.النمط لا يتغيّر أبدًا. سلسلة الاستبدال وحدها هي التي تحدّد الترتيب والفواصل.
| Replacementالاستبدال | Outputالمخرج | Readingالقراءة |
|---|---|---|
| $2$3$1$2$3$1 | 0125202601252026 | slide 70: month, day, year, separators droppedالشريحة 70: الشهر، ثم اليوم، ثم السنة، مع حذف الفواصل |
| \2/\3/\1\2/\3/\1 | 01/25/202601/25/2026 | US order with slashes written by the replacementالترتيب الأمريكي، والشرطات المائلة يكتبها الاستبدال |
| \3/\2/\1\3/\2/\1 | 25/01/202625/01/2026 | day, month, year: the slide 72 targetاليوم، ثم الشهر، ثم السنة: الهدف المطلوب في الشريحة 72 |
The syntax of the reference differs by tool. sed and Perl write $1 or \1 inside s/.../.../; JavaScript's replace uses $1 and $& for the whole match; Python's re.sub uses \1 in a raw string and \g<0> for the whole match (Python re documentation). SLP3 (section 2.6.7) uses the same trick to move US dates to European order: re.sub(r"(\d{2})/(\d{2})/(\d{4})", r"\2-\1-\3", s) turns 10/15/2011 into 15-10-2011.
صيغة المرجع تختلف من أداة لأخرى. sed وPerl يكتبان $1 أو \1 داخل s/.../.../؛ والدالة replace في JavaScript تستخدم $1، و$& للمطابقة كاملة؛ والدالة re.sub في Python تستخدم \1 داخل سلسلة خام، و\g<0> للمطابقة كاملة (توثيق Python re). ويستخدم SLP3 (القسم 2.6.7) الحيلة نفسها لنقل التواريخ الأمريكية إلى الترتيب الأوروبي: re.sub(r"(\d{2})/(\d{2})/(\d{4})", r"\2-\1-\3", s) يحوّل 10/15/2011 إلى 15-10-2011.
A backreference is not only for replacements. Inside the pattern itself, \1 means "the same text that group 1 just captured", so (\w+) \1 finds a doubled word. SLP3's careful version, \b([A-Za-z]+)\s+\1\b, restricts the group to letters, adds word boundaries and allows any whitespace; on the the cat sat on on the mat it returns the and on. This is the mechanism behind the faster-they-ran exercise in the next concept.
الـ backreference (المرجع الخلفي) ليس للاستبدالات فقط. داخل النمط نفسه، \1 تعني "النص نفسه الذي التقطته المجموعة 1 للتو"، لذلك يجد (\w+) \1 كلمة مكرّرة. والنسخة المتأنّية في SLP3، \b([A-Za-z]+)\s+\1\b، تقصر المجموعة على الحروف، وتضيف word boundaries (حدود الكلمات)، وتسمح بأي مسافة بيضاء؛ وعلى النص the the cat sat on on the mat تُرجع the وon. وهذه هي الآلية التي يقوم عليها تمرين faster-they-ran في المفهوم التالي.
Looking without movingالنظر دون تحرّك
The email and date patterns consume text left to right. Some rules cannot be written that way. A password must be at least eight characters, contain a capital letter, and contain a digit, and the three rules overlap: the same characters count for all of them. Lookahead solves this. (?=...) requires that a pattern could match starting here, (?!...) forbids it, and neither consumes anything. SLP3 (section 2.6.8) puts it precisely: the match pointer does not advance, just as with anchors.
أنماط البريد والتاريخ تستهلك النص من اليسار إلى اليمين. لكن بعض القواعد لا يمكن كتابتها بهذه الطريقة. يجب أن تكون كلمة المرور ثمانية محارف على الأقل، وأن تحتوي على حرف كبير، وأن تحتوي على رقم، والقواعد الثلاث متداخلة: المحارف نفسها تُحسب لها جميعًا. الـ lookahead (النظر إلى الأمام) يحلّ هذه المشكلة. (?=...) يشترط أن يكون نمطٌ ما قابلًا للمطابقة بدءًا من هنا، و(?!...) يمنع ذلك، ولا يستهلك أيٌّ منهما شيئًا. ويقولها SLP3 (القسم 2.6.8) بدقة: مؤشر المطابقة لا يتقدّم، تمامًا كما في الـ anchors.
So ^(?=.*[A-Z])(?=.*\d).{8,}$ reads: at the start of the line, check that somewhere ahead there is a capital; still at the start, check that somewhere ahead there is a digit; now, still at the start, consume at least eight characters to the end. Because the two checks both begin at position 0 they can look at the same characters, which a consuming pattern could never do.
إذن يُقرأ ^(?=.*[A-Z])(?=.*\d).{8,}$ هكذا: عند بداية السطر، تحقّق من وجود حرف كبير في مكان ما أمامك؛ وما زلت عند البداية، تحقّق من وجود رقم في مكان ما أمامك؛ والآن، وما زلت عند البداية، استهلك ثمانية محارف على الأقل حتى النهاية. ولأن الفحصين يبدآن كلاهما من الموضع 0 فيمكنهما النظر إلى المحارف نفسها، وهذا ما لا يستطيعه نمط مستهلِك أبدًا.
| Candidateالمرشّحة | Lengthالطول | Capitalsالأحرف الكبيرة | Digitsالأرقام | Resultالنتيجة |
|---|---|---|---|---|
| Passw0rdXPassw0rdX | 99 | P, XP, X | 00 | acceptedمقبولة |
| passwordpassword | 88 | noneلا يوجد | noneلا يوجد | rejectedمرفوضة |
| PASSWORD1PASSWORD1 | 99 | allكلها | 11 | acceptedمقبولة |
| Pw1shortPw1short | 88 | PP | 11 | accepted, exactly 8مقبولة، 8 محارف بالضبط |
Negative lookahead is just as useful. SLP3's equation 2.18, ^(?![tT])(\w+)\b, captures a word at the start of a line only if it does not begin with t or T. Without the lookahead you would need a class that lists every other letter.
والـ lookahead السالب مفيد بالقدر نفسه. المعادلة 2.18 في SLP3، ^(?![tT])(\w+)\b، تلتقط كلمة في بداية السطر فقط إذا لم تبدأ بـ t أو T. ومن دون الـ lookahead ستحتاج إلى فئة تسرد كل الحروف الأخرى.
Recall
What does re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\2\3\1', '2026-01-25') return, and why is there no separator?ماذا يُرجع re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\2\3\1', '2026-01-25')، ولماذا لا يوجد فاصل؟
Quick checkاختبار سريع
After the lookahead ^(?=.*\d) succeeds on Passw0rdX, where does the match pointer stand?بعد أن ينجح الـ lookahead ^(?=.*\d) على Passw0rdX، أين يقف مؤشر المطابقة؟
Slide 72 is a set of six problems with no answers. Each of them uses one tool from the previous two concepts, and together they cover everything the exam can ask about escaping, each capture group and its backreference, and lookahead. Try each one in the workbench before revealing the solution. The check button compares your matches against the expected list and tells you what is missing or extra.
الشريحة 72 مجموعة من ست مسائل بلا حلول. كل واحدة منها تستخدم أداة واحدة من المفهومين السابقين، وهي معًا تغطي كل ما يمكن أن يسأل عنه الامتحان في الـ escaping، وفي كل capture group والـ backreference الخاص بها، وفي الـ lookahead. جرّب كل مسألة في منصة التجربة قبل كشف الحل. زر الفحص يقارن مطابقاتك بالقائمة المتوقعة ويخبرك بما هو ناقص أو زائد.
Match the two tags <Begin> and <\End> and nothing else.طابِق الوسمين <Begin> و<\End> ولا شيء غيرهما.
/…/gType a pattern to see live results.اكتب نمطًا لترى النتائج مباشرةً.
Patterns run in JavaScript syntax inside a worker with a 600 ms limit. Python differs in three places: backreferences in replacements are \1 not $1, named groups are (?P<name>...), and \p{L} needs the regex module.تعمل الأنماط بصياغة JavaScript داخل worker بحد زمني 600 ms. وتختلف Python في ثلاثة مواضع: المراجع الخلفية في نص الاستبدال تُكتب \1 لا $1، والمجموعات المسماة تُكتب (?P<name>...)، و\p{L} تحتاج إلى وحدة regex.
The six problems map one to one onto the tools of the previous two concepts. The tags problem rewards a negated class or an escaped backslash: <[^>]+> reads as "any run of non-closing-brackets inside brackets". The Apple problem is the one where a global i flag backfires, because it would also lowercase Juice, so the case-insensitivity has to live per letter inside a class like [Aa], or inside a scoped group like (?i:apple). The password problem is the argument for lookahead: three overlapping rules, all checked from the same position, none consuming input. The faster-they-ran sentence needs backreferences, capturing the repeated words once and reusing them as \1 and \2. The date swap is the classic capture-group substitution. The boxes problem shows that the whole-match reference, $& or \g<0>, lets you skip a group entirely when you do not need to rearrange anything.
المسائل الست تقابل أدوات المفهومين السابقين واحدة بواحدة. مسألة الوسوم (tags) تكافئ استخدام فئة منفية أو backslash مُهرَّب: يُقرأ <[^>]+> على أنه "أي سلسلة من محارف ليست أقواس إغلاق، داخل أقواس". ومسألة Apple هي التي ينقلب فيها العلم i العام ضدك، لأنه سيجعل Juice أيضًا غير حسّاسة لحالة الأحرف فيقبل حرفها الأول صغيرًا، لذلك يجب أن يكون عدم التمييز بين الحروف الكبيرة والصغيرة لكل حرف على حدة داخل فئة مثل [Aa]، أو داخل مجموعة محدودة النطاق مثل (?i:apple). ومسألة كلمة المرور هي الحجة على الـ lookahead: ثلاث قواعد متداخلة، تُفحص كلها من الموضع نفسه، ولا يستهلك أيٌّ منها المدخلات. وجملة faster-they-ran تحتاج إلى backreferences، بالتقاط الكلمات المكررة مرة واحدة وإعادة استخدامها بوصفها \1 و\2. وتبديل التاريخ هو الاستبدال الكلاسيكي بمجموعات الالتقاط. ومسألة الصناديق (boxes) تبيّن أن مرجع المطابقة الكاملة، $& أو \g<0>، يتيح لك الاستغناء عن المجموعة كليًا عندما لا تحتاج إلى إعادة ترتيب أي شيء.
Recall
Match the tags <Begin> and <\End> in the string <Begin> Hello World <\End>, and nothing else.طابِق الوسمين <Begin> و<\End> في النص <Begin> Hello World <\End>، ولا شيء غيرهما.
Recall
Match Apple Juice, apPLe Juice and APPLE Juice but not Apple juice.طابِق Apple Juice وapPLe Juice وAPPLE Juice، لكن ليس Apple juice.
Recall
Write a password check: at least 8 characters, at least one capital letter, at least one digit.اكتب فحصًا لكلمة المرور: 8 محارف على الأقل، وحرف كبير واحد على الأقل، ورقم واحد على الأقل.
Recall
Match both 'The faster they ran, the faster we ran' and 'The faster they read, the faster we read' with one pattern.طابِق الجملتين 'The faster they ran, the faster we ran' و'The faster they read, the faster we read' بنمط واحد.
Recall
Convert 2026-01-25 to 25/01/2026 with capture groups.حوِّل 2026-01-25 إلى 25/01/2026 باستخدام مجموعات الالتقاط.
Recall
Convert 'the 35 boxes' to 'the <35> boxes'.حوِّل 'the 35 boxes' إلى 'the <35> boxes'.
Slides 73 to 75 are the reference card for the whole regex block: every quantifier, character class, capture group and anchor in one place. They are reproduced here as tables so you can scan them during revision, with the two engine differences that the card leaves implicit: how line anchors behave under multiline mode, and which engines allow a variable-length lookbehind.
الشرائح 73 إلى 75 هي البطاقة المرجعية لكتلة الـ regex كلها: كل quantifier، وcharacter class، وcapture group، وanchor في مكان واحد. وهي معروضة هنا كجداول لتتصفّحها أثناء المراجعة، مع فرقين بين المحرّكات تتركهما البطاقة ضمنيين: كيف تتصرف مراسي الأسطر في وضع multiline، وأيّ المحرّكات تسمح بـ lookbehind متغيّر الطول.
Alternation and quantifiersالاختيار والـ quantifiers
- a|b
- alternation: a or bالاختيار (alternation): a أو b
- ?
- zero or one of the preceding elementصفر أو مرة واحدة من العنصر السابق
- +
- one or moreمرة واحدة أو أكثر
- *
- zero or moreصفر مرة أو أكثر
- *?
- zero or more, lazy: stop as early as the rest of the pattern allowsصفر مرة أو أكثر، بصيغة كسولة (lazy): توقّف في أبكر موضع يسمح به باقي النمط
- {N}
- exactly NN مرة بالضبط
- {N,M}
- between N and Mبين N وM مرة
The lazy form matters more than its size suggests. Greedy .* grabs as much as it can and backs off only if the rest of the pattern fails; .*? takes as little as possible and grows only when it must. Part 08 showed the difference on HTML tags.
الصيغة الكسولة (lazy) أهم مما يوحي به حجمها. الـ greedy (الجشع) .* يلتهم أكبر قدر ممكن ولا يتراجع إلا إذا فشل باقي النمط؛ أما .*? فيأخذ أقل قدر ممكن ولا يكبر إلا عند الضرورة. وقد أظهر الجزء 08 الفرق على وسوم HTML.
Pattern collectionsمجموعات المحارف في الأنماط
- [A-Z]
- one uppercase ASCII letterحرف ASCII كبير واحد
- [a-z]
- one lowercase ASCII letterحرف ASCII صغير واحد
- [0-9]
- one ASCII digitرقم ASCII واحد
- [asdf]
- one of a, s, d, fمحرف واحد من a, s, d, f
- [^asdf]
- any one character except a, s, d, fأي محرف واحد عدا a, s, d, f
Groupsالمجموعات
- (...)
- capturing group: match and remember, referenced as \1 or $1مجموعة التقاط (capturing group): تطابق وتتذكّر، ويُشار إليها بـ \1 أو $1
- (?:...)
- non-capturing group: scope for | or a quantifier, nothing rememberedمجموعة غير ملتقِطة (non-capturing group): نطاق لـ | أو لـ quantifier، ولا يُتذكَّر شيء
- (?<name>...)
- named group; Python spells it (?P<name>...)مجموعة مسمّاة (named group)؛ وتكتبها Python بالشكل (?P<name>...)
General tokensرموز عامة
- .
- any character except newlineأي محرف عدا السطر الجديد (newline)
- \n
- newlineسطر جديد (newline)
- \t
- tabمسافة جدولة (tab)
- \s
- one whitespace characterمحرف مسافة بيضاء واحد (whitespace)
- \S
- one non-whitespace characterمحرف واحد ليس مسافة بيضاء
- \w
- one word character: letter, digit or underscoreمحرف كلمة واحد (word character): حرف أو رقم أو شرطة سفلية (underscore)
- \W
- one non-word characterمحرف واحد ليس من محارف الكلمة
- \b
- word boundary, zero widthحدّ كلمة (word boundary)، عديم العرض
- \B
- not a word boundary, zero widthليس حدّ كلمة، عديم العرض
- ^
- start of string, or start of line under mبداية النص، أو بداية السطر مع العلم m
- $
- end of string, or end of line under mنهاية النص، أو نهاية السطر مع العلم m
- \\
- a literal backslashbackslash حرفي
Take one input and walk the flags. On the two-line string cat\ncar the pattern ^ca.$ shows the three flags in action. With no flags it matches nothing: ^ wants the very first position, and the dot cannot be a newline, so $ after a 3-letter match can never reach the end. Turning on m gives cat and car, one per line. Adding g reports both; without g a JavaScript exec returns only the first. The i flag is independent: it would let the pattern tolerate Cat too. Each flag flips exactly one assumption, anchor meaning, case, or how many results are returned.
خذ مدخلًا واحدًا ومرّ على الأعلام. على النص ذي السطرين cat\ncar يُظهر النمط ^ca.$ الأعلام الثلاثة وهي تعمل. من دون أعلام لا يطابق شيئًا: ^ يريد الموضع الأول تمامًا، والنقطة لا يمكن أن تكون سطرًا جديدًا، لذلك لا يمكن لـ $ بعد مطابقة من ثلاثة أحرف أن يصل إلى النهاية أبدًا. تشغيل m يعطي cat وcar، واحدة في كل سطر. وإضافة g تُبلغ عن كلتيهما؛ ومن دون g فإن exec في JavaScript يُرجع الأولى فقط. والعلم i مستقل: سيسمح للنمط بقبول Cat أيضًا. كل علم يقلب افتراضًا واحدًا بالضبط: معنى المرساة، أو حالة الأحرف، أو عدد النتائج المُرجَعة.
Flagsالأعلام (flags)
- g
- global: report every match, a JavaScript and regex101 flag; Python uses findall and sub insteadعام (global): أبلِغ عن كل مطابقة، وهو علم في JavaScript وregex101؛ أما Python فتستخدم findall وsub بدلًا منه
- m
- multiline: ^ and $ also match at each line breakمتعدد الأسطر (multiline): ^ و$ يطابقان أيضًا عند كل فاصل سطر
- i
- case-insensitiveغير حسّاس لحالة الأحرف (case-insensitive)
| Syntaxالصيغة | Nameالاسم | Exampleمثال | Resultالنتيجة |
|---|---|---|---|
| (?=...)(?=...) | positive lookaheadlookahead موجب | foo(?=bar)foo(?=bar) | foo in foobar onlyfoo في foobar فقط |
| (?!...)(?!...) | negative lookaheadlookahead سالب | foo(?!bar)foo(?!bar) | foo in foobaz onlyfoo في foobaz فقط |
| (?<=...)(?<=...) | positive lookbehindlookbehind موجب | (?<=#)\d+(?<=#)\d+ | 42 and 8 in #42 and 7 and #842 و8 في #42 and 7 and #8 |
| (?<!...)(?<!...) | negative lookbehindlookbehind سالب | (?<!#)\b\d+(?<!#)\b\d+ | 7 in the same string7 في النص نفسه |
One detail to read closely in the table: (?<!#)\b\d+ needs its \b. Without the boundary, the engine could pick up the 2 of #42, because the position before that digit has 4 in front of it, not #, so the negative lookbehind does not object and the lookahead for a digit succeeds. The \b forces the match to begin where a word begins, so the 2 is ruled out and only 7 survives.
تفصيل يستحق القراءة بتمعّن في الجدول: (?<!#)\b\d+ يحتاج إلى الـ \b الخاص به. من دون الحدّ، قد يلتقط المحرّك الرقم 2 من #42، لأن الموضع الذي قبل هذا الرقم يسبقه 4 وليس #، فلا يعترض الـ lookbehind السالب، وينجح البحث عن رقم. الـ \b يجبر المطابقة على أن تبدأ حيث تبدأ كلمة، فيُستبعد الـ 2 ولا يبقى إلا 7.
Recall
Which lookbehinds does Python re accept, and what do JavaScript and the regex module allow instead?ما الـ lookbehinds التي تقبلها Python re، وماذا تسمح به JavaScript ووحدة regex بدلًا من ذلك؟
Part 07 showed you this pattern as a list of six rules; now that you can read regex syntax, walk it character by character. Before GPT-2's BPE merges touch a sentence, one regex cuts it into pieces. On We're 350 dogs! Um, lunch? the pieces are We, 're, ␣350, ␣dogs, !, ␣Um, ,, ␣lunch and ?, nine in all, where ␣ marks a leading space that stays inside the piece. That regex is the pre-tokenizer, and the whole behavior of the tokenizer on numbers, punctuation and spaces is decided by it.
عرض لك الجزء 07 هذا النمط كقائمة من ست قواعد؛ والآن بعد أن أصبحت تقرأ صيغة الـ regex، امشِ عليه محرفًا محرفًا. قبل أن تلمس merges الـ BPE في GPT-2 أي جملة، يقطعها regex واحد إلى قطع. على الجملة We're 350 dogs! Um, lunch? تكون القطع: We، 're، ␣350، ␣dogs، !، ␣Um، ,، ␣lunch و?، أي تسع قطع في المجموع، حيث يرمز ␣ إلى مسافة بادئة تبقى داخل القطعة. هذا الـ regex هو الـ pre-tokenizer، وهو الذي يحدّد سلوك الـ tokenizer كله مع الأرقام وعلامات الترقيم والمسافات.
Recall
From part 07: what does a pre-tokenizer do, and why do BPE merges normally not cross its pieces?من الجزء 07: ماذا يفعل الـ pre-tokenizer، ولماذا لا تعبر عمليات دمج BPE قطعه عادةً؟
The pattern from the GPT-2 repository's encoder.py is 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+. It is a disjunction of six alternatives, and the engine tries them left to right at every position, taking the first that matches. Read it as six rules in priority order.
النمط في الملف encoder.py من مستودع GPT-2 هو 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+. إنه اختيار (disjunction) بين ستة بدائل، والمحرّك يجرّبها من اليسار إلى اليمين عند كل موضع، ويأخذ أول بديل يطابق. اقرأه كست قواعد مرتّبة حسب الأولوية.
| Alternativeالبديل | Meaningالمعنى | Pieces it producedالقطع التي أنتجها |
|---|---|---|
| 's|'t|'re|'ve|'m|'ll|'d's|'t|'re|'ve|'m|'ll|'d | a contraction suffix, tried firstلاحقة اختصار (contraction)، وتُجرَّب أولًا | 're're |
| ?\p{L}+ ?\p{L}+ | an optional space then one or more Unicode lettersمسافة اختيارية ثم حرف Unicode واحد أو أكثر | We, ␣dogs, ␣Um, ␣lunchWe, ␣dogs, ␣Um, ␣lunch |
| ?\p{N}+ ?\p{N}+ | an optional space then one or more Unicode digitsمسافة اختيارية ثم رقم Unicode واحد أو أكثر | ␣350␣350 |
| ?[^\s\p{L}\p{N}]+ ?[^\s\p{L}\p{N}]+ | an optional space then a run that is neither space, letter nor digitمسافة اختيارية ثم سلسلة ليست مسافة ولا حرفًا ولا رقمًا | !, comma, ?!، الفاصلة، ? |
| \s+(?!\S)\s+(?!\S) | whitespace not followed by a non-space, so the last space is left for the next word; also any trailing whitespaceمسافات بيضاء لا يتبعها محرف غير أبيض، فتُترك المسافة الأخيرة للكلمة التالية؛ وكذلك أي مسافات بيضاء في نهاية النص | ␣␣ in Hello␣␣␣world␣␣ في Hello␣␣␣world |
| \s+\s+ | a single whitespace character directly before a non-space that the rule above cannot take: a lone newline or tab before a wordمحرف مسافة بيضاء واحد مباشرة قبل محرف غير أبيض لا تستطيع القاعدة السابقة أخذه: سطر جديد أو tab منفرد قبل كلمة | ⏎ in a⏎b⏎ في a⏎b |
Order is the design. Contractions come first so that We're becomes We plus 're: at position 0 no contraction matches, so the letter rule takes We and stops at the apostrophe; at position 2 the contraction rule fires before the punctuation rule can grab the apostrophe alone. Had the letter rule come first the result would be the same for We, but if punctuation came before contractions you would get ' and then re, and the model would never learn that 're is one unit.
الترتيب هو التصميم. الاختصارات تأتي أولًا حتى تصبح We're القطعة We زائد 're: عند الموضع 0 لا يطابق أي اختصار، فتأخذ قاعدة الحروف We وتتوقف عند الفاصلة العليا (apostrophe)؛ وعند الموضع 2 تنطلق قاعدة الاختصارات قبل أن تتمكن قاعدة الترقيم من التقاط الفاصلة العليا وحدها. لو جاءت قاعدة الحروف أولًا لكانت النتيجة نفسها بالنسبة لـ We، لكن لو جاءت علامات الترقيم قبل الاختصارات لحصلت على ' ثم re، ولما تعلّم النموذج أبدًا أن 're وحدة واحدة.
The space handling is the subtle part. Letters and digits carry an optional leading space, so a word is normally tokenized together with the space before it: ␣dogs is one piece, and the model learns that word-initial pieces look different from word-internal ones. Runs of spaces are handled by \s+(?!\S): whitespace that is not followed by a non-space. On Hello␣␣␣world that alternative takes the first two spaces and stops, because the third space is followed by w, and the third space is then picked up by ?\p{L}+ as part of ␣world. The result is Hello, ␣␣, ␣world. Trailing whitespace at the end of a document also goes to \s+(?!\S), because at the end of the string nothing follows and the negative lookahead succeeds. The final plain \s+ fires only in the one case the rule above cannot handle: a single whitespace character directly before a non-space that no ␣? prefix will take, which means a lone newline or tab before a word. On a⏎b it produces the ⏎ piece.
التعامل مع المسافات هو الجزء الدقيق. الحروف والأرقام تحمل مسافة بادئة اختيارية، لذلك تُقطَّع الكلمة عادةً مع المسافة التي قبلها: ␣dogs قطعة واحدة، ويتعلّم النموذج أن القطع التي تبدأ بها الكلمات تبدو مختلفة عن القطع التي تقع داخل الكلمات. أما سلاسل المسافات فيتعامل معها \s+(?!\S): مسافات بيضاء لا يتبعها محرف غير أبيض. على Hello␣␣␣world يأخذ هذا البديل المسافتين الأوليين ويتوقف، لأن المسافة الثالثة يتبعها w، ثم يلتقط ?\p{L}+ المسافة الثالثة كجزء من ␣world. والنتيجة Hello، ␣␣، ␣world. والمسافات البيضاء في نهاية المستند تذهب أيضًا إلى \s+(?!\S)، لأنه لا شيء يتبعها في نهاية النص فينجح الـ lookahead السالب. أما \s+ العادي الأخير فلا ينطلق إلا في الحالة الوحيدة التي لا تستطيع القاعدة السابقة معالجتها: محرف أبيض واحد مباشرة قبل محرف غير أبيض لا تأخذه أي بادئة ␣?، أي سطر جديد أو tab منفرد قبل كلمة. وعلى a⏎b يُنتج القطعة ⏎.
Why regex and not reلماذا regex وليس re
The slide imports the third-party regex module under the name re. The reason is \p{L} and \p{N}. These are Unicode property classes: every character whose General_Category is Letter, and every character whose category is Number, as defined in Unicode Standard Annex 44. Python's built-in re does not support them; the regex module does, and so does JavaScript with the u flag (regex module documentation, MDN). The payoff is script independence. On مرحبا بالعالم ١٢٣ the same pattern returns مرحبا, ␣بالعالم and ␣١٢٣: Arabic letters are letters and Arabic-Indic digits are digits without any special case in the pattern. A pattern written with [A-Za-z] and [0-9] would still cut at the spaces, because the negated punctuation class excludes whitespace, but all three pieces would come out through the punctuation rule, indistinguishable from runs of symbols.
تستورد الشريحة وحدة regex الخارجية تحت الاسم re. والسبب هو \p{L} و\p{N}. هذه Unicode property classes (فئات خصائص Unicode): كل محرف فئته العامة (General_Category) هي Letter، وكل محرف فئته Number، كما يعرّفها الملحق 44 من معيار Unicode. وحدة re المدمجة في Python لا تدعمها؛ ووحدة regex تدعمها، وكذلك JavaScript مع العلم u (توثيق وحدة regex، وMDN). والمكسب هو الاستقلال عن نظام الكتابة. على مرحبا بالعالم ١٢٣ يُرجع النمط نفسه مرحبا، ␣بالعالم و␣١٢٣: الحروف العربية حروف، والأرقام العربية الهندية أرقام، دون أي حالة خاصة في النمط. أما النمط المكتوب بـ [A-Za-z] و[0-9] فسيظل يقطع عند المسافات، لأن فئة الترقيم المنفية تستثني المسافات البيضاء، لكن القطع الثلاث كلها ستخرج عبر قاعدة الترقيم، فلا يمكن تمييزها عن سلاسل من الرموز.
For the exam, two ways to make a pattern Unicode-aware: use property classes such as \p{L} and \p{N} instead of ASCII ranges, and apply Unicode normalization (NFC or NFKC, from part 05) to the input before matching so that composed and decomposed forms of the same letter cannot split a match.
للامتحان، طريقتان لجعل النمط واعيًا بـ Unicode: استخدم فئات الخصائص مثل \p{L} و\p{N} بدلًا من نطاقات ASCII، وطبّق Unicode normalization (التطبيع، NFC أو NFKC، من الجزء 05) على المدخل قبل المطابقة، حتى لا تتمكن الصيغ المركّبة والمفكّكة للحرف نفسه من تقسيم المطابقة.
Run the GPT-2 pre-tokenizer pattern and read which alternative produced each piece.شغّل نمط المقسِّم المبدئي لـGPT-2 واقرأ أي بديل في النمط أنتج كل قطعة.
/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/guType a pattern to see live results.اكتب نمطًا لترى النتائج مباشرةً.
Patterns run in JavaScript syntax inside a worker with a 600 ms limit. Python differs in three places: backreferences in replacements are \1 not $1, named groups are (?P<name>...), and \p{L} needs the regex module.تعمل الأنماط بصياغة JavaScript داخل worker بحد زمني 600 ms. وتختلف Python في ثلاثة مواضع: المراجع الخلفية في نص الاستبدال تُكتب \1 لا $1، والمجموعات المسماة تُكتب (?P<name>...)، و\p{L} تحتاج إلى وحدة regex.
What the pieces are forما الغرض من القطع
The purpose of the cut is to separate words, numbers, punctuation, contractions and whitespace before BPE sees the text. Then the merges run inside each piece. This is literally how encoder.py is written: it loops over re.findall(self.pat, text) and calls self.bpe(token) on each piece separately (GPT-2 repository). A merge can join d and ogs inside ␣dogs, but no merge can ever join dogs with the ! that follows it, because they were never in the same piece. Byte-level operation, from part 06, applies inside each piece too, which is why the tokenizer is also a byte-level one.
الغرض من القطع هو فصل الكلمات والأرقام وعلامات الترقيم والاختصارات والمسافات قبل أن يرى BPE النص. ثم تجري عمليات الدمج داخل كل قطعة. وهكذا كُتب encoder.py حرفيًا: يمرّ في حلقة على re.findall(self.pat, text) ويستدعي self.bpe(token) على كل قطعة على حدة (مستودع GPT-2). يمكن لعملية دمج أن تضم d وogs داخل ␣dogs، لكن لا يمكن لأي دمج أبدًا أن يضم dogs إلى ! الذي يليها، لأنهما لم يكونا في القطعة نفسها قط. والعمل على مستوى البايت، من الجزء 06، ينطبق داخل كل قطعة أيضًا، ولهذا فهذا الـ tokenizer هو أيضًا tokenizer من نوع byte-level.
The cut lines are a design choice, and later tokenizers move them. tiktoken's r50k pattern for GPT-2 is the same language hardened for speed: '(?:[sdmt]|ll|ve|re)| ?\p{L}++| ?\p{N}++| ?[^\s\p{L}\p{N}]++|\s++$|\s+(?!\S)|\s, with possessive quantifiers ++ that refuse to backtrack and an explicit end-of-string whitespace rule. cl100k_base, used by GPT-4, caps numbers at three digits with \p{N}{1,3}+ and makes contractions case-insensitive (tiktoken repository). Hugging Face's ByteLevel pre-tokenizer applies the same GPT-2 pattern unless you switch its use_regex option off (Hugging Face tokenizers documentation). SuperBPE (introduced in part 07) goes the other way: after a first stage that learns subwords inside pieces, a second stage is allowed to merge across whitespace, and Liu et al. (2025) report up to 33 percent fewer tokens at a 200k vocabulary. Every one of these is a change to the pre-tokenizer, not to the BPE algorithm.
خطوط القطع خيار تصميمي، والـ tokenizers اللاحقة تحرّكها. نمط r50k في tiktoken الخاص بـ GPT-2 هو اللغة نفسها بعد تقويتها من أجل السرعة: '(?:[sdmt]|ll|ve|re)| ?\p{L}++| ?\p{N}++| ?[^\s\p{L}\p{N}]++|\s++$|\s+(?!\S)|\s، مع possessive quantifiers ++ التي ترفض التراجع (backtrack)، وقاعدة صريحة للمسافات البيضاء في نهاية النص. وcl100k_base، المستخدم في GPT-4، يحدّ الأرقام بثلاث خانات عبر \p{N}{1,3}+ ويجعل الاختصارات غير حسّاسة لحالة الأحرف (مستودع tiktoken). والـ pre-tokenizer المسمّى ByteLevel في Hugging Face يطبّق نمط GPT-2 نفسه ما لم توقف خيار use_regex فيه (توثيق Hugging Face tokenizers). أما SuperBPE (الذي قُدِّم في الجزء 07) فيذهب في الاتجاه المعاكس: بعد مرحلة أولى تتعلّم الـ subwords داخل القطع، يُسمح لمرحلة ثانية بالدمج عبر المسافات، ويذكر Liu et al. (2025) انخفاضًا يصل إلى 33% في عدد الـ tokens عند مفردات بحجم 200k. وكل واحد من هذه هو تغيير في الـ pre-tokenizer، لا في خوارزمية BPE.
Recall
Explain each alternative of the GPT-2 pattern on We're 350 dogs!اشرح كل بديل في نمط GPT-2 على We're 350 dogs!
Recall
Name two ways to make a pattern Unicode-aware.سمِّ طريقتين لجعل النمط واعيًا بـ Unicode.
Quick checkاختبار سريع
In the GPT-2 pre-tokenizer, which alternative produces the piece ' 350' with its leading space?في الـ pre-tokenizer الخاص بـ GPT-2، أي بديل يُنتج القطعة ' 350' مع مسافتها البادئة؟
Slide 78 closes the regex block with four engineering habits. Three of them you have already practiced in this part without being told. The email pattern grew from an error analysis of four addresses: start simple, add cases as failures appear. The workbench tasks are unit tests: a fixed list of inputs with expected outputs, rerun after every edit. The GPT-2 pattern was explicit about Unicode: property classes and, from part 05, normalization before matching. The fourth habit is the one that bites in production.
تختم الشريحة 78 كتلة الـ regex بأربع عادات هندسية. ثلاث منها مارستها بالفعل في هذا الجزء دون أن يُقال لك. نمط البريد الإلكتروني نما من تحليل أخطاء على أربعة عناوين: ابدأ ببساطة، وأضف حالات كلما ظهرت أخطاء. ومهام منصة التجربة هي اختبارات وحدات (unit tests): قائمة ثابتة من المدخلات مع مخرجاتها المتوقعة، يُعاد تشغيلها بعد كل تعديل. ونمط GPT-2 كان صريحًا بشأن Unicode: فئات الخصائص، والتطبيع قبل المطابقة من الجزء 05. أما العادة الرابعة فهي التي تلدغك في بيئة الإنتاج (production).
Catastrophic backtrackingالتراجع الكارثي (catastrophic backtracking)
Consider (a+)+b against aaaaaaaa!. The pattern says: one or more groups, each of one or more a's, followed by b. There is no b, so the answer is no. But a backtracking engine does not know that until it has tried every way of splitting the eight a's between the inner plus and the outer plus: all eight in one group, seven then one, one then seven, two then six, and so on. The number of ways to partition n a's into ordered runs is 2^(n-1), and each of them ends at the same exclamation mark. Add one a and the work doubles. This is catastrophic backtracking.
خذ (a+)+b على النص aaaaaaaa!. يقول النمط: مجموعة واحدة أو أكثر، كل منها حرف a واحد أو أكثر، يتبعها b. لا يوجد b، لذلك فالجواب لا. لكن المحرّك القائم على التراجع (backtracking engine) لا يعرف ذلك حتى يجرّب كل طريقة لتقسيم حروف a الثمانية بين الـ plus الداخلي والـ plus الخارجي: الثمانية كلها في مجموعة واحدة، سبعة ثم واحد، واحد ثم سبعة، اثنان ثم ستة، وهكذا. عدد طرق تقسيم n حرفًا من a إلى سلاسل مرتّبة هو 2^(n-1)، وكل واحدة منها تنتهي عند علامة التعجب نفسها. أضف حرف a واحدًا فيتضاعف العمل. هذا هو catastrophic backtracking.
Worked exampleمثال محلول
Measuring the explosionقياس الانفجار
Set up two patternsجهّز نمطين
(a+)+b and a+b, both run against n a's followed by an exclamation mark, in Python re and in JavaScript.(a+)+b وa+b، يُشغَّل كلاهما على n حرفًا من a تتبعها علامة تعجب، في Python re وفي JavaScript.Time the nested patternقِس زمن النمط المتداخل
Python time roughly quadruples every two extra characters (see the table below), which is doubling per character. JavaScript follows the same curve, roughly seven to fourteen times faster.زمن Python يتضاعف أربع مرات تقريبًا مع كل حرفين إضافيين (انظر الجدول أدناه)، أي أنه يتضاعف مرتين مع كل حرف. وJavaScript يتبع المنحنى نفسه، لكنه أسرع بنحو سبع إلى أربع عشرة مرة.Time the flat patternقِس زمن النمط المسطّح
a+b on the same strings stays under 60 microseconds in Python at every n.a+b has only one way to split any run of a's, so the work is at most polynomial (each start position backs off once), never exponential.a+b على النصوص نفسها يبقى تحت 60 ميكروثانية في Python عند كل قيمة لـ n. للنمط a+b طريقة واحدة فقط لتقسيم أي سلسلة من a، لذلك فالعمل على الأكثر متعدد الحدود (polynomial)، إذ يتراجع كل موضع بداية مرة واحدة، وليس أُسّيًا أبدًا.Same strings, same answer, more than four orders of magnitude apartالنصوص نفسها، والجواب نفسه، وفرق يزيد على أربع رُتَب عشرية
Run time depends on the structure of the pattern and the shape of the input, not on the length of the pattern.زمن التشغيل يعتمد على بنية النمط وشكل المدخل، لا على طول النمط.
| nn | Python rePython re | JavaScriptJavaScript |
|---|---|---|
| 2020 | 43 ms43 ms | 8.3 ms8.3 ms |
| 2222 | 175 ms175 ms | 31 ms31 ms |
| 2424 | 711 ms711 ms | 126 ms126 ms |
| 2626 | 2900 ms2900 ms | 506 ms506 ms |
Russ Cox (2007) documents the classic case: a pattern of a? repeated n times followed by a repeated n times, matched against a string of n a's. At n = 29 Perl needs over sixty seconds, while a Thompson NFA, which simulates all states at once, takes about twenty microseconds. OWASP lists (a+)+ among its evil patterns because a single crafted input can pin a server's CPU, an attack it calls ReDoS. Both sources agree on the cause: an engine that explores alternatives one at a time, on a pattern with overlapping ways to match the same text.
يوثّق Russ Cox (2007) الحالة الكلاسيكية: نمط من a? مكرّرًا n مرة متبوعًا بـ a مكرّرًا n مرة، يُطابَق مع نص من n حرفًا من a. عند n = 29 يحتاج Perl إلى أكثر من ستين ثانية، بينما يستغرق Thompson NFA، الذي يحاكي كل الحالات في آن واحد، نحو عشرين ميكروثانية. وتُدرج OWASP النمط (a+)+ ضمن أنماطها الشريرة (evil patterns)، لأن مدخلًا واحدًا مصمّمًا بعناية يمكنه أن يُشغل معالج الخادم بالكامل، وهو هجوم تسمّيه ReDoS. ويتفق المصدران على السبب: محرّك يستكشف البدائل واحدًا تلو الآخر، على نمط له طرق متداخلة لمطابقة النص نفسه.
Watch the engine time as the input grows. Then change the pattern to ^a+b and try again.راقب زمن المحرك مع ازدياد طول المدخل. ثم غيّر النمط إلى ^a+b وجرّب مرة أخرى.
/^(a+)+b/gType a pattern to see live results.اكتب نمطًا لترى النتائج مباشرةً.
Patterns run in JavaScript syntax inside a worker with a 600 ms limit. Python differs in three places: backreferences in replacements are \1 not $1, named groups are (?P<name>...), and \p{L} needs the regex module.تعمل الأنماط بصياغة JavaScript داخل worker بحد زمني 600 ms. وتختلف Python في ثلاثة مواضع: المراجع الخلفية في نص الاستبدال تُكتب \1 لا $1، والمجموعات المسماة تُكتب (?P<name>...)، و\p{L} تحتاج إلى وحدة regex.
Three fixes, in order of preference. Rewrite the pattern so that quantifiers do not nest over the same characters: a+b matches exactly the same strings as (a+)+b. Lazy quantifiers do not prevent the explosion either: (a+?)+b backtracks just like (a+)+b, because laziness only changes the order in which splits are tried, not how many exist. Use possessive quantifiers or atomic groups where the engine offers them: tiktoken's \p{L}++ is precisely this, a plus that refuses to give characters back. Or run a linear-time engine such as RE2, Go's regexp or Rust's regex crate, which reject backreferences and lookaround in exchange for a guarantee that time is linear in the input.
ثلاثة إصلاحات، مرتّبة حسب الأفضلية. أعد كتابة النمط بحيث لا تتداخل الـ quantifiers فوق المحارف نفسها: a+b يطابق بالضبط النصوص نفسها التي يطابقها (a+)+b. والـ quantifiers الكسولة (lazy) لا تمنع الانفجار هي الأخرى: (a+?)+b يتراجع تمامًا مثل (a+)+b، لأن الكسل يغيّر فقط ترتيب تجربة التقسيمات، لا عددها. استخدم الـ possessive quantifiers أو المجموعات الذرّية (atomic groups) حيث يوفّرها المحرّك: \p{L}++ في tiktoken هو هذا تحديدًا، plus يرفض إعادة المحارف. أو شغّل محرّكًا خطّي الزمن مثل RE2، أو regexp في Go، أو regex crate في Rust، وهي ترفض الـ backreferences والـ lookaround مقابل ضمان أن يكون الزمن خطّيًا في طول المدخل.
Recall
Give an example of catastrophic backtracking and a fix.أعطِ مثالًا على catastrophic backtracking وإصلاحًا له.
Quick checkاختبار سريع
Why does (a+)+b take seconds on aaaaaaaaaaaaaaaaaaaaaaaaaa! while a+b takes microseconds?لماذا يستغرق (a+)+b ثواني على aaaaaaaaaaaaaaaaaaaaaaaaaa! بينما يستغرق a+b ميكروثوانٍ؟
Recapالخلاصة
If you remember nothing elseإن لم تتذكر شيئاً آخر فتذكّر هذا
- The metacharacters . ^ $ * + ? ( ) [ ] { } | \ need a backslash to match literally; \n and \t go the other way and give a plain letter a special meaning.المحارف الخاصة . ^ $ * + ? ( ) [ ] { } | \ تحتاج إلى backslash لتُطابَق حرفيًا؛ أما \n و\t فتعملان في الاتجاه المعاكس وتعطيان حرفًا عاديًا معنى خاصًا.
- Precedence: parentheses, then counters, then sequences and anchors, then |. (cat|dog)s matches cats and dogs; cat|dogs matches cat and dogs.الأولوية: الأقواس، ثم العدّادات (quantifiers)، ثم التتابعات والمراسي (anchors)، ثم |. النمط (cat|dog)s يطابق cats وdogs؛ والنمط cat|dogs يطابق cat وdogs.
- Capture groups only record. \1 in the pattern or $1 (Python \1) in the replacement reuses them; (?:...) groups without recording.مجموعات الالتقاط تسجّل فقط. \1 داخل النمط، أو $1 (و\1 في Python) داخل الاستبدال، يعيد استخدامها؛ و(?:...) يجمّع دون تسجيل.
- (\d{4})-(\d{2})-(\d{2}) with \3/\2/\1 turns 2026-01-25 into 25/01/2026; slide 70's $2$3$1 gives 01252026 because the separators were never captured.النمط (\d{4})-(\d{2})-(\d{2}) مع \3/\2/\1 يحوّل 2026-01-25 إلى 25/01/2026؛ أما $2$3$1 في الشريحة 70 فيعطي 01252026 لأن الفواصل لم تُلتقط أصلًا.
- Lookahead (?=...) and (?!...) are zero-width; stacking them expresses overlapping rules such as a password check.الـ lookahead بصيغتيه (?=...) و(?!...) عديم العرض (zero-width)؛ وتكديس أكثر من واحد يعبّر عن قواعد متداخلة مثل فحص كلمة المرور.
- \d is Unicode Nd in Python re but ASCII only in JavaScript; \p{L} and \p{N} need the regex module or the u flag.الرمز \d في re الخاصة بـ Python يعني أرقام Unicode من الفئة Nd، لكنه ASCII فقط في JavaScript؛ و\p{L} و\p{N} تحتاجان إلى وحدة regex أو العلم u.
- The GPT-2 pre-tokenizer tries contractions, letters, numbers, punctuation and whitespace in that order; BPE merges run inside each piece.الـ pre-tokenizer في GPT-2 يجرّب الاختصارات (contractions)، ثم الحروف، ثم الأرقام، ثم علامات الترقيم، ثم المسافات البيضاء بهذا الترتيب؛ وعمليات دمج BPE تجري داخل كل قطعة.
- \s+(?!\S) eats a run of spaces but leaves the last one attached to the next word.النمط \s+(?!\S) يلتهم سلسلة من المسافات لكنه يترك المسافة الأخيرة ملتصقة بالكلمة التالية.
- Nested quantifiers such as (a+)+b backtrack exponentially: seconds at 26 characters in Python, microseconds for a+b.الـ quantifiers المتداخلة مثل (a+)+b تتراجع (backtrack) تراجعًا أُسّيًا: ثوانٍ عند 26 حرفًا في Python، مقابل ميكروثوانٍ للنمط a+b.
Sourcesالمصادر
- Speech and Language Processing, chapter 2: Regular Expressions, Tokenization, Edit DistanceBookJurafsky and Martin, draft of August 19, 2026Sections 2.6.4 to 2.6.9, Figures 2.14 and 2.15; precedence ladder, escaping table, substitutions, lookahead, BPE pre-tokenizationالأقسام 2.6.4 إلى 2.6.9، والشكلان 2.14 و2.15؛ سُلّم الأولوية، وجدول التهريب، والاستبدالات، والـ lookahead، والـ pre-tokenization في BPE(opens in a new tab)(يفتح في تبويب جديد)
- re: Regular expression operationsDocsPython documentationUnicode \d, fixed-width lookbehind, \g<0>, scoped flags, MULTILINE\d في Unicode، والـ lookbehind ثابت العرض، و\g<0>، والأعلام محدودة النطاق، وMULTILINE(opens in a new tab)(يفتح في تبويب جديد)
- regex: alternative regular expression moduleDocsPyPI\p{...} property classes and variable-length lookbehindفئات الخصائص \p{...} والـ lookbehind متغيّر الطول(opens in a new tab)(يفتح في تبويب جديد)
- Unicode character class escape: \p{...}, \P{...}DocsMDN Web DocsRequires the u or v flag; \d is ASCII only in JavaScriptيتطلّب العلم u أو v؛ و\d في JavaScript يعني ASCII فقط(opens in a new tab)(يفتح في تبويب جديد)
- Lookbehind assertionDocsMDN Web DocsVariable-length lookbehind in JavaScript since ES2018الـ lookbehind متغيّر الطول في JavaScript منذ ES2018(opens in a new tab)(يفتح في تبويب جديد)
- Unicode Standard Annex #44: Unicode Character DatabaseDocsUnicode ConsortiumGeneral_Category values L, N and Ndقيم General_Category وهي L وN وNd(opens in a new tab)(يفتح في تبويب جديد)
- encoder.pyDocsOpenAI, gpt-2 repositoryThe pre-tokenizer pattern and the per-piece bpe() loopنمط الـ pre-tokenizer وحلقة bpe() على كل قطعة(opens in a new tab)(يفتح في تبويب جديد)
- Language Models are Unsupervised Multitask LearnersPaperRadford et al., OpenAI, 2019Section 2.2: no merges across character categories, exception for spacesالقسم 2.2: لا دمج عبر فئات المحارف، مع استثناء للمسافات(opens in a new tab)(يفتح في تبويب جديد)
- openai_public.pyDocsOpenAI, tiktoken repositoryr50k and cl100k_base pre-tokenizer patternsأنماط الـ pre-tokenizer في r50k وcl100k_base(opens in a new tab)(يفتح في تبويب جديد)
- Pre-tokenizersDocsHugging Face tokenizers documentationByteLevel use_regex option for the GPT-2 patternخيار use_regex في ByteLevel لنمط GPT-2(opens in a new tab)(يفتح في تبويب جديد)
- SuperBPE: Space Travel for Language ModelsPaperLiu et al., 2025Pretokenization curriculum, superwords across whitespace, up to 33 percent fewer tokensمنهج تدريجي للـ pretokenization، وكلمات فائقة (superwords) عبر المسافات، وانخفاض يصل إلى 33 في المئة في عدد الـ tokens(opens in a new tab)(يفتح في تبويب جديد)
- Regular Expression Matching Can Be Simple And FastArticleRuss Cox, 2007Backtracking versus Thompson NFA; sixty seconds versus twenty microsecondsالتراجع (backtracking) مقابل Thompson NFA؛ ستون ثانية مقابل عشرين ميكروثانية(opens in a new tab)(يفتح في تبويب جديد)
- Regular expression Denial of Service (ReDoS)DocsOWASPEvil patterns including (a+)+الأنماط الشريرة (evil patterns) ومنها (a+)+(opens in a new tab)(يفتح في تبويب جديد)
- regex101: build, test and debug regexDocsregex101Practice site named on slide 72; substitution tab, Python and JavaScript flavorsموقع التدريب المذكور في الشريحة 72؛ تبويب الاستبدال، ونكهتا Python وJavaScript(opens in a new tab)(يفتح في تبويب جديد)
Part 10: Minimum edit distance: alignments and searchمسافة التحرير الدنيا: المحاذاة والبحث
Measuring how far apart two strings are with insertions, deletions and substitutions, seeing the answer as an alignment, and recognizing the problem as a shortest path that dynamic programming solves.قياس بُعد سلسلتين نصيتين عن بعضهما بالإدراج والحذف والاستبدال، والنظر إلى الإجابة كمحاذاة (alignment)، والتعرف على المشكلة كأقصر مسار تحله البرمجة الديناميكية.
4 concepts4 مفاهيم, ، slides 79-86الشرائح 79-86
Why this part mattersلماذا يهمّ هذا الجزء
Edit distance is the first dynamic programming algorithm in this course, and its shape returns in the Viterbi decoder and in CKY parsing. It is also the metric under word error rate, so any speech or Arabic ASR work in the research project will report it. It is a reliable exam item: define it, write the recurrence, fill a table, recover an alignment.
This part builds the idea in four moves. First the definition and why anyone needs it. Then the alignment view, which turns a distance into columns you can read and add up, and which exposes a trap: the slides define substitution at cost 1, but the worked table in part 11 (taken from SLP3) charges 2, and the same pair of words comes out as 5 or 8 depending on that choice. Then the search view, which shows why brute force fails and what dynamic programming remembers. Finally the recurrence itself and the cost function it plugs in.
مسافة التحرير (edit distance) هي أول خوارزمية برمجة ديناميكية (dynamic programming) في هذا المقرر، وشكلها يتكرر لاحقًا في مفكّك Viterbi وفي تحليل CKY. وهي أيضًا المقياس الذي يقوم عليه معدل خطأ الكلمات (word error rate)، لذلك فأي عمل على الكلام أو على التعرّف الآلي على الكلام العربي (Arabic ASR) في مشروع البحث سيذكره. وهي سؤال امتحان مضمون: عرّفها، اكتب العلاقة التكرارية، املأ جدولًا، استرجع محاذاة.
يبني هذا الجزء الفكرة في أربع خطوات. أولًا التعريف ولماذا يحتاجه أحد أصلًا. ثم منظور المحاذاة، الذي يحوّل المسافة إلى أعمدة يمكنك قراءتها وجمعها، ويكشف فخًّا: الشرائح تعرّف الاستبدال بتكلفة 1، لكن الجدول المحلول في الجزء 11 (المأخوذ من SLP3) يحتسبه بتكلفة 2، فيخرج الزوج نفسه من الكلمات بقيمة 5 أو 8 بحسب هذا الاختيار. ثم منظور البحث، الذي يبيّن لماذا تفشل القوة الغاشمة (brute force) وما الذي تتذكره البرمجة الديناميكية. وأخيرًا العلاقة التكرارية نفسها ودالة التكلفة التي تُوضع فيها.
By the end you canفي نهاية هذا الجزء ستستطيع
- Define minimum edit distance, name the three operations, and say what each costs under unit costs.تعرّف مسافة التحرير الدنيا (minimum edit distance)، وتسمّي العمليات الثلاث، وتذكر تكلفة كل منها في التكاليف الوحدوية (unit costs).
- Read and cost an alignment under unit costs and under substitution cost 2, and declare which convention you use.تقرأ المحاذاة (alignment) وتحسب تكلفتها في التكاليف الوحدوية وعندما تكون تكلفة الاستبدال 2، وتصرّح بالاصطلاح الذي تستخدمه.
- Explain why naive search over edit sequences is exponential and why the grid of prefix pairs is O(mn).تشرح لماذا يكون البحث الساذج في متتاليات التحرير أُسّيًا، ولماذا تكون شبكة أزواج البادئات (prefix pairs) من رتبة O(mn).
- Write the initialization and the recurrence for D[i,j] and justify D[i,0] = i.تكتب التهيئة (initialization) والعلاقة التكرارية (recurrence) لـ D[i,j]، وتبرّر لماذا D[i,0] = i.
- Compute a word error rate from an alignment and describe weighted substitution and transposition extensions.تحسب معدل خطأ الكلمات (WER) من محاذاة، وتصف امتدادات الاستبدال الموزون والتبديل (transposition).
A speech recognizer hears "turn on the kitchen light" and writes "turn on a kitchen light please". A spell checker sees "acress". An OCR engine reads the two letters "rn" as an "m". In each case there is a string we have and a string we want, and the question is the same: how much editing separates them?
يسمع نظام التعرّف على الكلام «turn on the kitchen light» فيكتب «turn on a kitchen light please». ويرى مدقق الإملاء «acress». ويقرأ محرك OCR الحرفين «rn» على أنهما «m». في كل حالة لدينا سلسلة نملكها وسلسلة نريدها، والسؤال واحد: كم من التحرير يفصل بينهما؟
The answer is the Minimum edit distance: the minimum total cost of the editing operations that turn a source string into a target string. Three operations are allowed. An insertion adds one symbol, a deletion removes one, and a substitution replaces one with another. Each operation has a cost, most often 1, and the distance is the cheapest way of getting from source to target, not the first way you happen to find. With every operation at cost 1 (and a substitution of a letter by itself at cost 0) this quantity is the Levenshtein distance, after the 1966 paper that introduced it for error correcting codes. Nothing in the definition says the symbols must be letters. Take words as the symbols and the same definition measures how far a recognized sentence is from its transcript, which is exactly how speech recognition uses it.
الإجابة هي minimum edit distance (مسافة التحرير الدنيا): أقل تكلفة إجمالية لعمليات التحرير التي تحوّل سلسلة مصدر (source) إلى سلسلة هدف (target). يُسمح بثلاث عمليات. الإدراج (insertion) يضيف رمزًا واحدًا، والحذف (deletion) يزيل رمزًا واحدًا، والاستبدال (substitution) يضع رمزًا مكان آخر. لكل عملية تكلفة، غالبًا 1، والمسافة هي أرخص طريقة للوصول من المصدر إلى الهدف، لا أول طريقة تصادفها. وعندما تكون تكلفة كل عملية 1 (وتكلفة استبدال الحرف بنفسه 0) تُسمّى هذه الكمية Levenshtein distance، نسبةً إلى بحث عام 1966 الذي قدّمها لرموز تصحيح الأخطاء. ولا يوجد في التعريف ما يشترط أن تكون الرموز حروفًا. اجعل الكلمات هي الرموز، فيقيس التعريف نفسه مدى بُعد جملة متعرَّف عليها عن نصها المرجعي، وهذا بالضبط ما يفعله التعرّف على الكلام.
Where edit distance is used, and the mechanism in each caseأين تُستخدم مسافة التحرير، وآلية عملها في كل حالة
- Spelling correctionتصحيح الإملاء
- Generate candidates that differ from the typo by a single insertion, deletion, substitution or reversal, then rank them: for acress, the candidates are actress, cress, caress, access, across and acres.ولّد المرشحين الذين يختلفون عن الخطأ المطبعي بإدراج واحد أو حذف واحد أو استبدال واحد أو عكس ترتيب حرفين، ثم رتّبهم: لكلمة acress المرشحون هم actress وcress وcaress وaccess وacross وacres.
- OCR post-processingالمعالجة اللاحقة لمخرجات OCR
- Map a recognized string with a misread rn or m to the nearest entry of a lexicon.اربط السلسلة المتعرَّف عليها، التي قُرئ فيها rn أو m خطأً، بأقرب مدخل في المعجم (lexicon).
- Speech recognition (WER)التعرّف على الكلام (WER)
- Align the recognized word sequence to the reference transcript and count the word-level insertions, substitutions and deletions.حاذِ متتالية الكلمات المتعرَّف عليها مع النص المرجعي، واحسب الإدراجات والاستبدالات والحذوفات على مستوى الكلمات.
- Approximate matchingالمطابقة التقريبية
- Search a text for a pattern while allowing a bounded number of edits, for example in DNA or in fuzzy search boxes.ابحث في نص عن نمط مع السماح بعدد محدود من التعديلات، كما في DNA أو في مربعات البحث التقريبي (fuzzy search).
- Alignmentالمحاذاة
- Make explicit which characters correspond, which is the view the next concept builds on.اجعل تقابل الحروف صريحًا، وهو المنظور الذي يبني عليه المفهوم التالي.
The spelling application is older than most of NLP. Damerau found in 1964 that a single wrong, missing, extra or transposed letter accounts for about 80 percent of spelling errors, which is why candidate generation by a single transformation works so well: Kernighan, Church and Gale's spelling corrector lists exactly the six single-transformation candidates for "acress" shown in the table, one of them (caress) reached by reversing the first two letters rather than by a Levenshtein substitution, and then picks among them with a probabilistic model. Approximate matching generalizes the search direction: instead of comparing two whole strings, you look for places in a long text that a pattern would match after at most k edits.
تطبيق الإملاء أقدم من معظم NLP. وجد Damerau عام 1964 أن حرفًا واحدًا خاطئًا أو ناقصًا أو زائدًا أو مبدَّل الموضع يفسّر نحو 80 بالمئة من أخطاء الإملاء، ولهذا ينجح توليد المرشحين بتحويل واحد نجاحًا كبيرًا: مصحح الإملاء الذي بناه Kernighan وChurch وGale يسرد بالضبط المرشحين الستة ذوي التحويل الواحد لكلمة «acress» المبيّنين في الجدول، وأحدهم (caress) يُوصل إليه بعكس ترتيب الحرفين الأولين لا باستبدال من نوع Levenshtein، ثم يختار بينهم بنموذج احتمالي. أما المطابقة التقريبية (approximate matching) فتعمّم اتجاه البحث: بدلًا من مقارنة سلسلتين كاملتين، تبحث عن مواضع في نص طويل يطابقها النمط بعد k تعديلات على الأكثر.
Word error rate, computedحساب معدل خطأ الكلمات
The Word error rate (WER) is edit distance applied to words. Align the recognizer's hypothesis to the human reference at the word level, count the insertions, substitutions and deletions on that alignment, and divide by the number of words in the reference. The denominator is the reference, never the hypothesis, and because insertions are counted the rate can exceed 100 percent.
Word error rate (معدل خطأ الكلمات) هو مسافة التحرير مطبّقة على الكلمات. حاذِ فرضية نظام التعرّف (hypothesis) مع المرجع البشري (reference) على مستوى الكلمات، واحسب الإدراجات والاستبدالات والحذوفات في تلك alignment، ثم اقسم على عدد كلمات المرجع. المقام هو المرجع وليس الفرضية أبدًا، ولأن الإدراجات تُحسب فقد يتجاوز المعدل 100 بالمئة.
Worked exampleمثال محلول
WER for the kitchen lightحساب WER لجملة ضوء المطبخ
Reference and hypothesisالمرجع والفرضية
Reference: "turn on the kitchen light" (5 words). Hypothesis: "turn on a kitchen light please" (6 words).المرجع: «turn on the kitchen light» (5 كلمات). الفرضية: «turn on a kitchen light please» (6 كلمات).Align at the word levelالمحاذاة على مستوى الكلمات
turn and on match, the becomes a (one substitution), kitchen and light match, please has nothing above it (one insertion).turn وon متطابقتان، وthe تصبح a (استبدال واحد)، وkitchen وlight متطابقتان، وplease لا يقابلها شيء فوقها (إدراج واحد).Count and divideالعدّ والقسمة
I + S + D = 1 + 1 + 0 = 2, over 5 reference words.I + S + D = 1 + 1 + 0 = 2، مقسومًا على 5 كلمات في المرجع.Resultالنتيجة
WER = 2 / 5 = 40 percent. A 2-word reference recognized as 5 words with three insertions would give 3 / 2 = 150 percent, which is legal and common on noisy audio.WER = 2 / 5 = 40 percent. ومرجع من كلمتين (2) يُتعرَّف عليه على أنه 5 كلمات بثلاثة إدراجات يعطي 3 / 2 = 150 percent، وهذا مقبول وشائع مع الصوت المشوَّش.
SLP3's own CallHome example has 6 substitutions, 3 insertions and 1 deletion over 13 reference words, a WER of 76.9 percent. The standard scorer is NIST's sclite in the SCTK toolkit, which does the alignment and the arithmetic for you but reports exactly these counts.
مثال CallHome في SLP3 نفسه فيه 6 استبدالات و3 إدراجات وحذف واحد (1) على 13 كلمة مرجعية، أي WER قدره 76.9 بالمئة. والمقيّم القياسي هو أداة sclite من NIST ضمن حزمة SCTK، التي تنفّذ المحاذاة والحساب نيابةً عنك لكنها تُبلغ عن هذه الأعداد نفسها بالضبط.
Recall
Define minimum edit distance and name the three operations. What is it called when every operation costs one?عرّف مسافة التحرير الدنيا وسمِّ العمليات الثلاث. ماذا تُسمّى عندما تكون تكلفة كل عملية واحدًا؟
Recall
How does WER use edit distance, and can it exceed 100 percent?كيف يستخدم WER مسافة التحرير، وهل يمكن أن يتجاوز 100 بالمئة؟
Quick checkاختبار سريع
A 10-word reference is recognized with 2 substitutions, 1 deletion and 2 insertions. What is the WER?مرجع من 10 كلمات تعرّف عليه النظام مع استبدالين وحذف واحد وإدراجين. ما قيمة WER؟
Lay the two words on top of each other as on slide 82, with a star for a gap, and read the ten columns from left to right: I over a star, N over E, T over X, E over E, a star over C, N over U, and then T I O N over T I O N. The row underneath, d s s _ i s, names the columns that cost something: delete I, substitute N by E, substitute T by X, insert C, substitute N by U. Five operations, and five is the minimum edit distance.
ضع الكلمتين إحداهما فوق الأخرى كما في الشريحة 82، مع نجمة للفجوة (gap)، واقرأ الأعمدة العشرة من اليسار إلى اليمين: I فوق نجمة، N فوق E، T فوق X، E فوق E، نجمة فوق C، N فوق U، ثم T I O N فوق T I O N. والصف الذي تحتها، d s s _ i s، يسمّي الأعمدة التي لها تكلفة: احذف I، استبدل N بـE، استبدل T بـX، أدرج C، استبدل N بـU. خمس عمليات، والخمسة هي مسافة التحرير الدنيا.
What you just read is an Alignment: a correspondence between the two strings that says, for every symbol, what it lines up with. A column with the same letter top and bottom is a match and costs nothing. A column with two different letters is a substitution. A letter over a gap is a deletion (the source letter is consumed without producing anything), and a gap over a letter is an insertion. The cost of an alignment is the sum of its column costs, and the minimum edit distance is simply the cost of the cheapest alignment. The practical half of the story is that the dynamic programming table does not just give the number, it stores a Backpointer in each cell, and following those pointers back from the last cell recovers one cheapest alignment. Part 11 does that recovery by hand.
ما قرأته للتو هو alignment (محاذاة): تقابل بين السلسلتين يحدد لكل رمز ما يقابله. العمود الذي فيه الحرف نفسه أعلى وأسفل هو تطابق (match) ولا يكلّف شيئًا. والعمود الذي فيه حرفان مختلفان هو استبدال. والحرف فوق فجوة هو حذف (يُستهلك حرف المصدر دون أن ينتج شيئًا)، والفجوة فوق حرف هي إدراج. تكلفة المحاذاة هي مجموع تكاليف أعمدتها، ومسافة التحرير الدنيا ببساطة هي تكلفة أرخص محاذاة. والنصف العملي من القصة أن جدول dynamic programming لا يعطي الرقم فقط، بل يخزّن backpointer (مؤشرًا خلفيًا) في كل خلية، وتتبّع هذه المؤشرات رجوعًا من الخلية الأخيرة يسترجع إحدى المحاذاات الأرخص. الجزء 11 يقوم بهذا الاسترجاع يدويًا.
Two cost conventions, and the same words come out as 5 or 8اصطلاحان للتكلفة، والكلمات نفسها تخرج بـ5 أو 8
Here is the trap this lecture sets, and the reason this section exists. Slides 85 and 86 define the Substitution cost as 1 for two different letters. The filled table you will meet in part 11 (slides 89 and 91) is copied from SLP3, and SLP3 fills it with a substitution cost of 2. Levenshtein proposed both: in his second version insertions and deletions cost 1 and substitutions are simply not allowed, and since any substitution can be written as a deletion followed by an insertion, that is the same as allowing it at cost 2. Both are legitimate cost functions. They give different numbers, and they can disagree about which alignment is best.
هذا هو الفخ الذي تنصبه هذه المحاضرة، وهو سبب وجود هذا القسم. الشريحتان 85 و86 تعرّفان substitution cost (تكلفة الاستبدال) بأنها 1 لحرفين مختلفين. أما الجدول المملوء الذي ستقابله في الجزء 11 (الشريحتان 89 و91) فمنسوخ من SLP3، وSLP3 يملؤه بتكلفة استبدال 2. اقترح Levenshtein الاثنين معًا: في نسخته الثانية يكلّف الإدراج والحذف 1 ولا يُسمح بالاستبدال إطلاقًا، وبما أن أي استبدال يمكن كتابته كحذف يليه إدراج، فهذا يكافئ السماح به بتكلفة 2. كلتاهما دالة تكلفة مشروعة. تعطيان أرقامًا مختلفة، وقد تختلفان أيضًا حول أي محاذاة هي الأفضل.
| Operationالعملية | Unit costs (slides 85, 86)التكاليف الوحدوية (الشريحتان 85 و86) | SLP3 table costs (substitution 2)تكاليف جدول SLP3 (الاستبدال 2) |
|---|---|---|
| Match (same letter)تطابق (الحرف نفسه) | 00 | 00 |
| Insertionإدراج | 11 | 11 |
| Deletionحذف | 11 | 11 |
| Substitution (different letters)استبدال (حرفان مختلفان) | 11 | 22 |
| Columnالعمود | Operationالعملية | Unit costsالتكاليف الوحدوية | Substitution 2الاستبدال 2 |
|---|---|---|---|
| I over *I فوق * | deleteحذف | 11 | 11 |
| N over EN فوق E | substituteاستبدال | 11 | 22 |
| T over XT فوق X | substituteاستبدال | 11 | 22 |
| E over EE فوق E | matchتطابق | 00 | 00 |
| * over C* فوق C | insertإدراج | 11 | 11 |
| N over UN فوق U | substituteاستبدال | 11 | 22 |
| T I O N over T I O NT I O N فوق T I O N | four matchesأربعة تطابقات | 00 | 00 |
| Totalالمجموع | 55 | 88 |
Read the totals again: 1 + 1 + 1 + 0 + 1 + 1 = 5 under unit costs and 1 + 2 + 2 + 0 + 1 + 2 = 8 with substitutions at 2. Both describe the same alignment. If an exam asks for the distance from intention to execution and you answer 8 without saying why, the grader who has the slide 85 recurrence in mind will mark it wrong, and the reverse is also true.
اقرأ المجموعين مرة أخرى: 1 + 1 + 1 + 0 + 1 + 1 = 5 في التكاليف الوحدوية و1 + 2 + 2 + 0 + 1 + 2 = 8 عندما يكلّف الاستبدال 2. كلاهما يصف المحاذاة نفسها. إذا سأل الامتحان عن المسافة من intention إلى execution وأجبت 8 دون أن تقول لماذا، فالمصحح الذي يضع في ذهنه علاقة الشريحة 85 سيعتبرها خطأ، والعكس صحيح أيضًا.
Try it: label the columns yourselfجرّب بنفسك: سمِّ الأعمدة
The editor below shows three alignments of intention and execution, with the four trailing matches already labeled. Label every remaining column, watch the two totals update, and then compare the presets. The third one pairs the letters position by position with no gaps at all: five substitutions. Under unit costs it ties the slide alignment at 5. With substitutions at 2 it costs 10 and loses to 8. The cost function does not only change the total; it changes which alignments are optimal.
يعرض المحرر أدناه ثلاث محاذاات لـintention وexecution، مع تسمية التطابقات الأربعة الأخيرة مسبقًا. سمِّ كل عمود متبقٍّ، وراقب المجموعين وهما يتحدّثان، ثم قارن المحاذاات الجاهزة. الثالثة تقرن الحروف موضعًا بموضع دون أي فجوات: خمسة استبدالات. في التكاليف الوحدوية تتعادل مع محاذاة الشريحة عند 5. وعندما يكلّف الاستبدال 2 تكلّف 10 وتخسر أمام 8. دالة التكلفة لا تغيّر المجموع فقط؛ بل تغيّر أيضًا أي المحاذاات هي المثلى.
Read each column of the alignment (source letter on top, target letter below, * for a gap) and label it match, substitution, insertion or deletion. The last 4 columns (T I O N) come pre-labeled as matches. The totals update from your labels under both cost conventions. Press check to grade the columns.اقرأ كل عمود في المحاذاة (حرف المصدر في الأعلى، وحرف الهدف في الأسفل، و* للفراغ) وسمِّه: تطابق (match) أو استبدال (sub) أو إدراج (ins) أو حذف (del). الأعمدة الـ4 الأخيرة (T I O N) مسمّاة مسبقًا على أنها تطابقات. تتحدّث المجاميع من تسمياتك وفق اصطلاحي الكلفة كليهما. اضغط تحقّق لتقييم الأعمدة.
| Alignmentالمحاذاة | Operationsالعمليات | Unit costsالتكاليف الوحدوية | Substitution 2الاستبدال 2 |
|---|---|---|---|
| Slide 82: d s s _ i sالشريحة 82: d s s _ i s | 1 del, 3 sub, 1 insحذف واحد، 3 استبدالات، إدراج واحد | 55 | 88 |
| SLP3 figure 2.19: delete i, n to e, t to x, insert u, n to cالشكل 2.19 في SLP3: احذف i، n إلى e، t إلى x، أدرج u، n إلى c | 1 del, 3 sub, 1 insحذف واحد، 3 استبدالات، إدراج واحد | 55 | 88 |
| Position by position, no gapsموضعًا بموضع، دون فجوات | 5 sub5 استبدالات | 55 | 1010 |
Worked exampleمثال محلول
A second pair: kitten to sittingزوج ثانٍ: kitten إلى sitting
Write the alignmentاكتب المحاذاة
k over s, i over i, t over t, t over t, e over i, n over n, and a gap over g.k فوق s، i فوق i، t فوق t، t فوق t، e فوق i، n فوق n، وفجوة فوق g.Name the columnsسمِّ الأعمدة
substitution, match, match, match, substitution, match, insertion.استبدال، تطابق، تطابق، تطابق، استبدال، تطابق، إدراج.Cost it both waysاحسب التكلفة بالطريقتين
Unit costs: 1 + 0 + 0 + 0 + 1 + 0 + 1 = 3. Substitution at 2: 2 + 0 + 0 + 0 + 2 + 0 + 1 = 5.التكاليف الوحدوية: 1 + 0 + 0 + 0 + 1 + 0 + 1 = 3. الاستبدال بتكلفة 2: 2 + 0 + 0 + 0 + 2 + 0 + 1 = 5.Resultالنتيجة
Distance 3 under unit costs, 5 under substitution cost 2. The alignment is optimal under both, because no cheaper one exists for either function.المسافة 3 في التكاليف الوحدوية، و5 عندما تكون تكلفة الاستبدال 2. هذه المحاذاة مثلى في الحالتين، لأنه لا توجد محاذاة أرخص منها في أي من الدالتين.
Recall
Cost the slide 82 alignment d s s _ i s under unit costs and under substitution cost 2.احسب تكلفة محاذاة الشريحة 82 (d s s _ i s) في التكاليف الوحدوية وعندما تكون تكلفة الاستبدال 2.
Quick checkاختبار سريع
Under unit costs, what is the minimum edit distance from intention to execution?في التكاليف الوحدوية، ما مسافة التحرير الدنيا من intention إلى execution؟
From an exploding search tree to a grid of prefix pairsمن شجرة بحث متفجرة إلى شبكة من أزواج البادئات
The obvious algorithm is search. Start at intention and try one edit: delete a letter and you get ntention, insert a letter and you get intecntion, substitute a letter and you get inxention. Those are three of the children. Count all of them for a 26-letter alphabet: 9 possible deletions, 26 × 10 = 260 insertions and 25 × 9 = 225 substitutions, which is 494 children for one step. The rule of thumb 2|Σ|L used below is 2 × 26 × 9 = 468 here, the same order as the exact 494 and convenient for estimating the growth. A blind search that needs five steps to reach execution touches on the order of 494^5, about 3 × 10^13 strings. SLP3 puts it plainly: the space of all possible edits is enormous, so we cannot search naively.
الخوارزمية البديهية هي البحث. ابدأ من intention وجرّب تعديلًا واحدًا: احذف حرفًا فتحصل على ntention، أدرج حرفًا فتحصل على intecntion، استبدل حرفًا فتحصل على inxention. هذه ثلاثة من الأبناء. عُدّها كلها لأبجدية من 26 حرفًا: 9 حذوفات ممكنة، و26 × 10 = 260 إدراجًا، و25 × 9 = 225 استبدالًا، أي 494 ابنًا لخطوة واحدة. والقاعدة التقريبية 2|Σ|L المستخدمة أدناه تساوي هنا 2 × 26 × 9 = 468، وهي من رتبة القيمة الدقيقة 494 نفسها ومريحة لتقدير النمو. والبحث الأعمى الذي يحتاج خمس خطوات للوصول إلى execution يلمس ما رتبته 494^5، أي نحو 3 × 10^13 سلسلة. ويقولها SLP3 صراحةً: فضاء كل التعديلات الممكنة هائل، فلا يمكننا البحث فيه بسذاجة.
The visual shows the observation that rescues the problem. Delete the i of intention and then substitute t by x and you reach nxention. Substitute t by x first and then delete the i and you reach nxention again. Two paths, one state, and once you know the cheapest way to reach a state there is no reason to explore any other route into it. SLP3 states the idea directly: many distinct edit paths end up in the same string, so rather than recomputing all those paths we can remember the shortest path to a state each time we see it. Remembering subproblem answers and combining them is Dynamic programming, Bellman's table-driven method from 1957.
يعرض الشكل الملاحظة التي تنقذ المسألة. احذف i من intention ثم استبدل t بـx فتصل إلى nxention. استبدل t بـx أولًا ثم احذف i فتصل إلى nxention مرة أخرى. مساران وحالة واحدة، وبمجرد أن تعرف أرخص طريقة للوصول إلى حالة فلا داعي لاستكشاف أي طريق آخر إليها. يقول SLP3 الفكرة مباشرة: كثير من مسارات التعديل المختلفة تنتهي إلى السلسلة نفسها، فبدلًا من إعادة حساب كل تلك المسارات يمكننا أن نتذكر أقصر مسار إلى الحالة كلما رأيناها. وتذكّر إجابات المسائل الفرعية والجمع بينها هو dynamic programming (البرمجة الديناميكية)، طريقة Bellman القائمة على الجداول من عام 1957.
Why only prefix pairs matterلماذا لا يهمّ إلا أزواج البادئات
Remembering strings is still too many states. The step that makes the table small is to notice which states can matter at all. Suppose exention lies on an optimal path from intention to execution. Then the part of the path from intention to exention must itself be optimal, because if a shorter way to exention existed we could splice it in and shorten the whole path, a contradiction. This is the Optimal substructure argument in SLP3, and it means the only thing worth remembering about a partial solution is how much of the source it has consumed and how much of the target it has produced: the pair (i, j). For two 9-letter words there are only (m + 1)(n + 1) = 10 × 10 = 100 such pairs. Put as a picture: edits are moves in a grid from (0, 0) to (m, n), each move is one operation, and dynamic programming finds the best path efficiently.
تذكّر السلاسل ما زال يعني حالات أكثر من اللازم. الخطوة التي تجعل الجدول صغيرًا هي أن نلاحظ أي الحالات يمكن أن تهمّ أصلًا. افترض أن exention تقع على مسار أمثل من intention إلى execution. عندئذ يجب أن يكون جزء المسار من intention إلى exention أمثل هو نفسه، لأنه لو وُجد طريق أقصر إلى exention لأمكننا وصله مكانه وتقصير المسار كله، وهذا تناقض. هذه هي حجة optimal substructure (البنية الجزئية المثلى) في SLP3، وهي تعني أن الشيء الوحيد الذي يستحق التذكر عن حل جزئي هو كم استهلك من المصدر وكم أنتج من الهدف: الزوج (i, j). ولكلمتين من 9 أحرف لا يوجد إلا (m + 1)(n + 1) = 10 × 10 = 100 زوج من هذا النوع. وبالصورة: التعديلات حركات في شبكة من (0, 0) إلى (m, n)، كل حركة عملية واحدة، والبرمجة الديناميكية تجد أفضل مسار بكفاءة.
| Moveالحركة | What it doesما تفعله | Operationالعملية | Recurrence termحدّ العلاقة التكرارية |
|---|---|---|---|
| Down, (i - 1, j) to (i, j)نزول، من (i - 1, j) إلى (i, j) | Consume a source letter, produce nothingيستهلك حرفًا من المصدر ولا ينتج شيئًا | Deletionحذف | D[i - 1, j] + delD[i - 1, j] + del |
| Right, (i, j - 1) to (i, j)يمين، من (i, j - 1) إلى (i, j) | Produce a target letter from nothingينتج حرفًا من الهدف من لا شيء | Insertionإدراج | D[i, j - 1] + insD[i, j - 1] + ins |
| Diagonal, (i - 1, j - 1) to (i, j)قُطري، من (i - 1, j - 1) إلى (i, j) | Pair a source letter with a target letterيقرن حرفًا من المصدر بحرف من الهدف | Substitution or matchاستبدال أو تطابق | D[i - 1, j - 1] + sub(x_i, y_j)D[i - 1, j - 1] + sub(x_i, y_j) |
A path from the top-left corner to the bottom-right corner that uses only these three moves is an alignment: each step is one column. Reading the slide 82 alignment as moves gives down, diagonal, diagonal, diagonal, right, then five diagonals, which is the staircase in the figure. Wagner and Fischer showed in 1974 that filling the grid solves the problem in time proportional to the product of the two lengths, O(mn) time and, with backpointers stored, O(mn) space. Each cell is filled once with three comparisons.
المسار من الزاوية العليا اليسرى إلى الزاوية السفلى اليمنى الذي لا يستخدم إلا هذه الحركات الثلاث هو alignment (محاذاة): كل خطوة عمود واحد. وقراءة محاذاة الشريحة 82 كحركات تعطي: نزول، قُطر، قُطر، قُطر، يمين، ثم خمس حركات قُطرية، وهذا هو الدرج في الشكل. بيّن Wagner وFischer عام 1974 أن ملء الشبكة يحل المسألة في زمن يتناسب مع حاصل ضرب الطولين، أي زمن O(mn)، ومع تخزين backpointers (المؤشرات الخلفية) مساحة O(mn). كل خلية تُملأ مرة واحدة بثلاث مقارنات.
Recall
Why is the search tree over edit sequences exponential while the grid is polynomial?لماذا تكون شجرة البحث على متتاليات التعديل أُسّية بينما تكون الشبكة كثيرة حدود؟
Quick checkاختبار سريع
In the DP grid with source letters down the rows, which move is an insertion?في شبكة البرمجة الديناميكية التي تكون فيها حروف المصدر على الصفوف نزولًا، أي حركة تمثل إدراجًا؟
Quick checkاختبار سريع
Why does dynamic programming beat naive search over edit sequences?لماذا تتفوق البرمجة الديناميكية على البحث الساذج في متتاليات التعديل؟
Three small questions give you the whole initialization. What is the distance from int to the empty string? You must delete i, n and t, so 3. From the empty string to ex? Insert e and x, so 2. From empty to empty? Nothing to do, 0. Write those as D[3, 0] = 3, D[0, 2] = 2 and D[0, 0] = 0 and you have the first row and column of every table you will ever fill.
ثلاثة أسئلة صغيرة تعطيك التهيئة كلها. ما المسافة من int إلى السلسلة الفارغة؟ عليك أن تحذف i وn وt، إذن 3. ومن السلسلة الفارغة إلى ex؟ أدرج e وx، إذن 2. ومن الفارغة إلى الفارغة؟ لا شيء يُفعل، 0. اكتبها على صورة D[3, 0] = 3 وD[0, 2] = 2 وD[0, 0] = 0 فيكون لديك الصف الأول والعمود الأول لكل جدول ستملؤه في حياتك.
Slide 85 sets the notation. The source x has length m, the target y has length n, and D[i, j] is the minimum edit distance between the prefix x[1..i] and the prefix y[1..j]. The answer to the whole problem is the last cell, D[m, n]. The Edit distance recurrence says how to fill every other cell from three neighbors.
الشريحة 85 تحدد الرموز. المصدر x طوله m، والهدف y طوله n، وD[i, j] هي minimum edit distance (مسافة التحرير الدنيا) بين البادئة x[1..i] والبادئة y[1..j]. وإجابة المسألة كلها هي الخلية الأخيرة، D[m, n]. وedit distance recurrence (العلاقة التكرارية لمسافة التحرير) تحدد كيف تُملأ كل خلية أخرى من ثلاثة جيران.
Each line is one possible last column of an optimal alignment of the two prefixes. Either the last column is x_i over a gap, in which case the rest is an optimal alignment of x[1..i-1] with y[1..j] and we pay a deletion; or it is a gap over y_j, the rest aligns x[1..i] with y[1..j-1] and we pay an insertion; or it is x_i over y_j, the rest aligns the two shorter prefixes and we pay the substitution cost, which is zero when the letters agree. There is no fourth shape a column can take, so the minimum over these three is exact. That is the optimal substructure of the previous concept written as an equation.
كل سطر يمثل عمودًا أخيرًا ممكنًا لـalignment (محاذاة) مثلى للبادئتين. إما أن يكون العمود الأخير x_i فوق فجوة، وعندها يكون الباقي محاذاة مثلى لـx[1..i-1] مع y[1..j] وندفع تكلفة حذف؛ أو يكون فجوة فوق y_j، فيحاذي الباقي x[1..i] مع y[1..j-1] وندفع تكلفة إدراج؛ أو يكون x_i فوق y_j، فيحاذي الباقي البادئتين الأقصر وندفع تكلفة الاستبدال، التي تساوي صفرًا عندما يتطابق الحرفان. لا يوجد شكل رابع يمكن أن يتخذه العمود، لذلك فالحد الأدنى على هذه الثلاثة دقيق تمامًا. وهذه هي البنية الجزئية المثلى من المفهوم السابق مكتوبة كمعادلة.
Now the exam favorite: why is D[i, 0] = i? The target prefix is empty, so every one of the i source letters has to disappear, and the only operation that removes a source letter is a deletion. No insertion can help, since it would produce a target letter where none is wanted, and no substitution can help, since it leaves a letter in place. At one unit per deletion the cost is exactly i. The mirror argument gives D[0, j] = j. In the general form of SLP3's pseudocode the border is built incrementally, D[i, 0] = D[i-1, 0] + del(x_i), which reduces to i when deletions cost one.
والآن السؤال المفضل في الامتحانات: لماذا D[i, 0] = i؟ البادئة الهدف فارغة، لذلك يجب أن يختفي كل حرف من حروف المصدر الـi، والعملية الوحيدة التي تزيل حرفًا من المصدر هي الحذف. لا يمكن لأي إدراج أن يساعد، لأنه سينتج حرفًا في الهدف حيث لا يُراد أي حرف، ولا يمكن لأي استبدال أن يساعد، لأنه يُبقي حرفًا في مكانه. وبوحدة واحدة لكل حذف تكون التكلفة i بالضبط. والحجة المعاكسة تعطي D[0, j] = j. وفي الصيغة العامة لشيفرة SLP3 الزائفة (pseudocode) يُبنى الحد تدريجيًا، D[i, 0] = D[i-1, 0] + del(x_i)، وهذا يؤول إلى i عندما تكون تكلفة الحذف واحدًا.
A table you can fill in one minuteجدول يمكنك ملؤه في دقيقة واحدة
Before the 10 × 10 table of part 11, fill a tiny one under unit costs: cat to cats. The first row and column are the initialization. Every other cell is the minimum of the cell above plus one, the cell to the left plus one, and the diagonal cell plus zero or one.
قبل جدول 10 × 10 في الجزء 11، املأ جدولًا صغيرًا في التكاليف الوحدوية: cat إلى cats. الصف الأول والعمود الأول هما التهيئة. وكل خلية أخرى هي أصغر قيمة بين الخلية التي فوقها زائد واحد، والخلية التي على يسارها زائد واحد، والخلية القُطرية زائد صفر أو واحد.
| εε | cc | aa | tt | ss | |
|---|---|---|---|---|---|
| εε | 00 | 11 | 22 | 33 | 44 |
| cc | 11 | 00 | 11 | 22 | 33 |
| aa | 22 | 11 | 00 | 11 | 22 |
| tt | 33 | 22 | 11 | 00 | 11 |
Worked exampleمثال محلول
Two cells in fullخليتان بالتفصيل الكامل
D[1, 1], c against cD[1, 1]، الحرف c مقابل c
Above: D[0, 1] + 1 = 2. Left: D[1, 0] + 1 = 2. Diagonal: D[0, 0] + sub(c, c) = 0 + 0 = 0. Minimum 0.من الأعلى: D[0, 1] + 1 = 2. من اليسار: D[1, 0] + 1 = 2. القُطر: D[0, 0] + sub(c, c) = 0 + 0 = 0. الأصغر 0.D[3, 4], cat against catsD[3, 4]، cat مقابل cats
Above: D[2, 4] + 1 = 3. Left: D[3, 3] + 1 = 1. Diagonal: D[2, 3] + sub(t, s) = 1 + 1 = 2. Minimum 1, from the left, which is an insertion of s.من الأعلى: D[2, 4] + 1 = 3. من اليسار: D[3, 3] + 1 = 1. القُطر: D[2, 3] + sub(t, s) = 1 + 1 = 2. الأصغر 1، من اليسار، أي إدراج s.Resultالنتيجة
D[3, 4] = 1: one insertion turns cat into cats, and the backpointer of the last cell already says so.D[3, 4] = 1: إدراج واحد يحوّل cat إلى cats، وbackpointer (المؤشر الخلفي) في الخلية الأخيرة يقول ذلك مسبقًا.
What the cost function can encodeما الذي يمكن أن تُرمّزه دالة التكلفة
Slide 86 spells out the unit Substitution cost: sub(a, b) = 0 if a = b, else 1. It also says the cost can be weighted, and this is where edit distance stops being a counting exercise and becomes a model. SLP3's caption to its pseudocode notes that costs can be specific to the letter, and its text adds that for spelling correction substitutions are more likely between letters that are next to each other on the keyboard. Kernighan, Church and Gale estimated four confusion matrices (deletion, addition, substitution and reversal counts) from the typos in 44 million words of 1988 AP newswire and used them as the channel probabilities of a noisy-channel spelling corrector; their top candidate agreed with the majority of three human judges in 87 percent of 329 cases. Set a substitution cost to the negative log of such a probability and the cheapest alignment becomes the most probable one.
الشريحة 86 توضح substitution cost (تكلفة الاستبدال) الوحدوية: sub(a, b) = 0 إذا a = b، وإلا 1. وتقول أيضًا إن التكلفة يمكن أن تكون موزونة، وهنا تتوقف مسافة التحرير عن كونها تمرين عدّ وتصبح نموذجًا. يذكر تعليق SLP3 على شيفرته الزائفة أن التكاليف يمكن أن تكون خاصة بكل حرف، ويضيف نصه أن الاستبدالات في تصحيح الإملاء أرجح بين الحروف المتجاورة على لوحة المفاتيح. قدّر Kernighan وChurch وGale أربع مصفوفات التباس (confusion matrices) (أعداد الحذف والإضافة والاستبدال والعكس) من الأخطاء المطبعية في 44 مليون كلمة من أخبار AP لعام 1988، واستخدموها احتمالاتِ القناة في مصحح إملاء قائم على نموذج القناة المشوِّشة (noisy channel)؛ واتفق مرشحهم الأول مع أغلبية ثلاثة محكّمين بشريين في 87 بالمئة من 329 حالة. اجعل تكلفة الاستبدال مساوية للوغاريتم السالب لاحتمال كهذا، فتصبح أرخص محاذاة هي الأكثر احتمالًا.
| Cost functionدالة التكلفة | sub(a, b)sub(a, b) | Nameالاسم | intention to executionمن intention إلى execution |
|---|---|---|---|
| Unit (slides 85 and 86)وحدوية (الشريحتان 85 و86) | 0 if a = b, else 10 إذا a = b، وإلا 1 | Levenshtein distanceمسافة Levenshtein | 55 |
| Substitution cost 2 (SLP3 tables)تكلفة استبدال 2 (جداول SLP3) | 0 if a = b, else 20 إذا a = b، وإلا 2 | Levenshtein's no-substitution variantصيغة Levenshtein بلا استبدال | 88 |
| Confusion-weightedموزونة بالالتباس | A value from a confusion matrixقيمة من مصفوفة التباس | Noisy-channel spelling correctionتصحيح الإملاء بنموذج القناة المشوِّشة | Depends on the matrixتعتمد على المصفوفة |
A cost function can also grow a fourth operation. Damerau's 1964 study listed transposition of two adjacent letters as one of the four single-error types. The simplest extension adds a fourth line to the Wagner-Fischer table, D[i-2, j-2] + cost, that applies when x_{i-1} = y_j and x_i = y_{j-1}; this restricted form is often called optimal string alignment distance, and it can overcount when a transposed pair is edited again. Lowrance and Wagner's 1975 algorithm handles that general case, and both are commonly labelled Damerau-Levenshtein distance. The typo tehcosts 2 with the three classic operations (delete one letter, insert it elsewhere) but only 1 with transposition. The slide recurrence does not include this move; treat it as an optional fourth line you can add when the application calls for it.
ويمكن لدالة التكلفة أيضًا أن تضيف عملية رابعة. دراسة Damerau عام 1964 عدّت تبديل موضع حرفين متجاورين (transposition) أحد أنواع الخطأ المفرد الأربعة. أبسط امتداد يضيف سطرًا رابعًا إلى جدول Wagner-Fischer، هو D[i-2, j-2] + cost، يُطبّق عندما x_{i-1} = y_j وx_i = y_{j-1}؛ وهذه الصيغة المقيّدة تُسمّى غالبًا مسافة المحاذاة المثلى للسلاسل (optimal string alignment distance)، وقد تبالغ في العدّ عندما يُعدَّل زوج مبدَّل مرة أخرى. أما خوارزمية Lowrance وWagner لعام 1975 فتعالج تلك الحالة العامة، وكلتاهما تُسمّى عادةً Damerau-Levenshtein distance. الخطأ المطبعي teh يكلّف 2 بالعمليات الكلاسيكية الثلاث (احذف حرفًا وأدرجه في مكان آخر) لكنه يكلّف 1 فقط مع التبديل. علاقة الشريحة لا تتضمن هذه الحركة؛ فتعامل معها كسطر رابع اختياري يمكنك إضافته عندما يتطلبه التطبيق.
Recall
Write the recurrence for D[i, j] with its initialization and say where the answer sits.اكتب العلاقة التكرارية لـ D[i, j] مع تهيئتها، وقل أين تقع الإجابة.
Recall
Why is D[i, 0] = i?لماذا D[i, 0] = i؟
Recall
flaw versus lawn: what are the Hamming distance and the edit distance, and why do they differ?flaw مقابل lawn: ما مسافة Hamming وما مسافة التحرير، ولماذا تختلفان؟
Quick checkاختبار سريع
Which operation explains why D[i, 0] = i under unit costs?أي عملية تفسّر لماذا D[i, 0] = i في التكاليف الوحدوية؟
Recapالخلاصة
If you remember nothing elseإن لم تتذكر شيئاً آخر فتذكّر هذا
- Minimum edit distance is the cheapest sequence of insertions, deletions and substitutions from source to target; with unit costs it is the Levenshtein distance.مسافة التحرير الدنيا هي أرخص متتالية من الإدراج والحذف والاستبدال تحوّل المصدر إلى الهدف؛ ومع التكاليف الوحدوية تُسمّى مسافة Levenshtein.
- Applications: spelling correction, OCR post-processing, word error rate for speech recognition, approximate matching and alignment.التطبيقات: تصحيح الإملاء، والمعالجة اللاحقة لمخرجات OCR، ومعدل خطأ الكلمات (WER) في التعرّف على الكلام، والمطابقة التقريبية، والمحاذاة.
- WER = (I + S + D) / reference words, read off a word-level alignment; insertions count, so it can exceed 100 percent.WER = (I + S + D) مقسومًا على عدد كلمات المرجع، ويُقرأ من محاذاة على مستوى الكلمات؛ الإدراجات تُحسب، لذلك قد يتجاوز 100 بالمئة.
- An alignment is a set of columns; its cost is the sum of column costs; the distance is the cost of the cheapest alignment; several alignments can tie.المحاذاة مجموعة من الأعمدة؛ تكلفتها مجموع تكاليف أعمدتها؛ والمسافة هي تكلفة أرخص محاذاة؛ وقد تتعادل عدة محاذاات في التكلفة.
- intention to execution costs 5 under unit costs and 8 when a substitution costs 2. Always state the convention.تكلفة intention إلى execution تساوي 5 في التكاليف الوحدوية و8 عندما يكلّف الاستبدال 2. صرّح دائمًا بالاصطلاح.
- The search tree over strings explodes (about 494 children per step for a 9-letter word); the grid over prefix pairs has (m + 1)(n + 1) = 100 cells.شجرة البحث على السلاسل تنفجر (نحو 494 ابنًا في كل خطوة لكلمة من 9 أحرف)؛ أما الشبكة على أزواج البادئات ففيها (m + 1)(n + 1) = 100 خلية.
- Down consumes a source letter (deletion), right produces a target letter (insertion), diagonal pairs two letters (substitution or match).النزول يستهلك حرفًا من المصدر (حذف)، والاتجاه يمينًا ينتج حرفًا من الهدف (إدراج)، والقُطر يقرن حرفين (استبدال أو تطابق).
- D[0,0] = 0, D[i,0] = i, D[0,j] = j; D[i,j] is the minimum of the three neighbors plus their operation cost; the answer is D[m,n].D[0,0] = 0 و D[i,0] = i و D[0,j] = j؛ و D[i,j] هي أصغر قيمة بين الجيران الثلاثة مضافًا إليها تكلفة عمليتها؛ والإجابة هي D[m,n].
- sub(a,b) = 0 if a = b else 1 is one choice; substitution cost 2, confusion-weighted costs and transposition (Damerau-Levenshtein) are others.sub(a,b) = 0 إذا a = b وإلا 1 هو خيار واحد؛ ومن الخيارات الأخرى تكلفة استبدال 2، والتكاليف الموزونة بمصفوفة الالتباس (confusion matrix)، والتبديل (Damerau-Levenshtein).
Sourcesالمصادر
- Speech and Language Processing, chapter 2: Words and Tokens, section 2.9 Minimum Edit DistanceBookJurafsky and Martin, draft of August 2026Definition, alignment figure 2.17, search figure 2.18, path figure 2.19, cost-2 table figure 2.20, pseudocode 2.21, backtrace 2.22التعريف، وشكل المحاذاة 2.17، وشكل البحث 2.18، وشكل المسار 2.19، وجدول التكلفة 2 في الشكل 2.20، والشيفرة الزائفة 2.21، والتتبّع الخلفي 2.22(opens in a new tab)(يفتح في تبويب جديد)
- Speech and Language Processing, chapter 16: Automatic Speech Recognition, section 16.6 Word Error RateBookJurafsky and Martin, draft of August 2026WER formula, the CallHome example with 76.9 percent, and why the rate can exceed 100 percentصيغة WER، ومثال CallHome بنسبة 76.9 بالمئة، ولماذا يمكن أن يتجاوز المعدل 100 بالمئة(opens in a new tab)(يفتح في تبويب جديد)
- Binary codes capable of correcting deletions, insertions and reversalsPaperSoviet Physics Doklady 10, 1966 (V. I. Levenshtein)Origin of the distance and of the no-substitution variant equivalent to substitution cost 2أصل المسافة، وأصل الصيغة التي لا تسمح بالاستبدال والمكافئة لتكلفة استبدال 2(opens in a new tab)(يفتح في تبويب جديد)
- The String-to-String Correction ProblemPaperJournal of the ACM 21(1), 1974 (Wagner and Fischer)The dynamic programming algorithm in time proportional to the product of the lengthsخوارزمية البرمجة الديناميكية بزمن يتناسب مع حاصل ضرب الطولين(opens in a new tab)(يفتح في تبويب جديد)
- A technique for computer detection and correction of spelling errorsPaperCommunications of the ACM 7(3), 1964 (Damerau)Single-error types including transposition; about 80 percent of errors are one edit awayأنواع الخطأ المفرد ومنها التبديل؛ نحو 80 بالمئة من الأخطاء تبعد تعديلًا واحدًا(opens in a new tab)(يفتح في تبويب جديد)
- An Extension of the String-to-String Correction ProblemPaperJournal of the ACM, 1975 (Lowrance and Wagner)Adds adjacent transposition to the Wagner-Fischer recurrence in its general, unrestricted formتضيف تبديل الحرفين المتجاورين إلى علاقة Wagner-Fischer التكرارية بصيغتها العامة غير المقيّدة(opens in a new tab)(يفتح في تبويب جديد)
- A Spelling Correction Program Based on a Noisy Channel ModelPaperCOLING 1990 (Kernighan, Church and Gale)Four confusion matrices estimated from 44 million words of 1988 AP newswire; 87 percent agreement with judges on 329 casesأربع مصفوفات التباس مقدّرة من 44 مليون كلمة من أخبار AP لعام 1988؛ واتفاق بنسبة 87 بالمئة مع المحكّمين في 329 حالة(opens in a new tab)(يفتح في تبويب جديد)
- Error Detecting and Error Correcting CodesPaperBell System Technical Journal 29(2), 1950 (Hamming)Hamming distance: substitutions only, equal lengthsمسافة Hamming: استبدالات فقط، وأطوال متساوية(opens in a new tab)(يفتح في تبويب جديد)
- Dynamic ProgrammingBookPrinceton University Press, 1957 (Bellman)The table-driven method of combining subproblem solutionsالطريقة القائمة على الجداول لجمع حلول المسائل الفرعية(opens in a new tab)(يفتح في تبويب جديد)
- SCTK, the NIST Scoring Toolkit (sclite)DocsNISTStandard WER scorer that performs the word-level alignmentالمقيّم القياسي لـ WER، وهو ينفّذ المحاذاة على مستوى الكلمات(opens in a new tab)(يفتح في تبويب جديد)
Part 11: Filling the DP table and recovering the alignmentملء جدول DP واستعادة المحاذاة
The full algorithm, a cell by cell computation for intention to execution, backpointers and backtrace to read off the alignment, the time and space complexity, and the lecture in one page.الخوارزمية كاملة، وحساب خلية بخلية لتحويل intention إلى execution، والمؤشرات الخلفية (backpointers) والتتبع العكسي (backtrace) لقراءة المحاذاة، وتعقيد الزمن والذاكرة، وملخص المحاضرة في صفحة واحدة.
5 concepts5 مفاهيم, ، slides 87-94الشرائح 87-94
Why this part mattersلماذا يهمّ هذا الجزء
The edit distance table is the most examinable algorithm in this lecture. SLP3 sets it as a by-hand exercise, and every spelling, transliteration or speech evaluation you will run in your research is this table applied to characters or words: word error rate is literally an edit distance divided by a length.
Part 10 defined the problem and the recurrence. This part makes the algorithm run. You will fill the 10 x 10 table for intention to execution cell by cell, see why the slide's table ends in 8 while the unit-cost answer is 5, store arrows as you go, and then walk those arrows home to read an alignment off the table. The same fill-then-backtrace pattern returns later in the course as Viterbi decoding and CKY parsing, so the effort pays three times.
جدول مسافة التعديل (edit distance) هو أكثر خوارزمية قابلة لأن تأتي في الامتحان من هذه المحاضرة. يضعه كتاب SLP3 تمرينًا يُحل يدويًا، وكل تقييم للتهجئة أو للنقل الحرفي (transliteration) أو للتعرف على الكلام ستجريه في بحثك هو هذا الجدول نفسه مطبقًا على الحروف أو الكلمات: فمعدل خطأ الكلمات (word error rate) هو حرفيًا مسافة تعديل مقسومة على طول.
عرّف الجزء 10 المسألة وعلاقة التكرار (recurrence). أما هذا الجزء فيجعل الخوارزمية تعمل فعلًا. ستملأ الجدول 10 x 10 لتحويل intention إلى execution خلية خلية، وسترى لماذا ينتهي جدول الشريحة بالقيمة 8 بينما الإجابة بالكلف الأحادية (unit cost) هي 5، وستخزن الأسهم أثناء الملء، ثم تتبع تلك الأسهم رجوعًا إلى البداية لتقرأ محاذاة (alignment) من الجدول. ونمط «املأ ثم تتبع رجوعًا» نفسه يعود لاحقًا في المقرر في فك ترميز Viterbi وفي التحليل النحوي CKY، فالجهد الذي تبذله الآن يؤتي ثماره ثلاث مرات.
By the end you canفي نهاية هذا الجزء ستستطيع
- Initialize and fill an edit distance table by hand under a stated cost convention and read the distance from D[n,m].تهيئة جدول مسافة التعديل (edit distance) وملؤه يدويًا وفق اصطلاح كلفة محدد، ثم قراءة المسافة من D[n,m].
- Store argmin arrows while filling and backtrace them into an alignment with operation letters.تخزين أسهم الـ argmin أثناء الملء، ثم تتبعها رجوعًا (backtrace) للحصول على محاذاة (alignment) مع حروف العمليات.
- Explain what a tie in the argmin means for the number of optimal alignments.شرح ما يعنيه التعادل في الـ argmin بالنسبة لعدد المحاذاات المثلى.
- State time and space complexity, and how two rows or Hirschberg's recursion reduce space.ذكر التعقيد الزمني والمكاني، وكيف يقلل استخدام صفين أو عودية Hirschberg من الذاكرة المطلوبة.
- Explain why slide 89 ends in 8 while unit costs give 5, and pass an exam under either convention.شرح لماذا ينتهي جدول الشريحة 89 بالقيمة 8 بينما تعطي الكلف الأحادية 5، والإجابة الصحيحة في الامتحان وفق أي من الاصطلاحين.
Start with a route you can check by eye. Take intention, delete the i to get ntention, replace n by e to get etention, replace t by x to get exention, insert u to get exenution, and replace n by c to get execution. Five edits, each of cost 1, and the string arrives exactly where it should.
ابدأ بمسار يمكنك التحقق منه بعينك. خذ intention، واحذف الحرف i لتحصل على ntention، ثم استبدل n بـ e لتحصل على etention، ثم استبدل t بـ x لتحصل على exention، ثم أدرج u لتحصل على exenution، ثم استبدل n بـ c لتحصل على execution. خمسة تعديلات، كلفة كل منها 1، وتصل السلسلة تمامًا إلى حيث يجب أن تصل.
- intention, delete i, gives ntentionintention، احذف i، فتحصل على ntention
- ntention, substitute n by e, gives etentionntention، استبدل n بـ e، فتحصل على etention
- etention, substitute t by x, gives exentionetention، استبدل t بـ x، فتحصل على exention
- exention, insert u, gives exenutionexention، أدرج u، فتحصل على exenution
- exenution, substitute n by c, gives executionexenution، استبدل n بـ c، فتحصل على execution
SLP3 states that the unit-cost Minimum edit distance between these two words is exactly 5, so this ladder is not merely a route, it is an optimal one. The interesting question is what optimality implies about the middle rungs. Suppose exention really lies on a shortest path. Then the way we reached exention must itself be the shortest way to reach exention: if a cheaper route to exention existed, we could splice it in and get a cheaper route to execution, which contradicts the assumption that our path was shortest. Every prefix of a shortest path is a shortest path. That property is called Optimal substructure, and it is the license for Dynamic programming: instead of remembering whole edit sequences, remember the best cost for every intermediate state once, and build longer answers out of shorter ones.
ينص SLP3 على أن minimum edit distance بالكلف الأحادية بين هاتين الكلمتين تساوي 5 بالضبط، لذا فهذا السلّم ليس مجرد مسار، بل مسار أمثل. والسؤال المثير هو: ماذا تعني الأمثلية بالنسبة للدرجات الوسطى؟ لنفترض أن exention تقع فعلًا على مسار أقصر. عندئذ يجب أن تكون الطريقة التي وصلنا بها إلى exention هي نفسها أقصر طريق للوصول إلى exention: فلو وُجد طريق أرخص إلى exention لأمكننا تركيبه مكان الجزء الأول والحصول على طريق أرخص إلى execution، وهذا يناقض افتراض أن مسارنا هو الأقصر. إذن كل بادئة (prefix) من مسار أقصر هي نفسها مسار أقصر. تسمى هذه الخاصية optimal substructure (البنية الجزئية المثلى)، وهي المسوّغ لاستخدام dynamic programming (البرمجة الديناميكية): فبدلًا من تذكر تسلسلات تعديل كاملة، نتذكر أفضل كلفة لكل حالة وسيطة مرة واحدة، ونبني الإجابات الأطول من الإجابات الأقصر.
The states themselves are what part 10 introduced: a pair of prefixes, the first i letters of the source and the first j letters of the target. The naive search over edit sequences explodes because thousands of different sequences pass through the same intermediate string, and each one is scored again from scratch. A table indexed by prefix pairs collapses all of those into one cell, and the Alignment you read from the table at the end is just the ladder above, laid out as a path through cells (SLP3, section 2.9.1).
أما الحالات نفسها فهي ما قدّمه الجزء 10: زوج من البادئات، أي أول i حرفًا من المصدر وأول j حرفًا من الهدف. البحث الساذج في تسلسلات التعديل ينفجر حجمه لأن آلاف التسلسلات المختلفة تمر بالسلسلة الوسيطة نفسها، وكل واحد منها يُحسب من الصفر مرة أخرى. أما الجدول المفهرس بأزواج البادئات فيدمج كل ذلك في خلية واحدة، والـ alignment (المحاذاة) التي تقرؤها من الجدول في النهاية ما هي إلا السلّم السابق نفسه، مرسومًا كمسار عبر الخلايا (SLP3، القسم 2.9.1).
Recall
Why does the fact that exention lies on an optimal path from intention to execution tell you anything about the path from intention to exention?لماذا يخبرك كون exention واقعة على مسار أمثل من intention إلى execution بشيء عن المسار من intention إلى exention؟
Compute the top-left corner of the intention to execution table by hand, using the slide's convention where a substitution costs 2. The empty string needs nothing to become the empty string, so D[0,0] = 0. Turning the one-letter prefix i into nothing takes one deletion, D[1,0] = 1. Building e from nothing takes one insertion, D[0,1] = 1. The first interior cell compares i with e: D[1,1] = min(1 + 1, 1 + 1, 0 + 2) = 2, and all three candidates tie.
احسب الزاوية العليا اليسرى من جدول intention إلى execution يدويًا، باستخدام اصطلاح الشريحة الذي تكون فيه كلفة الاستبدال 2. السلسلة الفارغة لا تحتاج إلى شيء لتصبح سلسلة فارغة، لذا D[0,0] = 0. وتحويل البادئة المكونة من حرف واحد i إلى لا شيء يتطلب حذفًا واحدًا، D[1,0] = 1. وبناء e من لا شيء يتطلب إدراجًا واحدًا، D[0,1] = 1. أول خلية داخلية تقارن i مع e: D[1,1] = min(1 + 1, 1 + 1, 0 + 2) = 2، والمرشحون الثلاثة متعادلون.
That small calculation is the whole algorithm, repeated. SLP3's pseudocode (its Fig. 2.21, reproduced on slide 88) makes it precise. Let n be the length of the source and m the length of the target, and create a matrix D with n + 1 rows and m + 1 columns, the extra row and column standing for the empty prefix. The first column is D[i,0] = D[i-1,0] + del-cost(source[i]), because the only way to turn a length-i prefix into nothing is to delete each of its letters. The first row is D[0,j] = D[0,j-1] + ins-cost(target[j]), because the only way to build a length-j prefix from nothing is to insert each letter. With unit insertion and deletion those two lines reduce to D[i,0] = i and D[0,j] = j. Then, row by row and column by column, every interior cell is the minimum of three candidates, and the answer is D[n,m].
هذا الحساب الصغير هو الخوارزمية كلها، مكررة. والشيفرة الوصفية (pseudocode) في SLP3 (الشكل 2.21 فيه، والمعروض في الشريحة 88) تجعل ذلك دقيقًا. ليكن n طول المصدر وm طول الهدف، وأنشئ مصفوفة D فيها n + 1 صفًا وm + 1 عمودًا، حيث يمثل الصف والعمود الإضافيان البادئة الفارغة. العمود الأول هو D[i,0] = D[i-1,0] + del-cost(source[i])، لأن الطريقة الوحيدة لتحويل بادئة طولها i إلى لا شيء هي حذف كل حرف من حروفها. والصف الأول هو D[0,j] = D[0,j-1] + ins-cost(target[j])، لأن الطريقة الوحيدة لبناء بادئة طولها j من لا شيء هي إدراج كل حرف. ومع كلفة إدراج وحذف أحادية يتبسط هذان السطران إلى D[i,0] = i وD[0,j] = j. ثم، صفًا بعد صف وعمودًا بعد عمود، تكون كل خلية داخلية القيمة الصغرى من ثلاثة مرشحين، والإجابة هي D[n,m].
The Edit distance recurrence looks only at three neighbors: the cell above (delete the source letter source[i], written x_i in the formula), the cell to the left (insert the target letter target[j], written y_j), and the diagonal cell (substitute one for the other, or match for free when they are equal). Nothing else in the two strings is consulted. That locality is what makes the fill order work: going row by row from the top-left, all three neighbors are already computed when you reach a cell. Any order with that property is fine, including column by column or along anti-diagonals, which is how the hover figure below animates it.
تنظر edit distance recurrence (علاقة التكرار لمسافة التعديل) إلى ثلاثة جيران فقط: الخلية العليا (حذف حرف المصدر source[i]، المكتوب x_i في الصيغة)، والخلية اليسرى (إدراج حرف الهدف target[j]، المكتوب y_j)، والخلية القطرية (استبدال أحدهما بالآخر، أو التطابق مجانًا عندما يتساويان). ولا يُرجع إلى أي شيء آخر في السلسلتين. هذه المحلية هي ما يجعل ترتيب الملء صحيحًا: عند السير صفًا بصف من الزاوية العليا اليسرى، تكون الجيران الثلاثة محسوبة مسبقًا عندما تصل إلى أي خلية. وأي ترتيب يحقق هذه الخاصية مقبول، بما في ذلك عمودًا بعمود أو على طول الأقطار المعاكسة (anti-diagonals)، وهي الطريقة التي يحرّك بها الشكل التفاعلي أدناه الملء.
Two conventions, two right answersاصطلاحان، وإجابتان صحيحتان
Slide 86 defined a unit Substitution cost, but the table on slide 89 is SLP3's Fig. 2.20, which charges 2 for a substitution. SLP3 explains the choice: a substitution can always be simulated by one deletion and one insertion, so charging 2 makes the metric coincide with the version of Levenshtein's distance that allows only insertions and deletions. Under that convention intention to execution costs 8; under unit costs it is 5, the length of the ladder from the previous concept. Both numbers are correct in their own world, and an exam answer is correct only if it names the world it lives in.
عرّفت الشريحة 86 substitution cost (كلفة الاستبدال) بأنها أحادية، لكن الجدول في الشريحة 89 هو الشكل 2.20 من SLP3، الذي يحتسب 2 للاستبدال. ويشرح SLP3 هذا الاختيار: يمكن دائمًا محاكاة الاستبدال بحذف واحد وإدراج واحد، لذا فإن احتساب 2 يجعل المقياس مطابقًا لنسخة Levenshtein distance التي لا تسمح إلا بالإدراج والحذف. وفق هذا الاصطلاح يكلف تحويل intention إلى execution القيمة 8؛ أما بالكلف الأحادية فهو 5، أي طول السلّم من المفهوم السابق. كلا الرقمين صحيح في عالمه، وإجابة الامتحان لا تكون صحيحة إلا إذا سمّت العالم الذي تنتمي إليه.
| Conventionالاصطلاح | Insertالإدراج | Deleteالحذف | Substituteالاستبدال | Matchالتطابق | Distanceالمسافة | Optimal alignmentsالمحاذاات المثلى |
|---|---|---|---|---|---|---|
| Unit (Levenshtein)أحادية (Levenshtein) | 11 | 11 | 11 | 00 | 55 | 77 |
| SLP3 table (slide 89)جدول SLP3 (الشريحة 89) | 11 | 11 | 22 | 00 | 88 | 134134 |
Here is the full table from the slide with the source intention down the rows and the target execution across the columns, followed by the same table under unit costs. Compare any substitution cell: D[1,1] is 2 in the first and 1 in the second, and that one-point gap propagates until the corners read 8 and 5.
إليك الجدول الكامل من الشريحة، والمصدر intention على امتداد الصفوف والهدف execution على امتداد الأعمدة، ويليه الجدول نفسه بالكلف الأحادية. قارن أي خلية استبدال: D[1,1] تساوي 2 في الأول و1 في الثاني، وهذا الفرق بنقطة واحدة ينتشر حتى تصبح قيمتا الزاويتين 8 و5.
| # | e | x | e | c | u | t | i | o | n | |
|---|---|---|---|---|---|---|---|---|---|---|
| # | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| i | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 6 | 7 | 8 |
| n | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 7 | 8 | 7 |
| t | 3 | 4 | 5 | 6 | 7 | 8 | 7 | 8 | 9 | 8 |
| e | 4 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 9 |
| n | 5 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 10 |
| t | 6 | 5 | 6 | 7 | 8 | 9 | 8 | 9 | 10 | 11 |
| i | 7 | 6 | 7 | 8 | 9 | 10 | 9 | 8 | 9 | 10 |
| o | 8 | 7 | 8 | 9 | 10 | 11 | 10 | 9 | 8 | 9 |
| n | 9 | 8 | 9 | 10 | 11 | 12 | 11 | 10 | 9 | 8 |
| # | e | x | e | c | u | t | i | o | n | |
|---|---|---|---|---|---|---|---|---|---|---|
| # | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| i | 1 | 1 | 2 | 3 | 4 | 5 | 6 | 6 | 7 | 8 |
| n | 2 | 2 | 2 | 3 | 4 | 5 | 6 | 7 | 7 | 7 |
| t | 3 | 3 | 3 | 3 | 4 | 5 | 5 | 6 | 7 | 8 |
| e | 4 | 3 | 4 | 3 | 4 | 5 | 6 | 6 | 7 | 8 |
| n | 5 | 4 | 4 | 4 | 4 | 5 | 6 | 7 | 7 | 7 |
| t | 6 | 5 | 5 | 5 | 5 | 5 | 5 | 6 | 7 | 8 |
| i | 7 | 6 | 6 | 6 | 6 | 6 | 6 | 5 | 6 | 7 |
| o | 8 | 7 | 7 | 7 | 7 | 7 | 7 | 6 | 5 | 6 |
| n | 9 | 8 | 8 | 8 | 8 | 8 | 8 | 7 | 6 | 5 |
Worked exampleمثال محلول
Three cells of the slide's table, substitution cost 2ثلاث خلايا من جدول الشريحة، بكلفة استبدال 2
D[1,1], i versus eD[1,1]، الحرف i مقابل e
Up gives D[0,1] + 1 = 2, left gives D[1,0] + 1 = 2, diagonal gives D[0,0] + 2 = 2. All three tie, so D[1,1] = 2 and the cell stores three arrows.الخلية العليا تعطي D[0,1] + 1 = 2، واليسرى تعطي D[1,0] + 1 = 2، والقطرية تعطي D[0,0] + 2 = 2. الثلاثة متعادلة، لذا D[1,1] = 2 وتخزن الخلية ثلاثة أسهم.D[4,2], e versus xD[4,2]، الحرف e مقابل x
Up gives D[3,2] + 1 = 6, left gives D[4,1] + 1 = 4, diagonal gives D[3,1] + 2 = 6. Left wins alone, so D[4,2] = 4 with a single left arrow.الخلية العليا تعطي D[3,2] + 1 = 6، واليسرى تعطي D[4,1] + 1 = 4، والقطرية تعطي D[3,1] + 2 = 6. اليسرى تفوز وحدها، لذا D[4,2] = 4 مع سهم واحد إلى اليسار.D[7,7], i versus iD[7,7]، الحرف i مقابل i
The letters match, so the diagonal is free: D[6,6] + 0 = 8. Up and left would give 9 + 1 and 9 + 1, so D[7,7] = 8 with one diagonal arrow.الحرفان متطابقان، لذا القطر مجاني: D[6,6] + 0 = 8. والعليا واليسرى كانتا ستعطيان 9 + 1 و9 + 1، لذا D[7,7] = 8 مع سهم قطري واحد.Resultالنتيجة
Continuing to the corner, D[9,9] = 8. Under unit costs the same three cells read 1, 4 and 5, and the corner reads 5.بالاستمرار حتى الزاوية، D[9,9] = 8. وبالكلف الأحادية تكون قيم الخلايا الثلاث نفسها 1 و4 و5، وتكون قيمة الزاوية 5.
Worked exampleمثال محلول
A table you can finish in a minute: cat to cut, unit costsجدول تنهيه في دقيقة: من cat إلى cut بالكلف الأحادية
Bordersالحواف
Row # is 0 1 2 3 and column # is 0 1 2 3.الصف # هو 0 1 2 3 والعمود # هو 0 1 2 3.Row cالصف c
c matches c, so D[1,1] = 0; then D[1,2] = 1 and D[1,3] = 2 by inserting u and t.c يطابق c، لذا D[1,1] = 0؛ ثم D[1,2] = 1 وD[1,3] = 2 بإدراج u وt.Row aالصف a
D[2,1] = 1 (delete a), D[2,2] = min(1 + 1, 0 + 1, 1 + 1) = 1 (substitute a by u), D[2,3] = 2.D[2,1] = 1 (حذف a)، وD[2,2] = min(1 + 1, 0 + 1, 1 + 1) = 1 (استبدال a بـ u)، وD[2,3] = 2.Row tالصف t
D[3,1] = 2, D[3,2] = 2, and t matches t so D[3,3] = D[2,2] + 0 = 1.D[3,1] = 2، وD[3,2] = 2، وt يطابق t لذا D[3,3] = D[2,2] + 0 = 1.Resultالنتيجة
Distance 1, alignment c a t over c u t with one substitution.المسافة 1، والمحاذاة c a t فوق c u t مع استبدال واحد.
| # | c | u | t | |
|---|---|---|---|---|
| # | 0 | 1 | 2 | 3 |
| c | 1 | 0 | 1 | 2 |
| a | 2 | 1 | 1 | 2 |
| t | 3 | 2 | 2 | 1 |
Now run the same procedure yourself. The simulator fills any pair of short words one cell at a time, prints the three candidates for each new cell, stores the arrows, and keeps both conventions side by side so you can watch the corner change from 5 to 8 with one toggle. The backtrace button belongs to the next concept; try it after reading on.
الآن نفّذ الإجراء نفسه بنفسك. يملأ المحاكي أي زوج من الكلمات القصيرة خلية في كل مرة، ويطبع المرشحين الثلاثة لكل خلية جديدة، ويخزن الأسهم، ويعرض الاصطلاحين جنبًا إلى جنب حتى ترى قيمة الزاوية تتغير من 5 إلى 8 بنقرة واحدة. أما زر التتبع الرجوعي (Backtrace) فيخص المفهوم التالي؛ جرّبه بعد أن تكمل القراءة.
| # | e | x | e | c | u | t | i | o | n | |
|---|---|---|---|---|---|---|---|---|---|---|
| # | ||||||||||
| i | ||||||||||
| n | ||||||||||
| t | ||||||||||
| e | ||||||||||
| n | ||||||||||
| t | ||||||||||
| i | ||||||||||
| o | ||||||||||
| n |
D[0,0] = 0: the empty string is already the empty string.D[0,0] = 0: السلسلة الفارغة هي أصلًا السلسلة الفارغة.
| Conventionالاصطلاح | Substitution costكلفة الاستبدال | Distanceالمسافة | Optimal alignmentsالمحاذاات المثلى |
|---|---|---|---|
| Unit (Levenshtein)موحدة (Levenshtein) | 11 | 55 | 77 |
| SLP3 table (slide 89) (shown)جدول SLP3 (الشريحة 89) (المعروض) | 22 | 88 | 134134 |
Quick checkاختبار سريع
In the recurrence, which candidate corresponds to deleting the source letter source[i]?في علاقة التكرار، أي مرشح يقابل حذف الحرف المصدر source[i]؟
Quick checkاختبار سريع
Slide 89 ends at 8 for intention to execution, but unit costs give 5. What explains the difference?ينتهي جدول الشريحة 89 بالقيمة 8 لتحويل intention إلى execution، بينما تعطي الكلف الأحادية 5. ما الذي يفسر الفرق؟
Recall
Why is the first column initialized to i and the first row to j?لماذا يُهيّأ العمود الأول بالقيمة i والصف الأول بالقيمة j؟
Recall
Which three cells does D[i,j] depend on, and what operation does each represent?على أي ثلاث خلايا تعتمد D[i,j]، وما العملية التي تمثلها كل منها؟
Put your finger on the 8 in the bottom-right corner of slide 91. That cell holds a single diagonal arrow, because n matches n and the free diagonal was the only candidate that reached 8. Step diagonally to (8,8), still 8, o matches o. Diagonal again to (7,7) for i, and to (6,6) for t. At (5,5) three arrows are drawn; the bold path takes the diagonal, substituting n by u for 2, which is why the value drops from 8 to 6 at (4,4). That cell has only a left arrow: insert c. Then (4,3) matches e for free, (3,2) substitutes t by x, (2,1) substitutes n by e, and (1,0) points up, deleting i, into (0,0).
ضع إصبعك على القيمة 8 في الزاوية السفلى اليمنى من الشريحة 91. تحمل هذه الخلية سهمًا قطريًا واحدًا، لأن n يطابق n والقطر المجاني هو المرشح الوحيد الذي وصل إلى 8. انتقل قطريًا إلى (8,8)، وما زالت القيمة 8، وo يطابق o. ثم قطريًا مرة أخرى إلى (7,7) للحرف i، وإلى (6,6) للحرف t. عند (5,5) رُسمت ثلاثة أسهم؛ والمسار العريض يأخذ القطر، مستبدلًا n بـ u بكلفة 2، ولهذا تنخفض القيمة من 8 إلى 6 عند (4,4). لهذه الخلية سهم واحد فقط إلى اليسار: إدراج c. ثم (4,3) تطابق e مجانًا، و(3,2) تستبدل t بـ x، و(2,1) تستبدل n بـ e، و(1,0) تشير إلى الأعلى، حاذفةً i، وصولًا إلى (0,0).
| Cellالخلية | Valueالقيمة | Arrow takenالسهم المتبع | Meaningالمعنى |
|---|---|---|---|
| (9,9)(9,9) | 88 | diagonalقطري | n matches n, cost 0الحرف n يطابق n، الكلفة 0 |
| (8,8)(8,8) | 88 | diagonalقطري | o matches o, cost 0الحرف o يطابق o، الكلفة 0 |
| (7,7)(7,7) | 88 | diagonalقطري | i matches i, cost 0الحرف i يطابق i، الكلفة 0 |
| (6,6)(6,6) | 88 | diagonalقطري | t matches t, cost 0الحرف t يطابق t، الكلفة 0 |
| (5,5)(5,5) | 88 | diagonalقطري | n to u, cost 2 (one of three arrows)استبدال n بـ u، الكلفة 2 (أحد ثلاثة أسهم) |
| (4,4)(4,4) | 66 | leftيسار | insert c, cost 1إدراج c، الكلفة 1 |
| (4,3)(4,3) | 55 | diagonalقطري | e matches e, cost 0 (one of two arrows)الحرف e يطابق e، الكلفة 0 (أحد سهمين) |
| (3,2)(3,2) | 55 | diagonalقطري | t to x, cost 2 (one of three arrows)استبدال t بـ x، الكلفة 2 (أحد ثلاثة أسهم) |
| (2,1)(2,1) | 33 | diagonalقطري | n to e, cost 2 (one of three arrows)استبدال n بـ e، الكلفة 2 (أحد ثلاثة أسهم) |
| (1,0)(1,0) | 11 | upأعلى | delete i, cost 1حذف i، الكلفة 1 |
| (0,0)(0,0) | 00 | stopتوقف | origin reachedالوصول إلى نقطة البداية |
Reverse the list and you have an edit sequence: delete i, n to e, t to x, match e, insert c, n to u, then four matches. Its cost is 1 + 2 + 2 + 0 + 1 + 2 + 0 + 0 + 0 + 0 = 8, the corner value, and written as rows it is SLP3's Fig. 2.17: INTE*NTION over *EXECUTION with the operation letters d s s i s under the changed columns. This is a different five-edit shape from the ladder in the first concept, yet it costs the same under both conventions, 8 here and 5 at unit costs: the ladder substitutes n by c and then inserts u, the bold path inserts c and then substitutes n by u, and both keep the four free matches at the end. The two diverge exactly at the three-arrow tie in (5,5): the left arrow leads to the ladder, the diagonal to the bold path. That is the tie rule of the next subsection in action.
اعكس القائمة فتحصل على تسلسل تعديل: حذف i، وn إلى e، وt إلى x، ومطابقة e، وإدراج c، وn إلى u، ثم أربع مطابقات. كلفته 1 + 2 + 2 + 0 + 1 + 2 + 0 + 0 + 0 + 0 = 8، أي قيمة الزاوية، وإذا كُتب على شكل صفوف فهو الشكل 2.17 من SLP3: INTE*NTION فوق *EXECUTION مع حروف العمليات d s s i s تحت الأعمدة التي تغيرت. هذا شكل مختلف من خمسة تعديلات عن السلّم في المفهوم الأول، ومع ذلك فكلفته هي نفسها وفق الاصطلاحين، 8 هنا و5 بالكلف الأحادية: السلّم يستبدل n بـ c ثم يدرج u، والمسار العريض يدرج c ثم يستبدل n بـ u، وكلاهما يحتفظ بالمطابقات المجانية الأربع في النهاية. ويفترق الاثنان تمامًا عند التعادل ذي الأسهم الثلاثة في (5,5): السهم الأيسر يقود إلى السلّم، والقطري إلى المسار العريض. هذه هي قاعدة التعادل في القسم الفرعي التالي وهي تعمل.
The general mechanism is what slide 90 states. While filling, each cell records which of its three candidates achieved the minimum, the argmin, as a Backpointer. Up means the source letter was deleted, left means the target letter was inserted, diagonal means substitution or match. After the fill, start at D[n,m] and follow arrows until D[0,0]. SLP3 puts it in one sentence: each complete path between the final cell and the initial cell is a minimum distance Alignment. Every step decreases i, j or both, so the walk takes at most n + m steps, which is why SLP3's lecture slides list the Backtrace as O(n + m).
الآلية العامة هي ما تنص عليه الشريحة 90. أثناء الملء، تسجل كل خلية أيًا من مرشحيها الثلاثة حقق القيمة الصغرى، أي الـ argmin، على شكل backpointer (مؤشر خلفي). السهم إلى الأعلى يعني أن حرف المصدر حُذف، وإلى اليسار يعني أن حرف الهدف أُدرج، والقطري يعني استبدالًا أو مطابقة. بعد الملء، ابدأ من D[n,m] واتبع الأسهم حتى D[0,0]. ويقولها SLP3 في جملة واحدة: كل مسار كامل بين الخلية الأخيرة والخلية الأولى هو alignment بأقل مسافة. وكل خطوة تُنقص i أو j أو كليهما، لذا يستغرق السير n + m خطوة على الأكثر، ولهذا تذكر شرائح محاضرة SLP3 أن backtrace (التتبع الرجوعي) يكلف O(n + m).
How to read an arrowكيف تقرأ السهم
- Upأعلى
- delete source[i], move to (i-1, j); two bold cells in one columnاحذف source[i] وانتقل إلى (i-1, j)؛ خليتان عريضتان في عمود واحد
- Leftيسار
- insert target[j], move to (i, j-1); two bold cells in one rowأدرج target[j] وانتقل إلى (i, j-1)؛ خليتان عريضتان في صف واحد
- Diagonalقطري
- substitute or match, move to (i-1, j-1); cost 0 when the letters are equalاستبدال أو تطابق، وانتقل إلى (i-1, j-1)؛ الكلفة 0 عندما يتساوى الحرفان
Ties are alternative alignmentsالتعادلات محاذاات بديلة
A cell like (1,1) on slide 91 carries three arrows because three candidates reached the same minimum. SLP3 says this directly: some cells have multiple backpointers because the minimum extension could have come from multiple previous cells. Each choice at a tie leads to a different complete path, and every complete path has the same total cost, so ties are exactly the reason multiple optimal alignments exist. For intention to execution there are 134 such paths under the cost-2 convention and 7 under unit costs (both counted for this part by walking every pointer set). Erickson shows a smaller case in his textbook, ALGORITHM to ALTRUISTIC, whose table has exactly three optimal paths. Go back to the simulator, press Backtrace, then Next alignment, and watch the highlighted path change at the teal-dotted cells while the distance stays fixed.
خلية مثل (1,1) في الشريحة 91 تحمل ثلاثة أسهم لأن ثلاثة مرشحين وصلوا إلى القيمة الصغرى نفسها. ويقول SLP3 ذلك صراحة: بعض الخلايا لها عدة مؤشرات خلفية لأن الامتداد الأدنى كان يمكن أن يأتي من عدة خلايا سابقة. كل اختيار عند التعادل يقود إلى مسار كامل مختلف، وكل مسار كامل له الكلفة الإجمالية نفسها، لذا فالتعادلات هي بالضبط سبب وجود عدة محاذاات مثلى. ولتحويل intention إلى execution يوجد 134 مسارًا من هذا النوع وفق اصطلاح الكلفة 2، و7 بالكلف الأحادية (وكلاهما حُسب لهذا الجزء بالمرور على كل مجموعة مؤشرات). ويعرض Erickson حالة أصغر في كتابه، من ALGORITHM إلى ALTRUISTIC، وجدولها فيه ثلاثة مسارات مثلى بالضبط. ارجع إلى المحاكي، واضغط Backtrace ثم Next alignment، وراقب المسار المظلل يتغير عند الخلايا المنقطة باللون الأزرق المخضر بينما تبقى المسافة ثابتة.
Quick checkاختبار سريع
A backpointer cell carries three arrows. What does that tell you about the alignments?خلية من خلايا المؤشرات الخلفية (backpointers) تحمل ثلاثة أسهم. ماذا يخبرك ذلك عن المحاذاات؟
Recall
A cell has two arrows. What does this mean for the alignments?خلية فيها سهمان. ماذا يعني ذلك بالنسبة للمحاذاات؟
Recall
Fill the unit-cost table for cat to cut and give the distance and one alignment.املأ جدول الكلف الأحادية من cat إلى cut، واذكر المسافة ومحاذاة واحدة.
The intention to execution table has 10 x 10 = 100 cells, and each cost a glance at three neighbors. Two documents of 100,000 characters each would need 10^10 cells, which is the scale where the accounting starts to matter and where the Stanford CS 262 notes on alignment begin their discussion of space.
جدول intention إلى execution فيه 10 x 10 = 100 خلية، وكل منها كلّف نظرة سريعة إلى ثلاثة جيران. أما وثيقتان طول كل منهما 100,000 حرف فستحتاجان إلى 10^10 خلية، وهذا هو الحجم الذي يبدأ عنده الحساب الدقيق للكلفة بالأهمية، وهو المكان الذي تبدأ فيه ملاحظات Stanford CS 262 عن المحاذاة نقاشها حول الذاكرة.
Time is the easy half. There are (n + 1)(m + 1) cells, each computed in constant time from three already-known neighbors, so the fill runs in O(mn), the bound Wagner and Fischer gave in 1974 and the one Erickson states for his edit distance chapter. Space is where the choices begin. Storing the whole table, as the simulator does, also takes O(mn). But look at the recurrence again: row i reads only row i - 1 and the cells to its own left. If all you want is the distance, keep two rows, the previous one and the one being filled, and throw the rest away. Put the shorter string across the columns and the memory is O(min(m,n)), exactly what slide 92 says.
الزمن هو النصف السهل. هناك (n + 1)(m + 1) خلية، تُحسب كل منها في زمن ثابت من ثلاثة جيران معروفين مسبقًا، لذا يعمل الملء في O(mn)، وهو الحد الذي قدّمه Wagner و Fischer عام 1974 والذي يذكره Erickson في فصله عن مسافة التعديل. أما الذاكرة فهي حيث تبدأ الخيارات. تخزين الجدول كاملًا، كما يفعل المحاكي، يأخذ أيضًا O(mn). لكن انظر إلى علاقة التكرار مرة أخرى: الصف i لا يقرأ إلا الصف i - 1 والخلايا الواقعة على يساره في الصف نفسه. فإذا كان كل ما تريده هو المسافة، فاحتفظ بصفين، السابق والذي يُملأ حاليًا، وتخلّص من الباقي. ضع السلسلة الأقصر على امتداد الأعمدة فتصبح الذاكرة O(min(m,n))، وهذا بالضبط ما تقوله الشريحة 92.
The price of that saving is the third bullet of the slide. The backpointers lived in the rows you discarded, so the two-row version cannot Backtrace. Erickson puts it plainly: by throwing away most of the table, we apparently lose the ability to walk backward. If you need the alignment as well, either keep the full table with its arrows, or recompute cleverly. Hirschberg's 1975 algorithm is the clever recomputation: run the two-row fill forward from the start and backward from the end, meet in the middle column to find which cell of that column the optimal path passes through, then recurse on the two halves. It recovers the full alignment in O(m + n) space while staying O(mn) in time; the CS 262 proof shows the constant roughly doubles, because every level of the recursion refills about half the area of the level above.
ثمن هذا التوفير هو النقطة الثالثة في الشريحة. فالـ backpointers كانت تعيش في الصفوف التي تخلصت منها، لذا لا تستطيع النسخة ذات الصفين إجراء backtrace. ويقولها Erickson بوضوح: بالتخلص من معظم الجدول، نفقد على ما يبدو القدرة على السير رجوعًا. إذا احتجت إلى المحاذاة أيضًا، فإما أن تحتفظ بالجدول كاملًا مع أسهمه، أو تعيد الحساب بذكاء. وHirschberg's 1975 algorithm (خوارزمية Hirschberg عام 1975) هي إعادة الحساب الذكية: نفّذ الملء بصفين إلى الأمام من البداية وإلى الخلف من النهاية، والتقِ في العمود الأوسط لتعرف أي خلية من ذلك العمود يمر بها المسار الأمثل، ثم طبّق العودية على النصفين. وهي تستعيد المحاذاة كاملة في ذاكرة O(m + n) مع بقاء الزمن O(mn)؛ ويبين برهان CS 262 أن الثابت يتضاعف تقريبًا، لأن كل مستوى من العودية يعيد ملء نحو نصف مساحة المستوى الذي فوقه.
| Goalالهدف | Timeالزمن | Spaceالذاكرة | What to storeما الذي يُخزَّن |
|---|---|---|---|
| Distance onlyالمسافة فقط | O(mn)O(mn) | O(min(m,n))O(min(m,n)) | Two rows: the previous one and the one being filledصفان: الصف السابق والصف الذي يُملأ حاليًا |
| Distance and alignmentالمسافة والمحاذاة | O(mn)O(mn) | O(mn)O(mn) | The whole table with an arrow set in every cellالجدول كاملًا مع مجموعة أسهم في كل خلية |
| Alignment in linear spaceالمحاذاة في ذاكرة خطية | O(mn), about twice the constantO(mn)، والثابت تقريبًا ضعفان | O(m+n)O(m+n) | Hirschberg's divide-and-conquer recursion, no stored tableعودية Hirschberg القائمة على التقسيم والدمج (divide-and-conquer)، دون تخزين الجدول |
Quick checkاختبار سريع
You need only the distance between two strings of lengths m and n. What is the least memory the standard algorithm needs?تحتاج فقط إلى المسافة بين سلسلتين طولاهما m و n. ما أقل ذاكرة تحتاجها الخوارزمية القياسية؟
Recall
You need only the distance between two long strings. How much memory do you need and why?تحتاج فقط إلى المسافة بين سلسلتين طويلتين. كم من الذاكرة تحتاج، ولماذا؟
Slide 93 closes the lecture with seven lines, and they tell one story. A word is not a universal primitive, so Tokenization is a design decision rather than a fact about text. Whatever units you pick, their frequencies follow a heavy tail (Zipf for rank against frequency, Heaps for vocabulary growth), so a fixed word vocabulary always leaks unseen words, and subwords are the answer.
تختم الشريحة 93 المحاضرة بسبعة أسطر، وهي تروي قصة واحدة. الكلمة ليست وحدة أولية عامة، لذا فإن tokenization (التقطيع) قرار تصميمي وليس حقيقة عن النص. وأيًا كانت الوحدات التي تختارها، فإن تكراراتها تتبع ذيلًا ثقيلًا (Zipf للرتبة مقابل التكرار، وHeaps لنمو المفردات)، لذا فإن أي مفردات كلمات ثابتة ستتسرب منها دائمًا كلمات غير مرئية سابقًا، والوحدات الجزئية (subwords) هي الحل.
Morphology shows that words do have meaningful pieces, morphemes, but that segmenting them cleanly is hard and differs across languages. Unicode and UTF-8 make multilingual text representable at all, and their bytes are the universal fallback when nothing else fits. BPE then learns a compact, reusable subword vocabulary from data, with a regex pre-tokenizer doing the practical work of splitting and normalizing before it. Finally, once text has become strings of units, the Minimum edit distance table you just filled is the foundational dynamic program for saying how similar two of those strings are.
يبين علم الصرف (morphology) أن للكلمات فعلًا أجزاء ذات معنى، هي morphemes (المورفيمات)، لكن تقطيعها بشكل نظيف صعب ويختلف من لغة إلى أخرى. و Unicode وUTF-8 يجعلان النص متعدد اللغات قابلًا للتمثيل أصلًا، وبايتاتهما هي الخيار الاحتياطي العام حين لا يناسب أي شيء آخر. ثم تتعلم BPE مفردات وحدات جزئية مضغوطة وقابلة لإعادة الاستخدام من البيانات، مع مقطّع مسبق (pre-tokenizer) مبني على regex يتولى العمل العملي للتقسيم والتطبيع قبلها. وأخيرًا، بعد أن يصبح النص سلاسل من الوحدات، يكون جدول minimum edit distance الذي ملأته للتو هو البرنامج الديناميكي الأساسي لقياس مدى تشابه سلسلتين من تلك السلاسل.
- Word is not a universal primitive; tokenization is a design decision.الكلمة ليست وحدة أولية عامة؛ والتقطيع (tokenization) قرار تصميمي.
- Vocabulary growth follows a heavy tail (Zipf, Heaps), which motivates subwords.نمو المفردات يتبع ذيلًا ثقيلًا (Zipf، Heaps)، وهذا ما يبرر الوحدات الجزئية (subwords).
- Morphology differs across languages; morphemes are meaningful but not always easy to segment.الصرف يختلف بين اللغات؛ والمورفيمات ذات معنى لكن تقطيعها ليس سهلًا دائمًا.
- Unicode and UTF-8 make multilingual text possible, and bytes are a universal fallback.Unicode وUTF-8 يجعلان النص متعدد اللغات ممكنًا، والبايتات خيار احتياطي عام.
- BPE learns a compact, reusable subword vocabulary.BPE تتعلم مفردات وحدات جزئية مضغوطة وقابلة لإعادة الاستخدام.
- Regex is the practical tool for pre-tokenization and normalization.التعابير النمطية (regex) هي الأداة العملية للتقطيع المسبق والتطبيع.
- Minimum edit distance is the foundational DP algorithm for string similarity.مسافة التعديل الصغرى (minimum edit distance) هي خوارزمية البرمجة الديناميكية الأساسية لقياس تشابه السلاسل النصية.
Recapالخلاصة
If you remember nothing elseإن لم تتذكر شيئاً آخر فتذكّر هذا
- D[i,0] = i deletions, D[0,j] = j insertions, D[0,0] = 0.D[i,0] = i عمليات حذف، و D[0,j] = j عمليات إدراج، و D[0,0] = 0.
- D[i,j] is the minimum of up plus delete, left plus insert, and diagonal plus substitute, where substitute costs 0 on a match.D[i,j] هي القيمة الصغرى من: الخلية العليا زائد كلفة الحذف، والخلية اليسرى زائد كلفة الإدراج، والخلية القطرية زائد كلفة الاستبدال، حيث تكون كلفة الاستبدال 0 عند التطابق.
- intention to execution costs 5 under unit costs and 8 under SLP3's cost-2 substitution; slide 89 uses cost 2.تحويل intention إلى execution يكلف 5 بالكلف الأحادية، و8 وفق اصطلاح SLP3 الذي يجعل كلفة الاستبدال 2؛ والشريحة 89 تستخدم الكلفة 2.
- Store the argmin arrows while filling; backtrace from D[n,m] to D[0,0] in O(n+m) steps; several arrows in a cell mean several optimal alignments (134 at cost 2, 7 at cost 1 for this pair).خزّن أسهم الـ argmin أثناء الملء؛ ثم تتبعها رجوعًا من D[n,m] إلى D[0,0] في O(n+m) خطوة؛ ووجود عدة أسهم في خلية يعني وجود عدة محاذاات مثلى (134 بالكلفة 2، و7 بالكلفة 1 لهذا الزوج من الكلمات).
- Time O(mn). Space O(mn) with the table, O(min(m,n)) with two rows when only the distance is needed. Hirschberg recovers the alignment in O(m+n) space.الزمن O(mn). والذاكرة O(mn) مع الجدول الكامل، و O(min(m,n)) مع صفين فقط عندما نحتاج المسافة وحدها. وخوارزمية Hirschberg تستعيد المحاذاة في ذاكرة O(m+n).
- Lecture takeaways: tokenization is a design decision; heavy tails motivate subwords; morphemes are meaningful but hard to segment; Unicode and UTF-8 with bytes as the fallback; BPE learns a compact vocabulary; regex handles pre-tokenization and normalization; edit distance is the foundational DP for string similarity.خلاصات المحاضرة: التقطيع (tokenization) قرار تصميمي؛ والذيول الثقيلة في توزيع الكلمات تبرر استخدام الوحدات الجزئية (subwords)؛ والمورفيمات ذات معنى لكن تقطيعها صعب؛ و Unicode و UTF-8 مع البايتات كخيار احتياطي؛ و BPE تتعلم مفردات مضغوطة؛ والتعابير النمطية (regex) تتولى التقطيع المسبق والتطبيع؛ ومسافة التعديل هي خوارزمية البرمجة الديناميكية الأساسية لقياس تشابه السلاسل النصية.
Sourcesالمصادر
- Speech and Language Processing, 3rd edition, chapter 2: Words and TokensBookStanford University (Jurafsky and Martin)Section 2.9, Eq. 2.19 and 2.20, Figs. 2.17 and 2.19 to 2.22 in the August 19, 2026 releaseالقسم 2.9، والمعادلتان 2.19 و 2.20، والأشكال 2.17 و 2.19 إلى 2.22 في إصدار 19 أغسطس 2026(opens in a new tab)(يفتح في تبويب جديد)
- Speech and Language Processing, online manuscript indexDocsStanford University (Jurafsky and Martin)Cited on slide 94 as the January 6, 2026 manuscriptمذكور في الشريحة 94 بوصفه مخطوطة 6 يناير 2026(opens in a new tab)(يفتح في تبويب جديد)
- Minimum Edit Distance lecture slidesDocsStanford University (Jurafsky)Time O(nm), space O(nm), backtrace O(n+m); remember where you came fromالزمن O(nm)، والذاكرة O(nm)، والتتبع الرجوعي O(n+m)؛ تذكّر من أين أتيت(opens in a new tab)(يفتح في تبويب جديد)
- The String-to-String Correction ProblemPaperJournal of the ACM 21(1):168-173, 1974 (Wagner and Fischer)The O(mn) dynamic programming algorithmخوارزمية البرمجة الديناميكية ذات التعقيد O(mn)(opens in a new tab)(يفتح في تبويب جديد)
- A linear space algorithm for computing maximal common subsequencesPaperCommunications of the ACM 18(6):341-343, 1975 (Hirschberg)Alignment recovery in O(mn) time and linear spaceاستعادة المحاذاة في زمن O(mn) وذاكرة خطية(opens in a new tab)(يفتح في تبويب جديد)
- Binary codes capable of correcting deletions, insertions, and reversalsPaperDoklady Akademii Nauk SSSR 163(4):845-848, 1965 (Levenshtein)Origin of the Levenshtein distanceأصل مسافة Levenshtein(opens in a new tab)(يفتح في تبويب جديد)
- Algorithms, chapter 3: Dynamic ProgrammingBookJeff Erickson, University of IllinoisEdit distance in O(mn) time and space; ALGORITHM to ALTRUISTIC with three optimal pathsمسافة التعديل في زمن وذاكرة O(mn)؛ وتحويل ALGORITHM إلى ALTRUISTIC بثلاثة مسارات مثلى(opens in a new tab)(يفتح في تبويب جديد)
- Algorithms, appendix D: Advanced Dynamic Programming, D.1 Saving SpaceBookJeff Erickson, University of IllinoisTwo-row trick, loss of the backward walk, and Hirschberg's O(m+n) space boundحيلة الصفين، وفقدان القدرة على السير رجوعًا، وحد الذاكرة O(m+n) لخوارزمية Hirschberg(opens in a new tab)(يفتح في تبويب جديد)
- CS 262 lecture 3 notes: Linear Space AlignmentDocsStanford UniversityTwo-column scoring, Hirschberg's O(N+M) space and O(MN) time with about twice the constantحساب الدرجات بعمودين، وخوارزمية Hirschberg بذاكرة O(N+M) وزمن O(MN) مع ثابت يقارب الضعف(opens in a new tab)(يفتح في تبويب جديد)
- Introduction to Algorithms, 4th editionBookMIT Press, 2022 (Cormen, Leiserson, Rivest and Stein)Dynamic programming chapter: optimal substructure and overlapping subproblemsفصل البرمجة الديناميكية: البنية الجزئية المثلى والمسائل الجزئية المتداخلة(opens in a new tab)(يفتح في تبويب جديد)