Final Recap: Parsing, Contextual Embeddings, Word Sense, Retrieval Augmented Generation and Text Summarization
Prerequisite Knowledge
This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.
Previously Covered in This Subject
- Key Industry Applications — covered in Lecture 4: CBOW, GloVe, and Statistical Language Modeling
- Dependency Parsing — covered in Lecture 10: Dependency Parsing
- Dependency Parsing — covered in Lecture 11: Contextual Word Embedding and Attention Mechanisms
- Contextual Word Embedding and Attention — covered in Lecture 11: Contextual Word Embedding and Attention Mechanisms
- Contextual Word Embedding and Attention — covered in Lecture 12: Contextual Word Embedding and Word Sense Disambiguation
- Word Sense Disambiguation, WordNet and Knowledge Graphs — covered in Lecture 12: Contextual Word Embedding and Word Sense Disambiguation
- Word Sense Disambiguation, WordNet and Knowledge Graphs — covered in Lecture 13: Knowledge Graphs and Semantic Web
- Retrieval Augmented Generation (RAG) — covered in Lecture 13: Knowledge Graphs and Semantic Web
- Key Industry Applications — covered in Lecture 13: Knowledge Graphs and Semantic Web
- Retrieval Augmented Generation (RAG) — covered in Lecture 14: Retrieval Augmented Generation
- Text Summarization — covered in Lecture 15: Text Summarization
This is the final post-midterm recap for Natural Language Processing, tying together the second half of the course. The session revisits evaluation (ROUGE), structure (constituency and dependency parsing with PCFG, CKY, arc-eager and Chu-Liu Edmonds), representation (contextual embeddings and self-attention), knowledge (WSD, WordNet, ontologies and knowledge graphs), grounding (RAG with token, chunk, and latency budgets), and distillation (text summarization with TF-IDF, LexRank, and MMR). The goal is not new theory but synthesis: procedures you can apply with given rules, tables, and formulas in an open-book exam, and patterns you will meet in industry RAG and summarization projects.
How to use these notes: for each of the eight technical sections (16.1–16.8) the spine gives hook, intuition with analogy, formal definitions with every symbol named, fully worked examples with numbers and checks, scope and pitfalls, visual description, and bridge to the next section. Exam boxes highlight mark allocation and question types; Q&A boxes preserve the professor's corrections. Work through the worked examples with a pen, then practice the sample paper CNF/CKY question and one ROUGE/MMR/RAG numerical without looking.
16.1 ROUGE — Recall-Oriented Evaluation for Summarization
16.1.1 Definition, Role and Intuition
Hook: How do you grade a summary when ten people would write ten different good summaries? You cannot look for one perfect answer. You need a way to ask: how much of what humans wrote did the machine also write?
A ROUGE score — Recall-Oriented Understudy for Gisting Evaluation — measures how much overlap exists between a system-generated summary and one or more human reference summaries. The name tells you the bias: it is recall-oriented, so it asks what fraction of the reference content was covered, not what fraction of the machine output was correct. It is the standard evaluation used for every summarization approach, whether extractive, abstractive, single-document or multi-document, rule-based, statistical, or neural. Irrespective of the method that builds the summary, the same ROUGE measure checks quality.
The intuition is direct: count words or word sequences that are common between the reference and the generated text, then normalize. When words match exactly as strings, they count. Ordering matters more when longer continuous sequences are checked. A human reference is needed as the gold benchmark; quality is judged by similarity to that benchmark. A toy example might use only one sentence, while real evaluations use many sentences, but the measure itself does not change. Because human references differ from person to person, using three references instead of one gives a fairer denominator — the system gets credit if it matches any of the trusted human phrasings.
Intuition and analogy — the highlighter test: Think of a reference summary as a teacher's answer sheet highlighted in yellow. Each word or phrase is a yellow mark. ROUGE lifts the student's summary and counts how many yellow marks are also present in the student's paper. ROUGE-1 counts single yellow words: did the student use the same words at all? ROUGE-2 counts pairs of consecutive yellow words: did the student keep two words together in the right order? The longer the counted sequence, the stricter the check on ordering. Where the analogy breaks: a student who paraphrases with synonyms understood the material but gets zero yellow marks under strict string match. That is why later methods like BERTScore count meaning, not just string.
Real-world placement: this is the score used across industry for all summarization systems, in the same way BLEU is used for machine translation. In this course ROUGE is the examinable metric for summarization evaluation, while BLEU and BERTScore will be studied in the follow-up NLP applications course. For deployment, teams report ROUGE-2 and ROUGE-3 because they balance word choice and word order, and they set a threshold such as 0.35 or 0.43 to decide whether a summary is good enough to ship.
Exam note: for text summarization expect a mathematical problem on evaluation — compute ROUGE-N from given reference and candidate, with denominator — or a problem on MMR and related concepts, or an application-oriented summary task where you state the metric and threshold. Show every counting step in a table.
16.1.2 Mathematical Formulation
The verbal description in the session was: count the number of words that are common across the reference summary and the generated summary, divide by the total -grams in the reference set. The reconciled formula for ROUGE-N is
where is an -gram, a continuous sequence of words, is the number of -grams co-occurring in the candidate summary and the reference, is the total number of -grams in the references, and the outer sum aggregates over all available human references.
Normalization is essential. Without it, a long reference would automatically score higher. With normalization, the score is a proportion in , often reported as a percentage, and a threshold can be set: only if the score exceeds the threshold is the system summary judged good.
Formalize — every symbol named: (gram order, integer ) tells how many consecutive words form one unit. (integer) is the total number of words in a single reference summary. is one reference summary, a sequence of words. counts how many times a particular -gram appears in both candidate and that reference. counts -grams in the reference alone. The result is a recall: numerator is covered material, denominator is total reference material. Higher is better. For reporting, becomes or about .
An important counting relation was stated verbally as: if you have 11 words you have 10 bigrams; bigrams are . More generally, derived from the sliding window argument:
This holds because a sliding window of size can start at positions through . A reference with and yields windows; with yields . The denominator for ROUGE-N therefore changes with : for ROUGE-2 use , for ROUGE-3 use .
Reconciled against standard definition (Lin 2004): the form above is the recall version. Some toolkits also report ROUGE precision and F-measure, but the lecture and the exam use the recall form shown here. Texts often write the same idea as overlapping -grams over reference -grams; notation matches the companion document on summarization evaluation.
In the session, ROUGE-1 was described as simply counting overlapping single words, ROUGE-2 as checking two words at a time, ROUGE-3 as checking three words at a time. That progression shows how ordering sensitivity grows with .
16.1.3 Worked Example — ROUGE-2 with Three References
Worked example — ROUGE-2 with three references, numerator 12, denominator 28, score 0.43
Setup. Three human reference summaries are available (a luxury not always available; sometimes only one). One system-generated candidate summary is to be evaluated. The measure computed is ROUGE-2, so . Only consecutive two-word sequences (bigrams) count if they appear in the same order in both reference and candidate. References concern water spinach.
Step 1 — denominator per reference.
- Reference 1 contains 11 words. Number of bigrams:
Contribution .
- Reference 2 contains 10 words:
Contribution .
- Reference 3 contains 10 words:
Contribution .
Total denominator:
Step 2 — numerator per reference (common bigrams).
- For reference 1, three common bigrams were identified: "water spinach", "spinach is", "is a". After that no consecutive bigrams matched because the remaining wording diverges (vegetable grown versus vegetable commonly etc). Contribution .
- For reference 2, again three common bigrams: "water spinach", "spinach is", "is a" overlap with the candidate. Contribution .
- For reference 3, six common bigrams were found. Count them explicitly: 1 "water spinach", 2 "spinach is", 3 "is a", 4 "commonly eaten", 5 "leaf vegetable", 6 "of Asia". Note that "leaf vegetable" must appear consecutively and exactly as that pair to count; the pair was counted as matching. Total for third reference .
Step 3 — total numerator and score.
Total numerator:
ROUGE-2 score:
Reported as . The numerator 12 and denominator 28 and score 0.43 are the numbers the manifest anchors.
Step 4 — sense check. Is reasonable? Yes. With three references the denominator 28 is modest, and 12 overlapping bigrams means less than half of reference bigrams were reproduced exactly — typical for abstractive candidates. For reference 3, six of nine bigrams overlapped, so that reference alone would score ; averaging with the two lower references pulls the final to .
Extension to ROUGE-3 (same principle, different denominator). For ROUGE-3, look for three consecutive words, numerator counts common trigrams, denominator uses per reference. For , trigrams ; for , trigrams . So denominator would be . For this example two overlapping trigrams were noted for ROUGE-3 in the first references, such as "water spinach is" and "spinach is a" type triples, with extra trigrams in the third reference. The session noted not to dwell on exact ROUGE-3 count beyond the principle that denominator is and ordering matters more.
The final step after scoring is thresholding: decide a minimum ROUGE score required to declare the system summary good. The threshold is chosen per application — for example, — and higher typically yields lower absolute scores because longer exact matches are rarer. A system scoring under a threshold would pass; under it would fail.
16.1.4 ROUGE-1, ROUGE-3 and Generalization
ROUGE-1 is simple word overlap ignoring order:
ROUGE-2 captures ordering better than ROUGE-1; ROUGE-3 and ROUGE-4 capture even more ordering, but scores drop quickly. In practice ROUGE-2 and ROUGE-3 are the common choices because ROUGE-1 ignores order too much and gives high scores even when sentences are shuffled, while ROUGE-2 and higher capture that continuous 2, 3, or 4 words retain order information. The session emphasized that ROUGE-1 will still give a high result even if word order differs, so industry typically reports ROUGE-2 and ROUGE-3 as the balanced view.
Computation for any order follows the same template:
For a second worked illustration with tiny numbers (self-check): if a reference has words "a b c d e", bigrams are "a b", "b c", "c d", "d e" — four bigrams . Trigrams are "a b c", "b c d", "c d e" — three . If candidate is "a b d e", common bigrams are "a b" and "d e" , so ROUGE-2 .
Scope and assumptions: ROUGE assumes string-exact match, case-sensitive unless lower-cased in preprocessing, and no stemming unless applied. It assumes at least one human reference is trustworthy. It is recall-oriented, so it rewards covering reference content but does not penalize a verbose candidate that adds extra unrelated text, except via precision variants. When paraphrase is common, ROUGE alone is not sufficient — that is where BERTScore or human judgment is added. The formula also assumes ; a reference shorter than contributes zero -grams.
Visual intuition: imagine a bar chart where the x-axis is (1, 2, 3, 4) and y-axis is ROUGE score for the same candidate against the same references. The bars fall as grows: ROUGE-1 is highest, ROUGE-4 is lowest, forming a decreasing staircase. The steepness shows how much word order matters in that dataset. Landmark: if ROUGE-1 is but ROUGE-2 is , the candidate gets words right but order wrong. Takeaway: report at least two points on this curve to see both coverage and ordering.
Comparison — ROUGE versus BLEU versus BERTScore:
| Dimension | ROUGE (summarization) | BLEU (translation) | BERTScore (embedding) |
|---|---|---|---|
| Direction | recall: reference coverage | precision: candidate accuracy with brevity penalty | recall/precision/F1 on vectors |
| Match unit | -gram string | -gram string, clipped | cosine of contextual embeddings |
| Order sensitivity | grows with | grows with | soft, via embeddings |
| Paraphrase | fails unless normalized | fails unless normalized | succeeds, similar vectors close |
| When to pick | summarization where missing info hurts | translation where extra words hurt | abstractive summaries with paraphrase |
One-line guide: for summarization prefer ROUGE (recall); for translation prefer BLEU (precision); when paraphrase tolerance matters add BERTScore.
Pitfalls — what the professor flagged:
- Leaf versus leafy: treating morphological variants as matches without stemming. Leaf and leafy share a root but are different strings, so ROUGE counts zero unless you normalize.
- Hyphen handling: "semi-aquatic" as one token versus two after splitting. Your score changes if you split and the reference did not. State preprocessing in your answer.
- Forgetting denominator change with : using for ROUGE-3 gives too large a denominator and a falsely low score. Always use .
- Averaging before counting: averaging per-reference ROUGE and then averaging again can double-count. Compute numerator and denominator per the formula's outer sum, then divide once, or average per query after scoring each query independently.
16.1.5 Student Questions and Answers
Q: Are "a leaf vegetable" and "a leafy vegetable" the same?
A: No. Without stemming or morphological analysis, the comparison is string literal. Leaf and leafy are treated as two different words and do not match. If preprocessing removes or normalizes suffixes, they might be merged, but in the ROUGE calculation as presented, with no preprocessing, they are distinct. By contrast, a vector-based alternative called BERTScore looks at word embeddings; there, leaf and leafy have similar vectors (cosine close to 1) and would be judged similar. That approach will be studied next semester but is out of scope for the current ROUGE calculation. The session flagged this as a warning: ROUGE counts string overlap, so morphological variants count as mismatches unless you state normalization. [Teaching moment 16.1.moment.1 — leaf versus leafy string mismatch without stemming, BERTScore vector alternative]
Q: In ROUGE-3 will the denominator count also change — is it still ? [16.1.qna.2]
A: Yes. For trigrams it is . In general . So for ROUGE-3 count trigrams as per reference, not . For ROUGE-1 it is , for ROUGE-2 it is , for ROUGE-4 it would be . Higher always reduces denominator and typically reduces numerator faster.
Q: Can you explain again how the six became six for the third reference? [16.1.qna.3]
A: The six overlapping bigrams for reference 3 are: 1 water spinach, 2 spinach is, 3 is a, 4 commonly eaten, 5 leaf vegetable, 6 of Asia. Counting them gives 6. The earlier recount confirmed commonly eaten as an overlapping pair, plus leaf vegetable and of Asia as additional pairs beyond the first three that are shared across all references. So contributions per reference are 3, 3, and 6, total numerator 12 over denominator 28, giving ROUGE-2 about 0.43.
Q: For the second sentence we have "semi-aquatic" with a dash — will we consider the dash while calculating -grams or just the text part? [16.1.qna.4]
A: The complete word is taken as a single token "semi-aquatic" together; it is not split. Whether the hyphen or dash is kept, removed, or split depends on preprocessing rules. If preprocessing removes underscores or hyphens, it would be split into "semi" and "aquatic", but as presented with no special preprocessing, the whole hyphenated string is one word and one position in the count. Always state your tokenization rule before counting; the exam expects you to write the assumption.
Q: If we do text summarization with different ordering or paraphrasing, exact word overlap will be low, so ROUGE will be very low. Should we use different metrics for different use cases? Would BLEU be more suitable than ROUGE? [16.1.qna.5]
A: For summarization, ROUGE remains more suitable than BLEU. BLEU is popular for machine translation and will be covered in the next semester including Indic translation. BLEU is precision-oriented and punishes extra words, while summarization cares more about recall of reference content. When exact string overlap is low due to paraphrase, vector-based evaluation like BERTScore is used: word embeddings are computed and cosine similarity between embeddings decides match, so paraphrases with similar meaning still score high. The same ROUGE overlap idea is retained, only the similarity is measured on vectors rather than literal strings. So keep ROUGE for summarization, add embedding-based scores when paraphrase tolerance is needed.
Q: We talked about one query and one human answer; in practice we will have a bunch of queries and system answers with human answers. Do we average? [16.1.qna.6]
A: Yes. Compute ROUGE per query against its references, then take the mean across all queries — often called mean ROUGE or macro-average. Evaluation is done after the summarization system is developed, like black-box testing after the project is built, regardless of whether the system uses transformers, rule-based, or machine learning methods. Report both per-query scores and the mean, so variance is visible.
16.1.6 Industry and Pedagogical Notes
Real-world: ROUGE is the standard recall-oriented measure applied across industry for summarization benchmarks. Every extractive, abstractive, single-document or multi-document system is judged with the same ROUGE logic. BERTScore and related embedding-based scores complement ROUGE when paraphrase tolerance is needed; there the word vectors are compared instead of literal strings, so "leaf" and "leafy vegetable" are close in vector space. Modern LLM and AI model evaluation also uses larger toolkits like RAG evaluation harnesses, which include many task-specific measures for conversational AI and question answering; those advanced evaluations are slated for the next semester.
A caution retained from the session: ROUGE counts string overlap, so morphological variants and hyphenated forms count as mismatches unless explicitly normalized in preprocessing. For the exam, always write your tokenization and normalization assumptions, show bigram lists, and state the threshold decision.
Recap and bridge: ROUGE-N counts common -grams over reference -grams, with denominator per reference. The worked case gave . ROUGE-1 ignores order, ROUGE-2 and ROUGE-3 capture order, and string match without preprocessing misses paraphrase. This evaluation mindset carries directly into Text Summarization (16.8) where MMR chooses sentences and ROUGE judges the final summary, and into RAG evaluation where answer grounding is checked.
16.2 Constituency Parsing — Ambiguity, Grammar and Strategies
16.2.1 Why Parsing Matters and the Ambiguity Problem
Hook: One short sentence can mean 132 different things. Without parsing, which meaning does the machine pick?
Ambiguity — the property that the same surface string maps to many meanings — is the central reason parsing exists. The surface words are fixed, but the relations among them are not. Even with modern transformers that learn relations implicitly, ambiguity remains because natural language permits the same words to attach at different places in a tree.
A vivid example retained from the session: the sentence involving "I saw the man on the hill with a telescope in Texas" was said to have 132 interpretations. The count is not a guess: each prepositional phrase "on the hill", "with a telescope", "in Texas" can attach to the verb "saw", to the noun "man", or to the noun "hill", and those choices multiply. Parsing means deciding, based on the relation among words, which interpretation holds. Was the telescope used to see the man? Was the speaker in Texas? Was the man on the hill? Was the speaker on the hill? Different attachment points produce different meanings. Parsing makes syntactic relations explicit so downstream tasks can ground meaning correctly.
Intuition and analogy — the family photo caption: Think of a sentence as a family photo with no labels. You see four people, but you do not know who is parent of whom. Ambiguity is that same photo fitting many family trees. Parsing is drawing the family tree lines: who governs whom. A constituency parser groups people into families (phrases), a dependency parser draws direct parent arrows between individuals. Where analogy breaks: in a tree, a person has one parent; in language, a phrase can have two parents in different analyses, but only one tree is correct in context.
Real-world placement: parsing supports automatic grammar correction, relation extraction, conversational AI, information extraction, and semantic search. Today many systems capture relations implicitly via transformers and self-attention, but earlier explicit parsing is more explainable and still used when you need to enforce grammatical rules, such as correcting a student's essay or ensuring machine translation respects target-language grammar. Both views teach the same core: relations among words must be resolved before meaning is reliable. Modern pipelines often combine both — explicit parse features for safety, attention for coverage.
Exam note: parsing, including statistical and dependency parsing, together accounts for six marks. Expect a small problem or an application-oriented question such as building a parse tree from given rules, or explaining why constituency suits grammar checking while dependency suits relation extraction. Rules and POS tags will be given; you decide phrase boundaries.
16.2.2 Grammar, Part-of-Speech and Parse Tree
A parser needs two inputs, and the exam will give you both, so you do not need to memorize them:
- A set of context-free grammar (CFG) rules. A typical top rule is , where is sentence, is noun phrase, is verb phrase. Further rules expand phrases: and many others such as , , . Do not memorize rules; they will be provided in the exam and you apply them.
- The part-of-speech (POS) tag of each word in the sentence — for example, Article, Adjective, Noun, Verb, Auxiliary. The tag restricts which rules can fire.
Given a sentence and the rules, a parse tree depicts relations among words as a hierarchy whose leaves are words and whose internal nodes are phrase labels. Two broad families exist: phrase-structure (constituency) parsing, which groups words into phrases (NP, VP, PP), and dependency parsing (covered in 16.4), which directly connects words with headed arcs.
Formalize — CFG essentials: A CFG is a tuple where is non-terminals such as , is terminals (words), is productions of form with and a string of terminals and non-terminals, and is the start symbol. A derivation yields sentence . A parse tree records which productions were used. Example: . Well-formedness requires every leaf word to be reachable from via allowed productions and every branching to match a rule exactly.
Example of rule use: for "The large can", the rule licenses grouping those three words as one NP if tags are Article, Adjective, Noun respectively. If "can" is instead tagged Aux, that rule cannot fire, so a different analysis is needed. That is how POS tags prune analyses.
16.2.3 Top-Down, Bottom-Up and Chart Parsing
Three strategies for the same grammar:
- Top-down parsing starts from the sentence symbol and expands left-hand side rules step by step until the leaf words are reached: start with , break and further, continue until leaves match the input. It predicts structure before seeing words, so it is goal-directed but may explore dead ends.
- Bottom-up parsing does the opposite: start from the words, apply only rules that are applicable to those words, then combine those constituents upward to reach the root . It is data-directed: only rules that fit observed tags are tried.
- Chart parsing addresses repeated work shared by both. Some constituents like articles are processed again and again across different branches. A chart is a data structure, a memory table indexed by span positions, that stores partial results already computed (often marked by a dot indicating how much of a rule has been processed, as in ). When the same word or phrase appears again in the same span, the result can be retrieved rather than recomputed.
The session stressed printing and study advice: slide decks are large because they include many references; for the open-book exam take only relevant slides near formulas or specifics that are hard to remember. Smaller printouts help find material faster during the exam, save paper and cost, and reduce search time. That advice matters because chart parsing tables are large — having a compact reference lets you locate the rule list quickly.
Why chart helps: without it, the article "the" occurring twice causes the same analysis to be redone. With a chart, after "the" at position 0-1 is recognized as Article, that fact is stored once and reused. The dot notation means already matched, still needed. This is the same idea as memoization in dynamic programming.
Scope and assumptions: CFG parsing assumes context-free independence: the expansion of does not depend on where appears. That is a simplification; real language has agreement and long-distance dependencies. It also assumes a fixed, given grammar covers the sentence — if a needed rule is missing, no parse is found even though a human would understand. Chart parsing assumes correctness of reuse only when span and label match exactly.
Visual intuition: picture a grid where rows are span lengths and columns are word boundaries 0 to . Cell holds constituents covering words to . Bottom row holds words, next row holds over "The large can", top cell should hold if the sentence is grammatical. Complexity grows as for CKY (later). Takeaway: parsing fills the triangle from short spans upward; the chart is that triangle.
16.2.4 Worked Example — Bottom-Up Chart Parsing
Worked example — bottom-up chart parsing for "The large can can hold the water" with rule
This sentence is chosen because "can" is ambiguous: it can be noun, auxiliary, or verb. That ambiguity makes it ideal for showing rule selection and why chart reuse must be conditional.
Procedure when a parsing question appears:
- First, number the positions between words, either starting at 0 or 1; the convention does not matter as long as every word is covered from its left to right position. For six words, use 0-1-2-3-4-5-6.
- Process the sentence left to right through the chart algorithm to the end, storing results at each span.
Step walkthrough for the first three words ("The large can"):
- Word 1 "the" at span 0-1 carries POS tag Article. Applicable rules beginning with Article are selected; there are typically two such rules in the given set, both kept as possibilities at this stage (for example, and ). Both are entered as dotted items: and .
- Word 2 "large" at span 1-2 is Adjective. Of the retained possibilities, only the rule that expects Adjective next continues; the other (expecting Noun immediately) is discarded for this path. So remains active, the other is pruned.
- Word 3 "can" at span 2-3: here ambiguity appears. "can" can be noun, auxiliary, or verb. No rule in the given grammar starts with Noun at this dot position? Actually the active dotted rule expects Noun, so Noun is possible here. The auxiliary and verb readings are also possible but not via this rule; they would be considered under a rule starting with Aux or Verb. So for this completion, we take "can" as Noun. The rule is now finishable: the sequence Article + Adjective + Noun is satisfied, spanning 0-3, yielding the first completed constituent covering "The large can". The chart stores . That is the rule name explicitly required by the manifest: .
Next "can" (second occurrence) after the first NP is complete:
- Sentence structure is known to be . Since is done, the next phase is spanning 3-6. For this second "can" at span 3-4, the noun reading no longer has a rule beginning with Noun in the context, so only auxiliary and verb rules remain; they belong to the portion. The distinction between and parts guides which rules are tried. Choosing Aux yields possibilities, choosing Verb yields , and the parse continues with "hold" and "the water". The exam will give the sentence, the set of rules, and the POS tags; the task is to apply those rules systematically using bottom-up chart parsing to build the tree and state which span each constituent covers.
Chart representation detail:
- After a constituent such as Article at 0-1 is processed, a dot-marked item is stored: at span 0-1, meaning Article done, still need Adjective and Noun.
- If the word "the" appears again at span 4-5 for "the water", the stored result that Article spans a length-1 interval can be reused: you know immediately that 4-5 can be Article without re-deriving POS.
Numeration check: With start 0, "The large can can hold the water" tokens map to boundaries: The(0-1) large(1-2) can(2-3) can(3-4) hold(4-5) the(5-6) water(6-7) if counting seven tokens including second "the". The convention shift (0-based vs 1-based) does not change correctness as long as spans are consistent.
Sense check: The parse finds over words 1-3, then over remainder, so top-level is achievable — the sentence is grammatical under the given grammar despite lexical ambiguity.
The same bottom-up flow applies generally: start at words, propose only rules whose first needed symbol matches the current tag, extend dotted items, complete constituents when dots reach the end, and propagate completions upward. Show a small table in the exam with columns Step, Span, Dotted Rule, Action.
Pitfalls:
- Assuming NP/VP boundaries are given. They are not. You must decide where NP ends and VP starts based on which rule completes. The Q&A below reinforces this.
- Reusing a chart entry blindly. Just because "can" was Noun at span 2-3 does not mean the next "can" at 3-4 is Noun. The exam deliberately includes such ambiguity to test conditional reuse.
- Forgetting to try all POS readings. If a word has three tags, all three must be considered where grammatically applicable. Dropping one discards valid parses.
- Not numbering spans. Without explicit span indices, it is hard to score partial credit. Always write span numbers.
16.2.5 Student Questions and Answers — Chart Memory
Q: Will it be given in the exam where the NP phrase ends and where the VP phrase starts? [16.2.qna.1]
A: No. You must decide based on the rules provided. The sentence, the rules, and the POS tags will be given. Apply the rules and perform bottom-up chart parsing accordingly. Every sentence may typically follow , though some grammars allow alone; follow whatever rules are given. Your answer should state the span where you completed and where you started , and justify via the rule that fired.
Q: In chart parsing we store the value of previously seen words such as typical verbs, but there could be a scenario where the first instance in a sentence is a verb and the next instance is a noun. If we retrieve the stored verb reading, isn't that a problem? Should we avoid chart parsing then? [16.2.qna.2] [Teaching moment 16.2.moment.1 — chart stores partial results, dot marks reusable memory]
A: You only reuse a stored chart entry if it is applicable in the current context. If a word like "can" can be verb in one place and noun in another, only the rule that fits the current grammatical context is used — specifically, only if the dotted rule expects that category at that span and the POS tag matches. Otherwise all rules that are applicable to the word in its current position must be explored at runtime. The decision cannot be fixed in advance because some words are closed-class and easy to preprocess, but ambiguous words require runtime exploration. Chart parsing still helps because you can check memory and reuse when the preprocessing condition is satisfied (same word, same tag, same span length); when not, you explore all applicable rules. So the chart is an optimization, not a constraint to reuse blindly. This is why the chart stores both the word and its tag, not just the word form.
A useful cross-link retained for later: stack, buffer, and arcs in dependency parsing (16.4) have analogous bookkeeping roles to the chart in constituency parsing: they keep state that allows reuse or transition. The difference is that chart stores completed constituents by span, while stack/buffer store incremental dependency state.
Recap and bridge: Language is highly ambiguous — one sentence can have 132 readings — and CFG rules plus POS tags make relations testable. Top-down predicts, bottom-up builds, chart memoizes. The worked sentence "The large can can hold the water" shows how fires for the first three words while the second "can" must be Aux/Verb for the VP. Next, Statistical Parsing (16.3) adds probabilities to choose among the many trees that survive the grammar.
16.3 Statistical Parsing, PCFG, CKY and Parser Evaluation
16.3.1 Statistical Parsing and PCFG Intuition
Hook: Grammar alone says many trees are possible. Which tree did the author intend? Look at the numbers: the tree the community actually uses most often is the best bet.
When multiple parse trees satisfy the same CFG, ambiguity remains unresolved by rules alone. Statistical or probabilistic parsing resolves this by attaching probability values to each grammar rule. The domain matters: if building a parser for the medical domain, probabilities are estimated from a corpus of medical documents; a news corpus gives different numbers. That is the teaching moment about domain specificity — the same rule may be common in medical records but rare in poetry. [Teaching moment 16.3.moment.1 — medical domain probabilities, corpus domain specificity]
Probabilistic Context-Free Grammar (PCFG) is exactly the same as earlier CFG but with a probability on each rule. Formally, where each carries with for each left-hand side . These probabilities are counts from training data that is labeled with part-of-speech and phrasing; once a treebank is annotated, counting makes probability estimation straightforward for a machine: .
Two additional items stressed: this needs labeled training data (a treebank), and evaluation uses a gold-standard benchmark dataset separate from training.
Why probabilities help: A rule with probability is used far more often than a sibling with . Multiplying rule probabilities along a tree gives the tree's overall plausibility. The tree with highest product wins, so frequent constructions are preferred without changing the grammar.
Real-world placement: PCFG probabilities are domain-specific. A parser trained on Wall Street Journal text may perform poorly on medical notes because rule frequencies change. Retraining on in-domain counts is often required before deployment.
16.3.2 Mathematical Formulation
PCFG probability models:
Let a parse tree be a collection of rules used in that derivation. With the PCFG independence assumption that each rule choice is independent given its left-hand side:
where is the probability associated with rule . So after a complete parse tree is built, multiply the probabilities of all rules used in that tree. Whichever tree has the higher product is selected as the final parse for the sentence in that domain. That is the selection criterion — argmax over trees.
Probability of a sentence generalizes over all trees that yield the sentence. The verbal description was: probability of a sentence is summation of probabilities of parse trees that generate it. Reconciled form:
where means the leaves of spell sentence . A threshold idea follows: if is very low (near zero), the string is judged not a valid English sentence under that grammar; if higher, it is acceptable. So helps assess grammatical legality and can be used for language modeling.
Variables defined: is a parse tree, a hierarchical structure over words; is a rule where is a non-terminal (like S, NP, VP) and is a sequence of terminals or non-terminals; is the sentence string; is a probability in with normalization per left-hand side.
A threshold check uses : pick (e.g., ); if flag as likely ungrammatical.
An example fragment from Jurafsky and Martin was referenced where rules and their probabilities are listed, such as with , with , etc. Given those numbers the computation is not hard — apply probabilities at each step and multiply.
Limiting sanity check: if a rule probability sums to 1 per left-hand side, and a tree uses only high-probability rules, stays relatively large; a tree using a rare rule with gets penalized heavily. For a single-rule tree , , which must lie in .
Worked example — PCFG tree probability and sentence probability
Suppose a tiny grammar relevant to "The dog barks" with probabilities:
- , ,
A tree using all six rules has:
Compute stepwise: ; ; ; ; .
So .
If a second tree uses a rare path with instead of , its product would be six times smaller (), so is chosen. Sentence probability if only these two trees yield the sentence is .
This calculation mirrors the exam task: given a table of rule probabilities, multiply along each tree, sum across trees that yield the sentence, and pick max.
16.3.3 CKY Parsing and Chomsky Normal Form (CNF)
CKY (Cocke-Kasami-Younger) parsing is a bottom-up chart parsing algorithm specialized for PCFG but with a restriction on rule form. It runs in for sentence length , using dynamic programming over spans. The core requirement for CNF is that every rule's right-hand side must have exactly one terminal or exactly two non-terminals:
Chomsky Normal Form prerequisites: Any CFG can be converted to CNF. Steps: (1) eliminate long RHS: for introduce and rewrite as , ; (2) handle unit productions by substitution; (3) replace mixed rules by with . This conversion must happen before applying CKY. The probabilities of new binarized rules are set to 1 or carried from originals so the total tree probability is preserved. CKY itself is otherwise the same idea as bottom-up chart parsing with probabilities. Instead of showing arcs, some presentations show a table (as in Jurafsky and Martin); both are equivalent. CKY can also be adapted for dependency parsing but is more complex and not the popular choice there; graph algorithms and deterministic parsing dominate dependency work.
Concrete CNF conversion example retained for exam: (three symbols) becomes , with a new non-terminal. That two-step replacement is applied wherever a rule has length .
CKY table intuition: cell stores non-terminals that derive substring ... Base cells filled by where is word . Then for span length to , combine splits between and : if and and , add to with probability . The max-probability parse is recovered by back-pointers.
Q: Do we also need to convert to CNF form in the exam if CKY is asked? [16.3.qna.1]
A: Yes. If CYK/CKY parsing is asked, first convert all rules to CNF form using the sub-rules discussed (introducing new symbols to make binarized rules), and only then apply the CKY algorithm. The sample paper includes a similar question where you must show the converted rule set and then the CKY table. Do not apply CKY directly to non-CNF rules. [Manifest expects CNF steps A to w and A to B C]
Scope and assumptions: CKY assumes grammar is in CNF. If you skip conversion, the algorithm misses valid parses. It also assumes independence of rule probabilities (PCFG assumption) which is a strong simplification — real rule choice depends on wider context. Complexity assumes moderate; very large grammars grow slower.
Visual: imagine a triangular table with words along the diagonal. You fill bottom row with POS tags, then grow upward: two bottom cells combine to form a cell above. Landmark is top cell — if it contains , sentence is grammatical and its stored probability is . Takeaway: CKY is chart parsing turned into a filled triangle with max-probability bookkeeping.
Exam note: you may be asked to convert rules to CNF first, then apply CKY to get the parse probability and the tree. Apply probability values at every point where a rule is applied and show the table or arcs.
16.3.4 Evaluation of Parsers — Labelled Precision, Recall and F-Score
Any parser system must be evaluated against a gold standard dataset that contains benchmark parses (the treebank test split). The standard measures are precision and recall, adapted to constituents because a constituent is correct only when both its label (e.g., NP, VP) and its span positions match the gold. Positions matter: even if the rule label is the same, differing positions means not identical — an NP covering words 0-2 is different from an NP covering 1-3.
Labelled evaluation formulas (reconciled):
Verbal description: in precision you compare candidates that match exactly out of total candidate constituents; in recall you compare matching constituents out of total gold constituents. Formalized with label-plus-span matching:
So is the harmonic mean. Constituents are counted only when both label and span are identical; must match exactly, not . Domain check: each metric in ; lies between Precision and Recall.
For the exam, a small numerical problem on this evaluation can appear. Always state matching criterion explicitly.
Worked example — labelled precision, recall, F1
Suppose candidate parse has constituents: → total 4. Gold has: → total 4. Matching (label+span both): → 3 matches. vs do not match due to label and span difference.
Then:
If instead candidate had an extra spurious making total 5 with still 3 matches, Precision , Recall , . The example shown in class contrasted the case where both position and label match (counted) versus label matches but positions differ (not counted) — only label+position identity counts, exactly as computed here.
A second self-check: if candidate invents 2 extra constituents, Precision drops but Recall unchanged; if candidate misses a gold constituent, Recall drops. That matches intuition that Precision penalizes over-generation, Recall penalizes under-generation.
Pitfalls:
- Counting label-only matches. A common error is to count as matching because labels agree — that is counted as mismatch because spans differ.
- Mixing parse probabilities with evaluation. chooses the tree; Precision/Recall judges the chosen tree against gold — do not multiply them together.
- Forgetting harmonic mean. is not arithmetic mean . Use .
- Not stating span convention. Whether you count 0-based or 1-based spans, be consistent and state it.
Recap and bridge: PCFG multiplies rule probabilities to score trees via and sums over trees for . CKY requires CNF ( or ) and builds a triangular table, converting longer rules via new binarizers first. Evaluation uses labelled Precision/Recall/F1 with exact label+span matching. These statistical tools choose the best constituency analysis before downstream dependency and contextual embedding (16.4, 16.5) reinterpret relations with learned weights.
16.4 Dependency Parsing
16.4.1 Foundations — Heads, Roots, Nodes and Rules
Hook: Instead of grouping words into phrases, what if you draw one arrow per word pointing to its boss?
While phrase-structure parsing groups words into phrases, dependency parsing finds direct relations between words. That is its focus: each word chooses one head it depends on, and the set of choices forms a tree.
Key terms:
- Root word: the most important word in the sentence, typically the main verb. Each phrase also has a head/root: a noun phrase has noun as its head, a verb phrase has verb as head.
- Words are treated as nodes (vertices), relations as directed edges (arcs) labeled with relation types such as nsubj, dobj, det, or similar short forms.
- Edge labels are short forms indicating the relation type; you do not need to memorize them — if named relations are asked in arc-eager parsing, those names will be provided.
Rules that a final dependency graph must satisfy to be a well-formed tree (an arborescence rooted at an imaginary ROOT):
- No island nodes: every word must be connected to at least one other node — no isolated word left floating.
- Every word has a single head (single incoming edge). A word cannot have two bosses.
- The root is an imaginary word, not an actual token; every real word may have an incoming edge from ROOT, but ROOT has no incoming edge, and typically exactly one word (the main verb) is a child of ROOT.
- No cycles: following head arrows must eventually reach ROOT without looping.
- Projectivity is often assumed for arc-eager but not for graph-based — the lecture notes that graph-based can handle non-projective cases.
Naming of relations need not be memorized; CKY can be used for dependency but is complex and not popular, so exam will give labels if needed.
Formal view: A dependency tree for sentence is a directed spanning tree where each has exactly one head with edge and label . The tree score under a weighted model is sum of edge scores: . The best tree maximizes this sum — that is the Chu-Liu Edmonds objective.
Real-world placement: dependency parsing is more widely used in industry for relation-centric tasks than constituency, though constituency remains foundational and better suited to grammar-check systems like Grammarly or to machine translation where the grammar of the target language must be followed exactly. The choice depends on application: dependency helps capture meaning via word relations ("who did what to whom"); constituency helps enforce phrasal grammar ("is the noun phrase well-formed?"). Many modern systems learn dependencies implicitly via transformers but still expose explicit dependency APIs where explainability matters.
Scope and assumptions: Dependency assumes one head per word is sufficient — it cannot represent words that truly depend on two heads. It assumes ROOT is unique and that the tree is spanning (covers all words). The arc-eager deterministic strategy assumes decisions can be made greedily left-to-right; errors early can propagate.
Visual: draw words in a line, with ROOT above the verb. Arcs are arrows from head to dependent curving above the line. A valid tree has every word with one incoming arrow, no word isolated, and all arrows eventually trace back to ROOT. A cycle would be two words pointing at each other — a loop above the line that must be broken.
16.4.2 Deterministic Arc-Eager Parsing — Stack, Buffer and Arcs
Deterministic (transition-based) parsing as a walk:
Deterministic parsing uses a fixed set of rules and a definite set of transitions; there is no probability in the parsing step itself, but it requires training data to learn which transition to predict at each step. It is deterministic given an oracle or a trained classifier — the same state yields the same next move.
Core data structures:
- Stack: holds words that have been seen but not yet fully attached. Top of stack is the focus for left-arc comparison.
- Buffer: holds words not yet processed; initially every word of the sentence is in the buffer, stack and arc sets are empty. Front of buffer is the next input word.
- Arcs: the set of dependency edges built so far.
Each configuration consists of a triple plus the transition chosen.
Operations (transitions) are:
- SHIFT: move the first word of the buffer onto the stack; the word is removed from the buffer. Use when the top of stack cannot yet be attached.
- LEFT-ARC (label ): create a left-directed edge where buffer front is head and stack top is dependent: add arc with label ; pop the dependent from the stack (its head is decided, it is done), keep head in buffer. Example: if stack top "He" depends on buffer front "sent", draw and remove "He".
- RIGHT-ARC (label ): create a right-directed edge where stack top is head and buffer front is dependent: add arc with label ; push buffer front onto stack (do not remove head, because a head may govern multiple dependents). Example: "sent" as head for "her" stays on stack to also attach later words.
- REDUCE: pop the top of the stack when its dependents are complete and it has a head already. No new arc.
Memory aid retained from class: right-arc keeps the word on the stack because the head may still govern other words; left-arc removes the dependent from the stack after attachment because its single head is now fixed. [Teaching moment 16.4.moment.1]
Training data creation (oracle): given a gold dependency graph for a sentence, apply LEFT-ARC, RIGHT-ARC, SHIFT and REDUCE in sequence to reproduce the graph; record each configuration as a training tuple of (stack, buffer, arcs) with its gold transition label. This sequence will be given in the exam if arc-eager parsing is asked; the task is to show transitions step by step, either as a table or as a diagram, listing for each step what remains in stack, buffer, and arcs.
For the exam, expect a table with columns Step, Stack, Buffer, Arcs, Transition. Initial state is Stack [], Buffer [w1...wn], Arcs {}. Terminate when Buffer empty and Stack contains only ROOT or is empty depending on variant.
16.4.3 Walkthrough — Arc-Eager Steps
Worked example — Arc-eager trace for "He sent her a letter" style sentence
This walkthrough uses the generic arc-eager steps described in class, matching the manifest example "Arc-eager steps stack buffer arcs shift left-arc right-arc He sent".
- Initially: stack [], buffer [He, sent, her, ...], arcs {}. The ROOT is conceptually present but not always pushed; MaltParser variant keeps stack empty at start, ROOT considered implicitly.
- Step 1 — SHIFT. Move "He" from buffer to stack: stack [He], buffer [sent, her, ...], arcs {}. Rationale: stack empty, cannot left-arc, must shift.
- Step 2 — LEFT-ARC (nsubj). Compare stack top "He" and buffer front "sent". Gold says "He" is dependent of "sent". Apply LEFT-ARC with label nsubj: add arc sent → He, pop "He" from stack. Result: stack [], buffer [sent, her, ...], arcs {sent→He}. Note dependent removed, head "sent" stays in buffer.
Why kept versus removed: RIGHT-ARC does not remove the head from the stack because a head can govern multiple dependents; LEFT-ARC removes the dependent because its head is already decided. This distinction was emphasized.
- Step 3 — SHIFT. Because stack empty after the left-arc, next operation is SHIFT: move "sent" from buffer to stack. Result: stack [sent], buffer [her, ...], arcs {sent→He}. Now "sent" is ready to be head for remaining words.
- Step 4 — RIGHT-ARC (dobj/iobj). Compare "sent" (stack top) and "her" (buffer front). Suppose gold says "her" depends on "sent". Apply RIGHT-ARC: add arc sent → her, push "her" onto stack while keeping "sent". Result: stack [sent, her], buffer [...], arcs {sent→He, sent→her}. "sent" remains to govern further dependents like "letter".
- Continue through all words, building shift/left-arc/right-arc/reduce steps until buffer empty and a complete dependency graph is formed. Each configuration records the state after the operation. Final state may apply REDUCE to pop dependents whose subtree is complete, ending with stack [sent] or [ROOT, sent] and buffer [].
Exam note: you may be asked to produce the transition sequence and the stack-buffer-arcs table for each configuration. Always show stack bottom-to-top, buffer front-to-back, and list arcs as head→dependent.
A second tiny trace check (edge cover): for two-word sentence "John sleeps": Start []|[John sleeps]|{} → SHIFT [John]|[sleeps]|{} → LEFT-ARC(sleeps→John)? Actually if "John" is nsubj of "sleeps", with buffer front "sleeps" and stack top "John", left-arc adds sleeps→John, stack []|[sleeps]|{sleeps→John} → SHIFT [sleeps]|[]|{...} → done. That covers single-head and no-island rules.
Student exchange during walkthrough confirmed: after shift, the stack gains the first buffer word and the buffer loses it; after left-arc the dependent leaves the stack and arcs grow; after right-arc the dependent is pushed but the head remains — these are the invariants to keep.
Q: When will dependency parsing be used by the machine and in which phase and how is it used internally? [16.4.qna.1]
A: Dependency parsing finds relations among words. In any NLP application where relations matter — conversational AI, information extraction, question answering — dependency relations are useful. Today transformers capture relations implicitly via attention, but dependency ideas are still used implicitly in many real-world applications to find word relations, especially where explainability or structure is needed. Graph-based dependency and neural dependency implementations are chosen in practice over direct use of the textbook arc-eager table, but the underlying idea remains identical. For the course, the arc-eager table creation serves as training data for a machine learning model that will then predict transitions on new test sentences similar to the training ones. Internally, parsing happens after tokenization and POS tagging and before semantic interpretation — it is the structural phase that feeds meaning extraction.
Q: We don't usually add root in the stack, but root will be present all the time? [16.4.qna.2]
A: Yes, root is always present conceptually. Some presentations (Jurafsky and Martin) show examples with ROOT explicitly on stack, where transitions happen from ROOT to dependents. There are multiple variations of arc-eager parsing; the version studied here follows the MaltParser style where stack starts empty, but other variations include explicit ROOT on the stack from step 0. Either is acceptable if you state your variant — the exam will accept consistent use of one variant as long as invariants (single head, no islands) hold.
16.4.4 From Transitions to a Classifier — Feature Learning
Creating the gold transition sequence alone does not make a parser. The purpose is to create training data for a multi-class classifier where each configuration's features predict the gold transition.
Features: part-of-speech tags, word forms, stack/buffer top items, and rule-like contextual clues. A configuration's feature vector encodes, for example, is-stack-empty, POS of stack top, POS of buffer front. Any machine learning or neural classifier, including feedforward networks or transformers used as classifiers, can be trained on these features.
Feature learning boils down to learning weights for each feature. At test time, the input features are multiplied by learned weights to decide which transition to predict — exactly like a 4-way logistic classifier over {SHIFT, LEFT-ARC, RIGHT-ARC, REDUCE}.
Worked example — feature weight learning with 12 dimensions (C0 C1 C2) and scores 6 versus 4.5
Setup from the session: there are four operations (left-arc, right-arc, reduce, shift) and three indicator features (called C0: is stack empty, C1: top-of-stack tag, C2: buffer front tag), so the joint feature map is dimensions — each operation has its own block of three weights. Weights are initialized, for illustration to for most positions except left-arc weights set slightly higher initially. The actual 12-dimensional vector is flattened for visualization; pipes in slides only show the four class blocks, but the stored vector is 12 numbers with a comma separation.
Feature encoding: for SHIFT, only the SHIFT block has non-zero entries (1 where its condition holds, e.g., stack empty =1), others are zero; for LEFT-ARC only the LEFT-ARC block is active, etc. The dot product with the weight vector yields a score per class; the class with maximum score (argmax) is the predicted transition.
Iteration 1 — stack empty = true:
Feature vectors (three per class):
- in SHIFT block, others 0
- in LEFT-ARC block
- similarly for RIGHT-ARC, REDUCE
Weights: suppose , (left-arc slightly higher), others . Scores:
- SHIFT:
- LEFT-ARC: → argmax is LEFT-ARC
- Others similar but 5.
Oracle says SHIFT (since stack empty requires SHIFT — you cannot left-arc without stack element). So predicted = LEFT-ARC, oracle = SHIFT → mismatch.
Weight update rule (perceptron):
where is current weight vector, is feature vector for gold transition, for mistaken prediction. So:
- SHIFT block:
- LEFT-ARC block:
- Others unchanged.
After update, SHIFT weight becomes 6, LEFT-ARC falls to 4.5, shifting argmax toward correct SHIFT on next encounter of same feature pattern. That is the manifest example: feature weight learning 12 dimensions C0 C1 C2 shift versus left-arc 6 and 4.5.
Subsequent iterations repeat: apply updated weights to next configuration (after moving John to stack, stack-empty becomes false, top-of-stack features become active, etc.), predict, and if still wrong, update again. At test time, final learned weights are simply applied to candidate transitions for the new sentence without further updates.
Edge dot product also maps: edge score as gives 12 for Root→John in the class example; same linear idea.
Sense check: if stack empty, only SHIFT is legal in gold data, so model must learn to boost SHIFT weight for that feature — the 6 versus 4.5 achieves that.
Weight update — formal: This is a structured perceptron update. For configuration with oracle and predicted ,
where is the joint feature map. Update only on error captures the manifest rule "Weights updated only in error case" [16.4.qna.3]. At training time, state progression follows oracle, not prediction [16.4.qna.4] — prediction only supplies error signal, while next configuration is reached via the gold transition so the model sees correct history.
Q: Are weights updated only in the error case? [16.4.qna.3]
A: Yes. Only if there is a mismatch between the benchmark/oracle transition and the predicted transition are weights updated. If prediction matches oracle, leave weights unchanged and move to next configuration. This matches perceptron training exactly.
Q: For the next operation, which operation should we do — the predicted left-arc or the oracle shift? [16.4.qna.4]
A: For learning, follow the oracle (benchmark) sequence. The prediction is only used to compute the error for weight update, not to drive the next state during training. So after the mismatch, the state advances via the shift that the oracle says is correct (for example John moves to stack). Weight update just adjusts parameters so that next time the model will prefer shift when stack empty. At test time there is no oracle, so you follow the model's predictions greedily.
A misconception corrected in class: weight update does not mean executing the wrong predicted arc; it means adjusting numbers so that future argmax will favor the oracle. The benchmark transition drives the state progression during training — keep those two roles separate.
Q: How do parsing strategies compare — when would you pick dependency over constituency? [16.4.qna.5 — Parsing grammatical structure versus relations coexist]
A: They coexist and choice depends on application. Dependency for relations — conversational AI, information extraction, open-domain QA where "who did what" matters — is more direct. Constituency for grammar checking (Grammarly-style), sentence compression, or machine translation where target-language phrase grammar must be enforced, is better. Many production pipelines run both or use dependency features from a constituency parse. The exam may ask you to justify a pick based on scenario — state the relation-versus-grammar trade-off and commit to one.
Pitfalls:
- Forgetting to block illegal transitions. LEFT-ARC requires non-empty stack and non-empty buffer; SHIFT requires non-empty buffer; REDUCE requires stack top already has a head. Enforce those guards or you generate invalid trees.
- Confusing LEFT-ARC and RIGHT-ARC head direction. LEFT-ARC: buffer head, stack dependent, pop dependent. RIGHT-ARC: stack head, buffer dependent, push dependent, keep head.
- Updating weights when prediction is correct. That would drift away from correct solution — update only on mismatch.
- Following prediction during training. That feeds the model wrong history and breaks learning; during training always advance via oracle.
16.4.5 Graph-Based Dependency — Chu-Liu Edmonds
Graph-based parsing as maximum arborescence:
The second dependency approach treats words as vertices and relations as weighted directed edges. Goal: find the maximum-weight spanning tree (arborescence) rooted at the imaginary ROOT. Edge weights indicate how likely a head-dependent relation is, learned from training data as described next. Among all possible spanning trees respecting single-head and no-cycle constraints, the one with maximum total edge weight is taken as the correct parse. This is exactly the maximum spanning arborescence problem solved by Chu-Liu Edmonds.
Worked example — Chu-Liu Edmonds greedy selection and cycle contraction (30, 20, WJS 40 versus 29, 31 versus 30)
Procedure:
- Assume to start that there is a directed edge between every pair of words in both directions plus edges from ROOT to each word, but no incoming edges to ROOT (ROOT cannot be dependent). For sentence "John saw Mary" plus ROOT, that is directed edges plus ROOT edges, before pruning.
- Edge weights are known from training (computed via feature weights as described next). Example numbers from class: for one word the incoming edges were weights 10, 20, 0 — keep 20, discard 10 and 0. For another word keep max among its incoming set, similarly for "Mary" among 30, 9, 3 — keep 30 (the manifest anchor 30). That enforces single head.
Step 1 — greedy max incoming per word:
For each word , keep only incoming edge with maximum weight; discard all other incoming edges for that word because every word can have exactly one head. In the "John saw Mary" example, for "saw" the incoming were 10, 20, 0 → keep 20. For "Mary" among 30, 9, 3 → keep 30. This greedy choice is optimal if no cycle appears.
Step 2 — cycle check:
Result after this step is a graph with edges (one per word). If that graph has no cycles, the problem is solved; the greedy choice already forms a valid tree and you stop — the exam's lucky case.
Step 3 — cycle example and contraction:
A directed cycle such as John → saw → John (weights creating a loop) would violate tree property and must be repaired. The class cycle was contracted:
- Contract the entire cycle into a single combined node (named WJS for John+Saw). Treat words in the cycle as one entity for edge-weight recombination.
- Recompute incoming edge weights to this combined node by summing: an edge into the cycle from outside now represents choosing one entry point into the cycle plus the internal best edge of the cycle that must be kept to retain strong internal structure. So totals like (incoming to John via Saw) and (ROOT→John→saw path weight) are compared; 40 is kept as larger, 29 discarded. Similarly recompute from the other side: versus ; keep 31. Now among edges incoming to the contracted node, only one may remain because a tree allows single head per node; so between 40 and 31, keep 40, discard 31? In the session's numbers the final retained incoming to the combined node was 40, with the manifest note that a shown 9 on the slide was an error and should not be there.
- Once a single incoming edge to the combined node is selected and no cycle remains, expand the contracted node back: restore original internal structure, keeping the internal edge that corresponded to the chosen combined entry (the 40 entry corresponds to specific original internal edges, dropping the cycle-breaking edge). That yields the final dependency tree without cycles, maximizing total weight.
Exam note: you can expect a mathematical problem: given a sentence with edge weights, compute the parse tree using Chu-Liu Edmonds. If lucky, there will be no cycles and greedy selection already gives the answer. If a cycle exists, apply contraction and recombination steps described; show intermediate graphs and which edges are kept/discarded at each stage.
Domain check: total tree weight is sum of kept edges. If greedy without cycle gave weights 20+30=50, after contraction total is recomputed but still sum of final tree edges — that sum is maximal among all possible trees.
Visual for this example: initially many faint edges between every pair. After greedy, only one dark incoming per word remains — a clean set of arrows. If two arrows form a loop, circle that loop, collapse it to one big node WJS, redraw outside edges to that big node with adjusted weights (original plus best internal edge), pick best, then expand.
16.4.6 Learning Edge Weights
How are edge weights obtained? Same linear scoring idea as transition parsing:
Setup:
- Features F1 through F7 are defined, typically based on POS patterns and positional indicators (for example, F1: first word is ROOT and second word is noun, F2: first word is verb, F3: word at end of sentence, F4: word occurs before word , etc.). The exact feature definitions will be given in the problem.
- Each feature has an initial weight (for example, given as random small numbers). There are seven features, each with a scalar weight; the weight vector length matches feature count.
To compute the weight (score) of a directed edge :
where (or real-valued) is the feature vector for that ordered pair and is the weight vector. Dot product is sum over features: .
Worked example — edge weight computed as feature vector dot weight vector, ROOT→John score 12
For edge ROOT → John, with known tags John=Noun, saw=Verb, Mary=Noun, and a specific feature set F1..F7 where F1 checks "first word is ROOT and second word is John (noun)" etc.:
- Check each feature for this pair and position relative to sentence boundaries. For ROOT→John, F1 (ROOT→Noun at position 1) is satisfied → 1. F2 (Verb→something) fails → 0. Similarly each of the seven features is checked, yielding a binary feature vector such as (illustrative; exam will give the rule for each F).
- Dot product with weight vector (example numbers) gives:
That matches the stated edge score 12 for that pair in the session. Repeating for every ordered pair (including both directions and plus ROOT to each word) yields the full matrix of edge weights, which is then fed to Chu-Liu Edmonds.
If after applying Chu-Liu Edmonds the predicted tree exactly matches the training gold tree, initial weights are judged correct. If not, weights are updated using the same perceptron idea at graph level: , where sums feature vectors over all edges in the tree (complete graph-level analog of earlier per-transition update). No numerical weight-update problem is expected for the edge-weight case in the exam beyond calculating edge scores from given feature vectors and weight vectors and understanding how features are mapped, but you should be able to explain the update rule.
Exam note: expect problems on graph-based parsing for one of: tree construction with given edge weights, or edge-weight calculation from features with , or one iteration of weight recomputation. Show work in tables where required, and always state feature definitions as given.
Pitfalls:
- Forgetting ROOT has no incoming edges. Including an incoming edge to ROOT breaks the arborescence.
- Keeping two incoming edges for one word. That violates single-head — keep only max.
- Not expanding the contracted cycle correctly. On expansion, keep the internal edge that was part of the winning combined entry, break the cycle at the other edge.
- Mixing transition-based and graph-based weight updates. They use different — per-configuration versus per-tree sums.
Recap and bridge: Dependency offers two algorithmic families for the same linguistic goal. Transition-based (arc-eager) walks left-to-right with stack/buffer and learns a classifier over 12-dimensional (4×3) transition features (shift 6 versus left-arc 4.5 after update). Graph-based scores every directed edge as (ROOT→John 12) and finds the maximum arborescence via Chu-Liu Edmonds, greedily keeping max incoming (30, 20) and contracting cycles (WJS 40 versus 29, 31 versus 30) when needed. Both rely on learned weights, but differ in search strategy. Next, Contextual Embeddings (16.5) replace hand-crafted dependency features with learned self-attention that captures relations implicitly.
16.5 Contextual Word Embedding and Attention
16.5.1 Motivation — From RNN to Attention
Hook: Recurrent models read a sentence word by word like a person with a tiny notepad — by the end, early words have faded. How do you let every word talk to every other word directly?
Early sequence models progressed from RNN to LSTM to encoder-decoder. The encoder converts input into a hidden representation; the decoder generates output token by token. A known limitation is vanishing or diminishing gradients: during back-propagation through many time steps, gradients shrink toward zero, so early-layer weights move close to zero and key features are effectively ignored. That means some words in the sentence are ignored when deciding an output such as translation — the model "forgets" the beginning by the time it reaches the end.
Attention was introduced to capture relations among input words explicitly without relying solely on recurrent compression. Rather than compressing the whole sentence into one vector, attention computes vector similarity between words and uses those similarities to decide importance for each position.
Intuition — the spotlight: Think of each word holding a flashlight. To understand word , it shines its light on every word and measures how brightly reflects back (similarity). Words that shine back bright get more of the spotlight when building the new representation for . The spotlight settings for "bank" differ when neighbors are "river" versus "investment", so the same word receives different light depending on context. Where analogy breaks: real attention is not a single brightness but a weighted blend of value vectors, not just an on/off spotlight.
Normalization idea: similarity scores must be turned into proportions that sum to one, so the model can select among options in a calibrated way. Softmax does that: it exponentiates scores and normalizes to a probability distribution. If there are 10 options, normalizing ensures probabilities add to one and the most relevant option can be chosen. The same idea applies when deciding how much one word pays attention to others — the attention weights sum to 1 across for each . [Teaching moment 16.5.moment.1 — softmax normalizes similarities to probabilities summing to one]
Real-world consequence of vanishing gradients: in a long clinical note, the diagnosis at the start may be lost by the end of an RNN. Attention fixes this by letting the last word attend directly to the first, with path length 1 instead of steps.
Scope and assumptions: Attention assumes vector similarity captures linguistic relatedness — that assumption is learned, not guaranteed, and is why training on large data is required. Scaled dot-product assumes dimensions are moderate; without scaling by scores blow up in high dimensions and softmax saturates.
Visual: picture a matrix where row is the query word and column is the key word; cell brightness is . Row sums are 1. For "I ate mango", row for "mango" may shine brightly on "ate" (verb-object) and on itself, dimly on "I". Takeaway: attention matrix shows which words each word listens to.
16.5.2 Self-Attention vs Cross-Attention
Two places attention is used:
- Self-attention finds relations among words within the same input (the encoder side). The similarity is computed among input words themselves: from input, from input, from input. This is the mechanism for contextual word embedding.
- Cross-attention finds relations between input (encoder) and output (decoder) words. In that case the query comes from the decoder (what the decoder is about to generate), while keys and values come from the encoder (the source sentence). Example: when generating French "pomme" from English "apple", cross-attention lets the decoder query over encoder words to find "apple".
For contextual word embedding, only self-attention (encoder side) matters. Contextual embedding generates a new vector for each input word that depends on its context words; it does not generate output tokens, so cross-attention is not needed. In a full transformer, both self-attention (inside encoder and inside decoder) and cross-attention (decoder attending to encoder) are present. Exam focus is self-attention and how it yields contextual embeddings.
Exam note: six marks can be expected on contextual word embedding, mostly as a mathematical problem on self-attention plus some conceptual or application-level questions. Residual connections and layer normalization inside the encoder block are less important for this course; self-attention computation is the core to master.
Why this split matters: if you are only embedding a sentence to obtain vectors for classification or search, you need self-attention alone. If you are translating, you need cross-attention to align source and target. The test will ask you to state which is used when and why contextual embedding excludes cross-attention.
16.5.3 Mathematical Formulation — Query, Key, Value
Formalize — QKV construction and scaled dot-product attention:
For each token, input vectors are first available (from earlier embedding lookup, for example GloVe or learned embeddings). Define:
- is the input vector for word (dimension ), integer dimension such as .
- , , are learned matrices for query, key, value respectively, where is key/query dimension and is value dimension (often for heads).
The verbal description in class: multiply input vectors by matrices to get query, key, value vectors because in higher dimensions relations are easier to capture after linear projection. Reconciled forms:
So each word yields a query vector , a key vector , and a value vector . Terminology: the query is the word being compared ("what am I looking for"), keys are the words it is compared against ("what do you offer"), and values carry the information to be aggregated ("what you contribute if you match").
Shapes: if is and is , then is . Same for . This shape agreement is required for the dot product to be valid.
Attention scores are computed as scaled dot products. The spoken rule was: take vector similarity (dot product), normalize by sizes so scores do not shoot up, and use softmax:
Because of softmax, and each acts as a probability or importance weight: larger means word is more important for deciding word 's new representation. Scaling by prevents dot products from growing large in magnitude when is large, which would push softmax into saturated tails with tiny gradients.
Contextual vector for word is then weighted sum of value vectors:
This is the contextual word embedding for word . It fuses information from all words weighted by relevance — a blend of the whole sentence tuned to position . For the whole sentence, stacking gives where are matrices stacking .
Worked example — self-attention with three words "I ate mango"
Treat dimension , for hand computation. Suppose after lookup:
- for "I"
- for "ate"
- for "mango"
Learned matrices (toy values): , similarly with small integers for illustration.
Step 1 — compute Q, K, V.
- . Compute: .
- Similarly , ; for brevity , , , , (pattern: each Q/K/V derived via same projection).
Step 2 — scores for word 1 ("I") as query.
Step 3 — softmax to get . Exponentiate: , each. Sum .
Check: (rounding).
Step 4 — weighted sum to get . . With :
- First component:
- Second:
So . This is the contextual embedding for "I" — dominated by but mixed with others.
Repeat with comparing against all keys to get for "ate", and with to get for "mango". Each word thus receives a distinct contextual vector even though the same word type elsewhere would start from same but obtain different due to different neighbors.
Sense check: rows sum to 1, all in . If all scores equal, would be each and would be mean of values. Here diagonal dominates, so self-information is strongest, which matches expectation that a word retains its own meaning while blending context.
Matrix form check: divided by then row-softmax then times yields — shapes line up: words, .
This calculation pattern is exactly what the six-mark exam problem will test: given and matrices or given directly, compute , scaled scores, softmax, and weighted sum. Show every step.
16.5.4 Multi-Head Attention
The above describes single-head attention. Multi-head attention uses multiple separate sets of matrices — that is, multiple attention heads, often or . Each head can focus on a different linguistic aspect: one head might focus on part-of-speech patterns, another on phrase structure, another on dependency relations such as subject-verb. The example mentioned in class from a university study showed each attention head capturing a different type of relation when visualized — one head's matrix lit up noun-modifier pairs, another lit up verb-object.
Combining heads yields richer representation than a single head. Conceptually, if you have heads, you get different and they are concatenated then projected:
where mixes heads back to dimension . The benefit is specialization: different heads learn different so they attend to different patterns, and the concat lets the model combine those views.
Why not just one bigger head? Multiple heads with smaller allow diverse representations without blowing up computation, and each head can learn a distinct similarity metric rather than averaging into one.
16.5.5 Positional Encoding and Masking
Independent of attention scores, word order matters: "I eat mango" is not the same as "mango eat I" — attention alone is permutation-invariant (swapping words permutes rows but not values), so order must be injected. Positional encoding captures that order. Instead of relying on recurrence, a fixed or learned positional signal is added to the word vector:
Sometimes written as:
The method for computing (for example sine and cosine functions of position and dimension: , ) need not be memorized; only the fact that it is added to the original contextual embedding to retain order information is important. Values from the positional encoding are summed with the attention-derived vectors elementwise before feeding to the encoder block.
Future masking: in self-attention for generation (decoder), only current and previous words are visible; future words are masked by setting their scores to before softmax so becomes 0 for future positions. This prevents cheating by looking ahead. This detail was noted as for understanding only; the exam's mathematical question will focus on self-attention contextual embedding steps described above, not on masking details inside full transformers.
Encoder block also contains residual connections () and layer normalization and feed-forward sublayers that produce probabilistic values, but those are not exam-critical beyond recognizing their presence: they stabilize training and add non-linearity after attention.
Scope and assumptions: Self-attention cost is — quadratic in sequence length — so it assumes fits in memory (practical limit is context length such as 512 or 8192). Positional encoding assumes addition does not destroy embedding information; learned encodings can be tuned to balance content versus position.
Visual: picture a stack of encoder blocks: input at bottom → add PE → self-attention (with and softmax) → add & norm → feed-forward → output at top. Each block refines ; stacking 6 or 12 blocks builds deep contextualization.
16.5.6 Significance
The biggest advantage of contextual embedding over static embeddings (such as GloVe, Skip-Gram, CBOW studied pre-midterm) is that the same surface word receives different vectors depending on context words, because attention weights change with surrounding words. Static embeddings give one vector per word type irrespective of context: the word "bank" gets one point in space. Contextual gives every occurrence its own point — "river bank" and "bank account" are far apart in space despite sharing a string.
A concrete consequence: a classifier that uses static vectors must struggle with polysemy, while one that uses can separate senses linearly because context has already disambiguated. That is why contextual vectors remain the standard even in modern agentic AI scenarios where inputs are converted to vectors via contextual embedding before tool use.
Recap and bridge: From RNN vanishing gradients to attention's spotlight: , scaled score , softmax to summing to 1, weighted sum . The three-word example gave after softmax . Multi-head concatenates diverse heads, positional encoding adds order via . This contextual foundation enables Word Sense Disambiguation (16.6) where "bank" senses are now separable, and grounds RAG retrieval where queries and chunks are embedded with the same contextual mechanism.
Real-world: transformers and their attention mechanism dominate current NLP, and vector similarity with normalization via softmax is a recurring technique in industry systems at web scale — from search ranking to retrieval-augmented generation. The same scaled-dot product appears in rerankers and dense retrievers.
16.6 Word Sense Disambiguation, WordNet and Knowledge Graphs
16.6.1 What Word Sense Covers
Hook: How does a search engine know you meant the river "bank" not the money "bank" when you typed "bank nearby"?
Word sense is the exact meaning intended for a polysemous word in context (for example "bank" as river bank versus financial institution, or "bass" as fish versus musical instrument). Word Sense Disambiguation (WSD) is the task of choosing the correct sense for each occurrence in running text; the system must output a sense identifier rather than just a POS tag.
WordNet is a manually created lexical graph that records relations among words: hypernymy (more general — "canine" is hypernym of "dog"), hyponymy (more specific — "dog" is hyponym of "animal"), synonymy (words sharing a synset), meronymy (part-of), and others. WordNet groups word forms into synsets (sets of synonyms) and links synsets via these relations, forming a navigable graph of meaning. These relations support disambiguation as features — if candidate sense shares hypernyms with surrounding words, it gains evidence.
Two task settings, and what they require:
- Lexical sample task: disambiguate a specific small set of target words (for example only "bank", "bass", "plant"). You collect data and train a classifier focused on those words. This is the industry-common setting where only certain words matter for an application such as product name resolution.
- All-words task: disambiguate every content word in a running text. This needs fully sense-annotated training data where each word carries both part-of-speech and WordNet sense tag — essentially a sense-tagged corpus where a sentence might be written as "bass" meaning noun, sense 2 (fish). That labeled data can then train any classifier where each sense is a different class; at test time every word is classified. The data cost is high, which is why lexical sample is more common.
Training data illustration: a sense-tagged sentence where every word is marked with superscript indicating the exact WordNet sense and subscript indicating part-of-speech, for example "The bass swam..." That annotation allows counting co-occurrences for supervised learning.
Worked example — how WordNet relations create features
Consider target word "bass" with two WordNet senses:
- s1: "bass" as fish (synset {bass, freshwater fish}, hypernym "fish")
- s2: "bass" as musical instrument/low tone (synset {bass, guitar}, hypernym "instrument")
Sentence: "He played the bass guitar". Context words are "played", "guitar". Feature extraction checks overlap with WordNet neighborhoods:
- For s1, gloss words include "fish, water, lake" — overlap with context is 0.
- For s2, gloss includes "instrument, music, guitar, played" — overlap with context is 2 ("played", "guitar").
A classifier would therefore prefer s2 because its graph neighbors intersect context. The same idea works with hypernym paths: "guitar" and s2 share hypernym "instrument", while s1 does not. That is how WordNet edges become numeric features without leaving the lecture's scope.
Why WordNet still matters in the neural era: even with contextual embeddings, WordNet provides curated, interpretable links that are useful for low-resource domains and for building ontologies where you need explicit relation names, not just vector closeness. It also supplies glosses for the Lesk algorithm next.
Scope and assumptions: WSD assumes sense inventory is fixed and known (WordNet's inventory). If language evolves and a new sense appears, WordNet must be updated. It also assumes sense tags in training data are reliable — human annotation error adds noise. The all-words setting assumes every word has a WordNet entry, which is not true for proper names or novel compounds.
Visual: imagine WordNet as a subway map. Synsets are stations, hypernym links are north-bound lines toward generality, hyponym links go south toward specificity. "Bass" appears at two stations on different lines; context words "fish" and "guitar" light up nearby stations. The brighter path picks the correct station.
16.6.2 Supervised Learning and Lesk
Supervised approach — senses as classes:
If labeled corpus plus features (surrounding words, POS, collocations) are available, treat each sense as a class and train a classifier. At training, each occurrence of "bass" with surrounding window and true sense yields a training pair . At test, given a new occurrence with window , predict . Any classifier is possible, but Naive Bayes is most popular and illustrative and matches material taught in machine learning courses, because it factorizes as product over context words.
Naive Bayes recap for WSD: with context words and sense ,
Choose sense maximizing this product. Counts come from sense-tagged data; is sense prior. The independence assumption is that context words are independent given sense — a simplification that still works well for bag-of-words features.
Worked example — Naive Bayes for "bass" fish versus music
Training counts from a toy corpus (smoothed with Laplace +1 to avoid zero):
Priors: .
Likelihoods:
- ,
- ,
- ,
- ,
Test sentence: "played guitar lake" as context.
Scores:
- For music:
- For fish:
Music score about 13 times larger, so predict music sense. If context were "lake fish water", fish likelihoods would dominate and fish sense would win. This is the calculation the exam expects for a small Naive Bayes table — multiply priors and likelihoods, compare, pick max.
For "bass" specifically, the session noted fish sense versus music/guitar sense distinguished via Naive Bayes using surrounding word features — exactly the table above, where "guitar" and "played" lift music, "lake" lifts fish.
Lesk algorithm: a simple yet powerful unsupervised method that requires no labeled training data, only WordNet glosses. It uses word overlap between the test sentence and the dictionary gloss (definition plus example sentences) for each sense. Count how many words overlap; the sense with highest overlap wins. Variants exist, but core Lesk is count intersection.
Lesk — formal: Let be the set of words in the definition and examples for sense , after stop-word removal and lower-casing. Let be the set of context words in the sentence (excluding target word). Define
Predicted sense . Tie broken by sense frequency or first sense. Extended Lesk augments gloss with related synsets' glosses (hypernyms etc.) before intersecting.
Variants: advanced Lesk uses vectors instead of string overlap: compute embedding similarity between words in test sentence and words in the gloss corpus, again maximizing overlap but in embedding space. Simple string Lesk already works well enough that more complex machinery is often unnecessary — a pedagogical point made that problems need not always require heavy methods; try the simple baseline before adding complexity.
Worked example — Lesk overlap for "bass" in "I caught a bass near the river bank"
Two senses with trimmed glosses:
- s1 fish: Gloss = {fish, freshwater, lake, river, catch, water, species}
- s2 music: Gloss = {instrument, music, low, tone, guitar, played, sound}
Context from sentence (lowercased, without stopwords and target): {caught, near, river, bank}
Scores:
- (plus "catch/ caught" morphological variants not counted without stemming — shows the same stemming point as ROUGE)
Predict s1 (fish). If sentence were "played bass guitar", context {played, guitar} yields s2 score 2 versus 0, so predict music. Extended Lesk would add hypernym gloss "fish is an animal living in water" etc., increasing fish overlap further.
Exam expectation: you will not be asked to do heavy math here beyond perhaps a Naive Bayes classification as above or a small Lesk overlap calculation where the sentence to disambiguate, target word, and gloss corpora are given, and you count intersection to decide the correct sense. Show overlap sets explicitly.
Comparison — supervised versus Lesk:
| Dimension | Supervised (Naive Bayes) | Lesk (overlap) |
|---|---|---|
| Data | needs sense-tagged corpus | needs only WordNet glosses |
| Accuracy when data rich | higher, can learn domain bias | lower, but no training |
| Domain adaptation | retrain on domain data | expand gloss with domain text |
| Cost | annotation heavy | cheap, baseline |
| When to pick | lexical sample with labeled data | all-words or cold start, or as strong baseline |
One-line guide: if you have labeled examples for that word, train Naive Bayes; if not, run Lesk and consider vector-extended Lesk for paraphrase tolerance.
Pitfalls:
- Ignoring sense prior. Predicting without can flip a close case; always include prior if given.
- Not smoothing zero counts. A context word unseen with a sense gives and kills the product — add-one smoothing avoids this.
- Counting without normalization in Lesk. Glosses differ in length; longer glosses have higher chance overlap. Extended Lesk relatives normalize or use gloss length correction — mention if asked.
- Forgetting stop-word removal. Counting "the" in overlap inflates scores meaningless.
16.6.3 Semantic Web, Ontology and Knowledge Graphs
From lexicon to world knowledge:
Ontology and knowledge graph organize world knowledge as entities, classes, and relations, going beyond word senses to facts about the world. Components: given a domain dataset, decide (1) entities (instances such as "Radha", "Bicycle"), (2) classes/concepts (such as "Student", "Vehicle"), (3) relation types/properties (such as "enrolledIn", "manufacturedBy"), then express them as a graph where nodes are entities/classes and edges are relations. That choice of what to model is the ontology design step.
Languages:
- RDF (Resource Description Framework) expresses facts as triples subject-predicate-object, for example (Radha, enrolledIn, NLP_Course) or (Bicycle, hasWheel, Wheel). Each triple is one edge in the graph. RDF Schema adds class hierarchy.
- OWL (Web Ontology Language) adds richer modeling: class restrictions, cardinality, disjointness, equivalence, reasoning (for example "every Student is a Person", "a Bicycle has exactly two Wheels", inference that if A is Student and Student subclass of Person then A is Person). Know the difference and when each is used: RDF for simple facts, OWL when you need constraints and automatic reasoning.
Task types the exam retains: given a scenario, build an RDF file (list triples); build an OWL file (add class axioms); describe components of any ontology or knowledge graph; describe how an ontology might be used for a particular application; state what a knowledge graph is and its applications.
Connections made in class:
- Knowledge graphs are used far beyond one retrieval method: Google's knowledge graph powers web search, enriching queries with entities without exposing user data. Agent frameworks access web APIs and search results internally via similar graph-backed knowledge — the agent's tool call is routed through an entity graph.
- In modern agent AI, ontologies and knowledge graphs help ground agents and prevent undesired autonomous actions, contributing to safe behavior even on the path toward more general intelligence. Example: an agent asked to "book the cheapest flight" can be constrained by an ontology that defines allowed airlines, budget limits, and booking rules, so it cannot book outside policy. This is why ontology remains relevant despite neural dominance — it supplies hard guardrails where vectors supply soft similarity.
- Graph-based retrieval (Graph RAG, covered in 16.7) stores data as a graph rather than plain vectors, suitable for domains like medical and finance where relations must be precise (drug-interacts-with-disease). Normal (naive) RAG stores vectors, Graph RAG stores nodes and edges.
Worked example — RDF/OWL for a campus domain
Domain: university courses.
Triples (RDF):
- (NLP_Course, rdf:type, Course)
- (Prof_Anil, teaches, NLP_Course)
- (Radha, enrolledIn, NLP_Course)
- (Radha, rdf:type, Student)
OWL axioms added:
Student rdfs:subClassOf Personteaches rdfs:domain Professor,rdfs:range CourseenrolledIn rdf:type owl:ObjectPropertywith cardinality: Student enrolledIn at least one Course
Application question: "How would you use this ontology to answer who teaches Radha's courses?" Traverse Radha → enrolledIn → Course → taughtBy → Professor. Explain in words and draw nodes/edges. That narrative plus triple list satisfies exam marking.
Six marks can be expected on word sense disambiguation plus semantic web ontology together, asked as conceptual or application-oriented questions based on algorithms (Lesk, Naive Bayes) or knowledge graph construction. No heavy math beyond the small Naive Bayes or Lesk table.
Pitfalls:
- Mixing RDF triple order. Triple is always subject-predicate-object; swapping gives a different fact.
- Over-modeling in OWL. Adding constraints not supported by data creates unsatisfiable ontology — only add what the scenario requires.
- Confusing WordNet with knowledge graph. WordNet is a lexical graph about words; a domain knowledge graph is about world entities — they are complementary but distinct.
Recap and bridge: Word sense is disambiguated either by supervised classifiers treating senses as classes (Naive Bayes over ) or by unsupervised Lesk overlapping gloss and context (). WordNet supplies the inventory and relations for both. At web scale, those relations generalize to ontologies and knowledge graphs expressed in RDF triples and OWL axioms, which ground agents and power Graph RAG. Next, RAG (16.7) shows how such knowledge is retrieved and augmented at query time without retraining.
16.7 Retrieval Augmented Generation (RAG)
16.7.1 Architecture and Motivation
Hook: Your LLM was trained last year and has never seen your company's new travel policy. How do you answer questions about it today without retraining the whole model?
Retrieval Augmented Generation (RAG) is a semantic search plus generation pattern present in roughly 90 to 95 percent of industry projects today, so understanding it deeply matters beyond the exam.
Why RAG exists — three LLM limits it fixes:
- Cutoff and staleness: training data has a cutoff and can be outdated; new documents after training are unknown.
- Hallucination: output not grounded, the model invents facts without source.
- Provenance: the source of a claim is often unknown — the user cannot verify.
Fine-tuning on domain data is possible and will be taught in the next semester, but RAG is less expensive and very effective. Instead of retraining with new data (costly, slow, risks forgetting), give the model access to an external knowledge base at query time and let it reason over retrieved evidence.
RAG flow end-to-end (know this diagram for the exam):
- Maintain a corpus of documents (knowledge-base documents) from which answers must be grounded. This is private, domain-specific data not exposed to the open web (example: company policy on international travel where professors, assistant professors, and associates have different budgets and travel rules — a policy only 5 pages matter out of 500). An open LLM like general-purpose chat without that corpus would answer incorrectly because it lacks the specific rules.
- Offline: all textual information is encoded as word embeddings (using the same contextual encoder as in 16.5) into vectors; the corpus is chunked, each chunk vector stored in a vector database with its source pointer.
- At query time: the user query is also encoded as a vector.
- Compute vector similarity (cosine or dot product) between query vector and document chunk vectors.
- Retrieve the most relevant chunks (sections/groups of words), apply a similarity threshold (for example cosine ) or top-K cutoff (for example top highest scores), extract only those chunks, augment them to the user's prompt as context, then let the LLM act as an English tutor: reason over the supplied snippets, extract relevant sentences, and produce a grounded answer that cites sources. [Teaching moment 16.7.moment.2 — RAG acts as English tutor extracting snippets to give grounded answer]
- Storage variants: naive RAG stores chunks as flat vectors; Graph RAG stores data as a graph (nodes and relations, as in 16.6); Multimodal RAG handles multiple modalities (text plus tables, images); Agentic RAG involves agents orchestrating retrieval, reasoning, and tool use in loops.
The answer is not random, is up-to-date because the latest policy document chunk is supplied at query time, and includes source grounding so hallucination is reduced. The knowledge base is not exposed to the open web, which also matters for federated contexts where each organization keeps its own corpus private — the same RAG pattern applies in federated learning style privacy, each org's retriever searches only its own store.
One-line contrast: without RAG, LLM answers from parametric memory (weights); with RAG, it answers from parametric memory plus retrieved non-parametric memory (chunks).
The same idea applies in federated contexts where each organization keeps its own corpus private and RAG retrieval is scoped locally — no cross-org data leakage.
Scope and assumptions: RAG assumes the retriever finds the right chunks. If corpus is chunked poorly or embeddings are weak, relevant policy may be missed and generation still hallucinates. It assumes the knowledge base is curated and up-to-date — stale documents produce stale answers. It does not replace fine-tuning when style or task format must be learned deeply; it complements it.
Visual: draw a swim lane with three boxes: Corpus → Vector Store (offline indexing), Query → Embed → Search → Top-K chunks, then Prompt = System + Query + Chunks → LLM → Grounded answer with citations. Arrows show 500 pages in, 5 pages out, then answer out. Landmark: the narrow waist after retrieval is where cost and quality are traded.
16.7.2 Token Cost, Budget and Chunking
Why tokens matter: Real-world systems incur cost per token — paid per prompt and per completion — and hard context limits, so token usage must be planned wisely when augmenting prompts. The whole policy document (for example 500 pages) cannot be appended; only the most relevant few chunks (perhaps 5 pages) should be, bounded by the LLM's maximum context length.
Definitions: a chunk is a contiguous group of words/section into which every document is broken before embedding (for example 512 or 600 tokens). Retrieval returns chunks, not whole documents. Selection uses a threshold cutoff or top-K highest similarity scores; top-K is deterministic count, threshold is quality-driven.
Token budget calculation — the central exam formula:
Every LLM has a maximum context length in tokens — total tokens it can accept in one prompt, paid per token. The prompt consists of system instructions plus user query plus retrieved document tokens. Define:
- be maximum context length in tokens, integer (for example 8192),
- be tokens for system instruction (for example "Using the following context, answer...", about 20 tokens, example "Generate summary in five words" pattern),
- be tokens for the actual user query (for example 100 tokens),
- be tokens available for RAG chunks.
Then
Only this many retrieved tokens can be appended without exceeding the limit. This is the available budget; exceeding it truncates or errors.
If all chunks have a fixed length (example tokens), the maximum number of chunks that can be appended is
The floor is used because even if the division yields 14.98, only 14 whole chunks fit; exceeding the upper limit is not allowed — you cannot send a fraction of a chunk without breaking semantics, and rounding up would overflow context. The lecture stressed this as a warning: floor 14 not ceiling 15 is the upper limit. [Teaching moment 16.7.moment.1]
Worked example — token budget, max chunks 14 from 7672 over 512
Concrete numbers from the session: suppose , , , so
Chunk size , so
So at most 14 chunks can be added; three example chunks shown in class (total ) fit well within that budget, leaving room. If you mistakenly used ceiling, you would claim 15 chunks tokens, which exceeds 7672 by 8 tokens and would overflow — that is why floor is required.
Self-check with different numbers: if , then , with gives chunks. The same arithmetic pattern is testable.
Variant with variable values: the exam may give you any of and ask for the remaining. Always write the formula, substitute, compute stepwise, state floor, and note assumption that chunks are fixed-size.
Chunk overlap and stride — why overlap helps:
Simply chopping a document into non-overlapping chunks loses continuity between sections and may lose meaning — a sentence split across the boundary is broken, and the retriever may miss it. So overlapping chunks are used: consecutive chunks share some tokens to preserve cross-boundary context. Define:
- be chunk size (for example 600 tokens),
- be overlap size (for example 120 tokens shared between two successive chunks),
- Stride be the number of unique tokens per chunk.
With and ,
Unique tokens per chunk are 480; the other 120 are repeated from prior chunk to maintain continuity.
If a document has length tokens, total number of chunks (with overlap) is approximately
More precisely, also yields 38; the session reported 38 unique chunks for that document length with these parameters. Advanced chunking techniques with variable lengths and semantic boundaries exist and will be studied next semester; here fixed-size chunking suffices, but you should state the approximation and whether you use floor or ceiling for chunk count — the lecture used floor-style division and rounded to 38.
Worked example — chunk overlap stride 480 and 38 chunks
Given :
- Stride
- Approx chunks , so 38 chunks if rounding up to cover whole document, or 37 full strides plus one final partial chunk.
If overlap were 0, chunks would be ; overlap adds about 8 extra chunks but preserves meaning at boundaries — a cost versus quality trade-off the exam may ask you to comment on.
A second check: if , stride , chunks → 22 chunks. Show both formulas and result, and note that last chunk may be shorter.
Scope and assumptions: Fixed-size chunking assumes token count approximates meaning density, which is not true near headings or tables. Overlap assumes redundancy is worth extra storage and search cost. Token budget assumes and estimates are stable — in practice they vary per query, so is recomputed each time.
16.7.3 Latency and Reranking
Retrieval is not free. The user waits while embedding, search, reranking, and generation happen sequentially.
Latency budget:
Total latency if using RAG includes:
- : query embedding time,
- : retrieval/search time to find related chunks (vector search),
- : reranking time (optional strategy that reorders retrieved chunks by a stronger, often cross-encoder, relevance model),
- : generation time by the LLM.
Without RAG, only generation time exists. So total is
This must remain below a user-expected threshold, for example maximum time for first token or total response. Example threshold given was milliseconds total (2.5 seconds).
Reranking trade-off: after retrieving top-K (for example 14), a stronger reranker can reorder them and keep only top few (for example 5) for generation. That improves quality but adds latency. It is therefore conditional on remaining budget.
Worked example — latency 2500 ms and whether reranking fits
Worked latency budgeting numbers from the session: assume budget
and measured components:
- ms
- ms
- ms
Subtotal without rerank ms. Remaining for rerank ms.
If the reranking algorithm needs ms (for 14 chunks through a cross-encoder), it cannot fit — you should skip reranking and return retrieved results as-is, accepting slightly lower precision to meet latency SLA. If reranker needs ms, it fits within 320 ms, so you can rerank and then generate from the top reranked chunks.
Second scenario: if ms, remaining is ms. Any reranker over 100 ms must be skipped. The exam may ask: given numbers, decide whether to rerank or not and justify with subtraction.
Top-K interaction: retrieval may fetch 14 chunks, reranker trims to 5, so generation tokens are rather than , saving generation time as well — a secondary latency benefit.
Latency components can be shown as a stacked bar: embed (thin), retrieval (medium), rerank (optional thin), generation (dominant). Takeaway: generation dominates, so token budget and reranking choices matter for user-perceived delay.
Real-world placement: chunk-level similarity threshold, top-K selection, and reranking are design choices balancing quality versus cost and time. Many production RAG systems set adaptive per query: high similarity → smaller K, low similarity → larger K, always bounded by token budget.
16.7.4 Variants, Tools and Exam Focus
Variants summarized — know when each suits:
- Naive RAG: vectors in flat store (for example FAISS). Simple, fast, suitable when relations are not critical and data is short documents. The default for most demos.
- Graph RAG: data stored as a graph (entities and relations from 16.6), retriever traverses relations. Useful in medical (drug-disease-patient), finance (company-supply-relationship), where connecting two distant facts via a relation matters more than vector closeness.
- Multimodal RAG: handles text plus other modalities — tables, images, audio. Know when it is used: when a policy document contains charts or scanned forms, you need image embeddings plus text.
- Agentic RAG: agents orchestrate retrieval, tool use, and generation in loops — the agent decides to retrieve again after seeing partial results. Suitable for multi-step research questions. Conceptual understanding suffices; no math problem will ask for agent loop latency beyond the components already listed.
Challenges and tools (for awareness, not memorized): chunking strategy, embedding choice, vector database, hybrid search (sparse + dense), source citation, freshness. Tools mentioned in ecosystem include vector stores and LLM orchestration frameworks — you need not name them in the exam, just understand roles.
Exam note: mathematical problems on RAG may ask token budget with given numbers (), chunk overlap/stride calculation (, ), latency allowance and whether reranking fits (), purpose and calculation of similarity threshold/top-K, or a combination of all these. No mathematical problem on multimodal or agentic RAG; only conceptual understanding ("what is multimodal RAG, when to use") is expected. Any simple combination of token, chunk, and latency numbers can be given — show formulas and floor/ceiling choices explicitly.
Q: Can a knowledge graph be used alone without RAG? [16.7.qna.1]
A: Yes. Knowledge graphs are used broadly beyond RAG; Google's knowledge graph is a standalone example powering web search entity boxes. In agent tooling, a Google search tool accesses live web results internally using such graphs. RAG is only one application of knowledge graphs; when graph storage is combined with RAG it is called Graph RAG — a variant where retrieval is over graph edges rather than flat vectors. So ontology and graph exist independently, RAG is a compositional pattern that can sit on top.
Q: For the RAG numerical, is it on chunking or token budget or latency or top-K? [16.7.qna.2]
A: It can be any of those or a combination. Token budget using maximum tokens for retrieved chunks given max context, system and query tokens — compute and in the session example. Or chunk overlap/stride computation and chunks . Or latency calculation including whether reranking time fits within the 2500 ms budget. Or threshold/top-K similarity reasoning (for example keep chunks with cosine up to ). Any simple combination of those can be given, so prepare to compute each in isolation and together.
Pitfalls:
- Using ceiling instead of floor for max_chunks. Ceiling overflows context; exam expects floor and the 14 not 15 distinction.
- Forgetting overlap when counting chunks. Using instead of undercounts chunks when overlap is non-zero.
- Adding rerank time even when it is skipped. Total latency is conditional — include rerank only if it fits budget, otherwise state it is skipped.
- Ignoring cost per token. Max chunks is bounded both by latency and by token cost — mention both when justifying K.
Recap and bridge: RAG grounds an LLM without retraining by retrieving chunks via embeddings and augmenting the prompt like an English tutor. Token budget limits max chunks to ; chunk stride gives about chunks; latency must stay below about ms, so reranking is conditional. Graph RAG, multimodal and agentic variants extend the pattern. This retrieval and grounding mindset sets up Text Summarization (16.8), where content selection mirrors retrieval and MMR handles redundancy.
16.8 Text Summarization
16.8.1 Types and When Each Suits
Hook: Given a 500-page report, would you copy its best five sentences or rewrite the story in your own five sentences? Your answer picks your summarization family.
Text summarization reduces a longer text to a shorter version that retains key information while respecting length and coherence.
Three taxonomic axes (know all three):
- Generic versus Query-focused: generic summarizes the whole text evenly without a user question — the goal is to preserve overall gist. Query-focused summarizes with respect to a specific user query (for example "what is papani?" or "travel budget for assistant professors"), keeping only information relevant to that query. The same 500-page policy yields different 5-page outputs for different queries.
- Extractive versus Abstractive: extractive selects and copies existing sentences verbatim — it highlights. Abstractive rewrites and generates new sentences that capture meaning, potentially using words not in the source — it paraphrases. Each suits different applications; you should be able to state which fits a given scenario: extractive when faithfulness and traceability are paramount (legal, medical), abstractive when fluency and compression matter (news, chat).
- Single-document versus Multi-document: not emphasized in this recap but part of the taxonomy — summarizing one article versus many articles on the same event.
The lecture used the highlighter versus pen analogy from companion notes: extractive is a highlighter, abstractive is a pen. The same evaluation (ROUGE) applies to both.
Approaches for extractive content selection:
- IR-based: steps are content selection (which sentences are most important), information ordering (in what order to present them for coherence), and sentence realization (polishing). Example IR-weighting: weight words by TF-IDF and give a sentence the sum of its words' TF-IDF weights (normalize by length to avoid long-sentence bias); sentences with maximum aggregated TF-IDF may be most important and should appear in the summary. Detailed TF-IDF example was shown and should be reviewed — compute term frequency times inverse document frequency per word, sum per sentence, rank.
- Graph-based (LexRank style): represent sentences as nodes, connect by vector similarity (or embedding cosine) above a threshold, find sentences that are maximally connected/central — the most central nodes have high LexRank scores and are likely summary-worthy. It is the graph analogue of PageRank on sentences, alternative to TF-IDF when you trust inter-sentence similarity over word frequency.
- Neural: feed the text into autoencoders or transformers (encoder-decoder) which generate the summary directly; worry about encoder length limits and decoder hallucination. No mathematical problem on neural summarization was indicated for this course, but understanding the pipeline is required: encode long text, decode short summary, train on article-summary pairs, evaluate with ROUGE.
Scope and assumptions: TF-IDF weighting assumes important words are frequent in the document but rare in the collection — that holds for topical words, not for function words. LexRank assumes similarity implies importance, which assumes the document is cohesive; on a multi-topic document, centrality may favor a middle topic only. Neural assumes enough training pairs; with few pairs extractive may beat abstractive. Always state which assumption your scenario violates.
Visual: for IR, imagine a bar chart where x-axis is sentences and y-axis is summed TF-IDF — the top five bars are selected. For graph, imagine sentences as dots with lines thicker for higher similarity — the densest cluster center is selected. For neural, imagine an hourglass: wide encoder, narrow bottleneck, wide decoder. Takeaway: different signals (frequency, centrality, learned) pick sentences differently.
Comparison — extractive versus abstractive versus graph:
| Dimension | Extractive (IR/TF-IDF) | Graph (LexRank) | Abstractive (Neural) |
|---|---|---|---|
| Output | copies source sentences | copies central sentences | generates new words |
| Faithfulness | highest, traceable | high, traceable | lower, needs grounding |
| Need for training data | none (unsupervised) | none (unsupervised) | many pairs required |
| Length control | pick K sentences | pick central K | decoder length control |
| When to pick | legal/medical where wording matters | news/digest where centrality matters | fluent summaries where paraphrase helps |
One-line guide: need audit trail → extractive; need consensus → LexRank; need fluency → abstractive with RAG grounding.
LexRank sketch for completeness: Build sentence similarity matrix . Threshold (for example ) to keep edges. Run PageRank: LexRank with damping . Highest LexRank sentences are summary. No exam math on LexRank beyond describing this flow.
16.8.2 Redundancy Control — MMR
When a summary is limited to, say, five sentences, selecting the five individually most important sentences can produce redundant information — they may all say the same thing in slightly different words, wasting budget. Redundancy must be removed while relevance is retained. The tool for this is Maximal Marginal Relevance (MMR), used after ranking for content selection.
MMR — formalize: Let be the set of retrieved/candidate sentences (not yet chosen), be the set of sentences already selected for the summary, be the query (or document centroid for generic summarization), be similarity (cosine) of candidate to the query, be similarity between candidates, be a weight balancing relevance versus redundancy.
MMR selects the next sentence as:
Interpretation: first term rewards relevance to query, second term penalizes similarity to already selected sentences (redundancy). takes worst-case redundancy — how similar is to its closest already-chosen sentence. When , MMR is pure relevance (no diversity penalty). When , it is pure diversity (ignore query). When , both balance equally. Raising favors relevance; lowering favors diversity/redundancy avoidance.
Properties: in , similarities in for cosine on non-negative vectors, MMR values in but ranking only needs order. The selected set grows incrementally: start with most relevant, then repeatedly apply MMR to add one more.
Worked example — MMR with , relevance versus redundancy
This calculation mirrors the class example where MMR with was worked stepwise.
Suppose query-focused task with candidates and initially where is the most relevant sentence already picked (or empty for first pick). Similarities:
- (very similar to already picked)
- (moderate relevance, low redundancy)
With :
- Score
- Score
- Score
is with , even though was most relevant alone, because is redundant with . That is MMR's purpose: it sacrificed a bit of relevance to avoid repetition.
If next iteration adds to , recompute against the enlarged for remaining candidates and repeat until summary length reached. The same stepwise max-marginal logic was shown in class and should be reviewed as the potential calculation problem; a mathematical problem on MMR can appear — show , both similarity columns, computed scores, and picked .
Edge illustration: with , scores become , , — now ties, showing higher shifts preference back to relevance.
Second tiny check: if empty (first pick), redundancy term is 0, so MMR reduces to — just pick most relevant.
Sense check: MMR never exceeds (when redundancy 0) and never falls below (when relevance 0 but redundant). The chosen sentence balances both.
Additional notes retained:
- Information ordering after content selection also matters; the selected sentences must be ordered coherently (for example chronologically or by narrative flow), not just by MMR score order. Query-focused multi-document summarization combines selection and ordering steps across many source documents, plus redundancy removal across documents.
- Evaluation of summaries uses ROUGE, as covered in 16.1; neural summaries are evaluated the same way — ROUGE-N with pattern and threshold. So the pipeline is: select via TF-IDF/LexRank/MMR → order → evaluate via ROUGE.
Exam note: text summarization was recently covered, so less time was spent in this recap, but standard question types include: conceptual differences (extractive versus abstractive, generic versus query — state which fits a scenario), IR-based steps with TF-IDF calculation, LexRank graph example description, and MMR calculation with balance. Neural techniques require only conceptual preparation (describe encoder-decoder and length limits). Also expect a potential evaluation problem as noted for ROUGE.
Pitfalls:
- Treating as unrelated to weighting. Larger means more relevance, less diversity — state direction explicitly.
- Computing as overlap count without normalizing. Use cosine or normalized similarity, otherwise long sentences dominate unfairly.
- Forgetting to update after each selection. Redundancy is against the enlarged , not the initial seed alone.
- Selecting top-K by relevance alone and claiming redundancy handled. Without MMR, top-K may be near duplicates — always show redundancy term if asked.
Recap and bridge: Summarization chooses between generic/query, extractive/abstractive, and ranks via TF-IDF or LexRank centrality, then de-duplicates with MMR with balancing relevance and redundancy, orders the result, and judges it with ROUGE. That closes the loop from parsing (structure) through attention (representation) and knowledge (WordNet/graph) to retrieval (RAG) and final distillation (summarization) — the full post-midterm arc revisited in this recap.
Exam Guidance Summary
This session served as the final post-midterm recap; pre-midterm quick review was deferred due to time but slides and videos remain available for that portion. All guidance below is carried through from the earlier draft and supplemented with procedure tips.
Structure and marks
- End-semester examination is weighted 40 marks. Pre-midterm content contributes 10 marks; post-midterm contributes 30 marks.
- Paper is open-book. Do not memorize grammar rules, relation names, or long derivations; those will be provided. Instead ensure understanding of procedures so you can apply given rules, POS tags, feature tables, and edge-weight tables.
Breakdown by module — what to expect and how to answer
- Module 2 — vector semantics and language models: 5 marks. Expect mathematical problems on TF-IDF (compute term frequency times inverse document frequency, sum per sentence) or conceptual questions on vector semantics and word embeddings (contrast static GloVe/Skip-Gram with contextual); also a problem on n-gram language models (count, smoothing, perplexity) or an application-oriented question on neural language models.
- POS tagging via Hidden Markov Model: 5 marks. Expect a problem either with Viterbi (trellis with emission and transition probabilities) or without Viterbi (HMM tagging by max probability).
- Parsing (constituency / statistical / dependency together): 6 marks. Expect a small problem or application-oriented question such as building a parse tree via bottom-up chart (show spans, e.g., ), or comparison of why one parsing strategy suits a given application (constituency for grammar check, dependency for relations). Rules and POS tags will be given; you decide phrase boundaries.
- Statistical parsing and PCFG plus CKY and evaluation: integrated with parsing. PCFG six marks style: compute and , with domain-specific probabilities. CKY/CYK: expect CNF conversion ( or , binarizing longer rules with new non-terminals) before CKY; sample paper includes a CNF+CKY question — practice it. Parser evaluation may ask Labelled Precision, Recall, with label+span matching.
- Dependency parsing: part of parsing marks. Expect Arc-eager transition table (stack, buffer, arcs; operations SHIFT, LEFT-ARC, RIGHT-ARC, REDUCE) or Chu-Liu Edmonds graph maximum spanning tree problem using given edge weights (greedy max incoming — keep 30, keep 20 — and cycle contraction with WJS 40 versus 29, 31 versus 30). Also possible: feature weights one iteration with 12 dimensions (C0 C1 C2) showing shift versus left-arc 6 and 4.5, and update . Also edge score where Root→John score 12 will be given as feature table.
- Contextual word embedding and Attention: 6 marks. Mostly a mathematical problem on self-attention: compute , scaled score , softmax , weighted sum for three words I/ate/mango style example; plus conceptual comparison of self-attention versus cross-attention and positional encoding . Residual and layer norm are not core.
- Word sense disambiguation + semantic web ontology: 6 marks together. Expect conceptual or application-oriented questions based on algorithms (Lesk overlap or Naive Bayes for bass fish versus music) or knowledge graph / RDF / OWL construction (triples subject-predicate-object, class axioms) and component description. No heavy math beyond small tables.
- Retrieval Augmented Generation: can include mathematical problems or concepts. Be ready for token budget and max chunks (floor not ceiling), chunk overlap/stride and chunks , latency and check against 2500 ms threshold to decide if reranking fits, plus threshold/top-K reasoning. Tool and challenge awareness is enough for the non-numerical part.
- Text summarization: can include mathematical or application questions. Expect ROUGE evaluation (ROUGE-2 with denominator , ROUGE-1 word overlap, ROUGE-3 , threshold), or MMR with balance , or TF-IDF / LexRank conceptual and scoring steps. Neural summarization is conceptual only. Text summarization evaluation, MMR, and related concepts are all fair game; MMR lambda 0.5 relevance versus redundancy is specifically noted. Evaluation also covers overall weight: pre-mid 10 marks include TF-IDF, n-gram language model, neural LM 5 marks plus HMM POS Viterbi 5 marks — review those slides too. Overall 40 marks, 30 post-mid weightage, open book show tables and assumptions — the recurring instruction is to show work and state assumptions.
- Overall exam advice — open book strategy: Refer to Jurafsky and Martin (especially parsing chapters — statistical parsing, PCFG, CKY) and to the shared watermark slides on the e-learn portal. Use recordings for stepwise algorithm demonstrations. For printing, minimize pages: include only slides with formulas or details that are hard to recall; smaller printouts are faster to search during the exam and save cost and paper. Show work in tables (for example chart parsing steps, stack-buffer-arc tables, CKY triangular tables); this makes grading easier and helps secure partial marks. Write all assumptions in full where interpretation is needed (tokenization for ROUGE hyphen handling, span convention for precision/recall, span numbering for parsing). Practice sample paper questions: there is a question on CNF conversion and CYK in the sample. Difficulty calibration: word sense disambiguation and ontology were described as comparatively simple if concepts are understood — an opportunity to secure marks — so do not leave them to last.
Key Industry Applications
- ROUGE as deployment gate: ROUGE provides the universal recall-based benchmark for summarization systems before deployment. Teams set a threshold (for example ROUGE-2 ) to decide whether an extractive or abstractive summary is good enough, mirroring the lecture's example and threshold decision.
- Parser benchmarking: Labelled precision, recall and with label-plus-span matching (exact label and span must match) are standard for parser benchmarking against gold treebank data. A candidate constituent does not match — that strictness is used in industry evaluation harnesses.
- Constituency versus dependency in production: Constituency parsing underpins grammar-check tools (Grammarly-style) and machine translation where target phrase grammar must be enforced; dependency parsing underpins relation extraction, information extraction, and conversational AI (who did what to whom). Modern pipelines often use dependency relations implicitly via transformers and attention, while still relying on graph-based dependency or neural dependency models in production where explicit relations are needed for explainability.
- Domain-specific PCFG: PCFG domain-specific rule probabilities illustrate why parsers trained on one domain (for example medical) may not transfer without retraining — Wall Street Journal probabilities differ from clinical notes. Retraining on in-domain treebank counts is standard before deploying a parser in a new domain.
- CKY with CNF as textbook standard: CKY with CNF ( or ) is the tabular algorithm taught in textbooks such as Jurafsky and Martin and mirrors bottom-up chart parsing used in statistical parsing pipelines where binarized rules via new non-terminals are introduced first.
- MaltParser-style learning to parse: MaltParser-style arc-eager deterministic parsing illustrates how oracle transitions over stack/buffer/arcs become training data for classifier-based parsers, a pattern reused across ML and neural implementations where features (C0 C1 C2, 12 dimensions) and weights are learned (shift 6 versus left-arc 4.5 after perceptron update ) and applied at test time.
- Chu-Liu Edmonds as workhorse: Chu-Liu Edmonds maximum spanning tree (arborescence) is the workhorse for graph-based dependency parsing in production, greedily keeping max incoming (for example 30 for Mary, 20 for saw) and contracting cycles (WJS 40 versus 29, 31 versus 30) when greedy creates a loop, then expanding — exactly the steps practiced for the exam.
- Contextual embeddings as LLM substrate: Contextual word embeddings with self-attention (, scaled dot , softmax to , weighted sum ) are the input representation for today's LLMs and agentic AI, replacing static embeddings like GloVe and Skip-Gram where a single word type had one vector. The same scaled-dot product is used in dense retrievers and rerankers.
- WordNet and Lesk in practice: WordNet as a manually built lexical graph enables sense features via hypernymy/hyponymy; simple Lesk-style overlap () still competes with heavier methods for many disambiguation tasks where data is scarce, while supervised classifiers treat each sense as a class (Naive Bayes over bass fish versus music). Both patterns appear in entity linking and search query disambiguation.
- Knowledge graphs for grounding and safety: Knowledge graphs (for example Google Knowledge Graph) support web search and agent tooling (agent web-search tool calls). Ontology languages RDF (triples subject-predicate-object) and OWL (classes, restrictions, reasoning) encode domain facts for safe grounding of agents, relevant even on the path toward more general intelligence, where grounding prevents undesired autonomous actions. Ontology design (entities, classes, relations) is the first step before graph construction.
- RAG at scale: RAG architectures dominate current deployments (around nine in ten projects, 90-95% ). Variants in use include naive vector RAG (flat store), Graph RAG for medical/finance where graph traversal matters, multimodal RAG for multi-format data (text plus tables/images), and agentic RAG for orchestrated multi-step workflows. Practical cost and latency engineering tasks are token-budget ( and ), chunk-overlap with stride (, chunks), and latency-budget ( ms) calculations. Embedding-based BERTScore mirrors ROUGE logic but on vectors, improving tolerance to paraphrase where leaf versus leafy mismatch is no longer a failure.
NLP Lecture 16 notes · Final Recap: Parsing, Contextual Embeddings, Word Sense, Retrieval Augmented Generation and Text Summarization
Sections Breakdown
ROUGE-N recall formula, n-gram counting with N-n+1, worked ROUGE-2 example 12/28≈0.43 and handling of paraphrase and hyphenation.
CFG rules, POS tags, parse trees, top-down vs bottom-up vs chart parsing with dot notation, and worked example The large can can hold the water.
PCFG rule probabilities, tree product P(T), sentence sum P(S), CNF conversion A→w and A→BC, CKY triangular table and labelled precision/recall/F1.
Head-root dependency graphs, arc-eager SHIFT/LEFT-ARC/RIGHT-ARC, perceptron weight update, Chu-Liu Edmonds max spanning tree with cycle contraction.
Self-attention QKV, scaled dot product, softmax weighting, multi-head attention, positional encoding and significance for LLMs.
Supervised WSD, Lesk overlap, WordNet similarities, RDF/OWL, ontology components and knowledge graph construction.
RAG retrieval-augmentation-generation, token budget 7672/512=14, chunk stride 480, latency budget under 2500 ms and reranking decisions.
Extractive vs abstractive, TF-IDF and graph ranking, MMR lambda 0.5 redundancy control, neural summarization and ROUGE gate.
Open-book strategy, mark distribution 40 marks, per-module procedure tips, tables and assumption statements required.
Deployment gates, parser benchmarking, constituency vs dependency tradeoffs, domain PCFG, Graph RAG and multimodal patterns.
Exam Revision Notes
Below is the distilled, exam-ready core. Every entry comes from the full explanation above. Use this section for rapid review; return to the main notes when a point needs more context.
ROUGE — Recall-Oriented Evaluation for Summarization
Must-know: Core of ROUGE — Recall-Oriented Evaluation for Summarization: key definition and procedure.
⚠️ Top pitfall: Common pitfall in ROUGE — Recall-Oriented Evaluation for Summarization as discussed in warnings.
Self-check: Quick check question for ROUGE — Recall-Oriented Evaluation for Summarization.
Connects to: Related concepts in this lecture.
Constituency Parsing — Ambiguity, Grammar and Strategies
Must-know: Core of Constituency Parsing — Ambiguity, Grammar and Strategies: key definition and procedure.
⚠️ Top pitfall: Common pitfall in Constituency Parsing — Ambiguity, Grammar and Strategies as discussed in warnings.
Self-check: Quick check question for Constituency Parsing — Ambiguity, Grammar and Strategies.
Connects to: Related concepts in this lecture.
Statistical Parsing, PCFG, CKY and Parser Evaluation
Must-know: Core of Statistical Parsing, PCFG, CKY and Parser Evaluation: key definition and procedure.
⚠️ Top pitfall: Common pitfall in Statistical Parsing, PCFG, CKY and Parser Evaluation as discussed in warnings.
Self-check: Quick check question for Statistical Parsing, PCFG, CKY and Parser Evaluation.
Connects to: Related concepts in this lecture.
Dependency Parsing
Must-know: Core of Dependency Parsing: key definition and procedure.
⚠️ Top pitfall: Common pitfall in Dependency Parsing as discussed in warnings.
Self-check: Quick check question for Dependency Parsing.
Connects to: Related concepts in this lecture.
Contextual Word Embedding and Attention
Must-know: Core of Contextual Word Embedding and Attention: key definition and procedure.
⚠️ Top pitfall: Common pitfall in Contextual Word Embedding and Attention as discussed in warnings.
Self-check: Quick check question for Contextual Word Embedding and Attention.
Connects to: Related concepts in this lecture.
Word Sense Disambiguation, WordNet and Knowledge Graphs
Must-know: Core of Word Sense Disambiguation, WordNet and Knowledge Graphs: key definition and procedure.
⚠️ Top pitfall: Common pitfall in Word Sense Disambiguation, WordNet and Knowledge Graphs as discussed in warnings.
Self-check: Quick check question for Word Sense Disambiguation, WordNet and Knowledge Graphs.
Connects to: Related concepts in this lecture.
Retrieval Augmented Generation (RAG)
Must-know: Core of Retrieval Augmented Generation (RAG): key definition and procedure.
⚠️ Top pitfall: Common pitfall in Retrieval Augmented Generation (RAG) as discussed in warnings.
Self-check: Quick check question for Retrieval Augmented Generation (RAG).
Connects to: Related concepts in this lecture.
Text Summarization
Must-know: Core of Text Summarization: key definition and procedure.
⚠️ Top pitfall: Common pitfall in Text Summarization as discussed in warnings.
Self-check: Quick check question for Text Summarization.
Connects to: Related concepts in this lecture.
Was this lecture useful?
BitsNotes AI Assistant
Subject Notes AssistantConfigure AI Chat
Choose how to access the chatbotSigned in as
Powered by BitsNotes — 20 messages per day. No API key needed. Want unlimited access? Use "Bring Your Own Key" mode.
Sign in to use AI Chat
Get 20 free AI messages per day to ask questions about your lecture notes. Sign in with Google or GitHub — it takes 5 seconds.
Sign In to BitsNotesSwitch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.