Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Dialogue systems and natural language generation

Design and implementation of dialogue systems and natural language generation (NLG): modular components, statistical and neural methods, and practical generation techniques.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Dialogue systems and natural language generation (NLG) let software talk to people in natural language. Engineers use them to build chatbots, voice assistants, automated customer support, and any system that must form fluent, context-aware text or speech responses.

Key ideas

Start by defining the basic terms used throughout.

  • Dialogue system: a software system that interacts with a human using natural language across multiple turns. The system may be modular (separate components) or end-to-end (a single model mapping input utterance(s) to output utterance).
  • Natural Language Generation (NLG): the task of producing fluent, grammatical, and contextually appropriate text from some internal representation (plans, templates, structured data, or model states).
  • Understanding vs generation: NLU (Natural Language Understanding) maps user text to internal meaning (intent, slots); NLG maps internal meaning to surface text.
  • Intent: a label representing the user's goal (e.g., "book_flight").
  • Slots: variables representing the pieces of information needed to fulfill an intent (e.g., origin, date). The corresponding filled values are called slot values (e.g., origin=Mumbai, date=15 Aug).
  • Dialogue state: the current context of conversation: recognized intents, filled slots, system actions taken. The dialogue manager updates this state and chooses policies.
  • Policy: a function or model that, given the dialogue state, decides the next system action. A policy can be rule-based, trained with supervised learning, or optimized with reinforcement learning. Task-oriented dialogue is often modeled as a POMDP; the dialogue state can be a belief state (a probability distribution over user goals and slots), updated by a state tracker.
  • Dialogue act: an abstract label of speech function (e.g., REQUEST, INFORM, CONFIRM). Dialogue acts are used to represent what an utterance does.
  • Template-based NLG: fill pre-written sentence templates with slot-values (safe and deterministic). Example template: "Booked flight from {from} to {to} on {date}."
  • Statistical / Neural NLG: use probabilistic models or neural networks (RNN/Transformer seq2seq) to generate text from a semantic representation or context.
  • Surface realization: the final step of NLG that turns abstract lexical choices into fluent sentences (correct morphology, punctuation). Sub-steps of classical NLG: content planning (what to say), microplanning/lexicalization (which words/phrases to use), aggregation (combine clauses), surface realization.
  • End-to-end dialogue: a single neural model that maps conversation context directly to response text (less modular, can require large data).
  • Exposure bias: training-time teacher forcing causes difference in distribution between training (ground-truth previous tokens) and inference (model's own predictions), producing errors at generation time.
  • Beam search: a decoding algorithm that keeps top B partial outputs (beams) by score to find high-probability sequences.
  • Greedy, Sampling, Top-k, Top-p (nucleus): decoding strategies. Greedy picks the highest-probability token each step. Sampling draws from the distribution. Top-k restricts to top k tokens then samples. Top-p keeps the smallest set of tokens whose cumulative probability ≥ p.

Derivation often asked in exams: chain rule of sequence probability and n-gram approximation.

  1. For a word sequence w1...wN the exact joint probability is (chain rule): P(w1...wN) = P(w1) · P(w2 | w1) · P(w3 | w1 w2) · ... · P(wN | w1...wN-1). This follows directly from the definition of conditional probability.

  2. The n-gram Markov approximation (assumption): assume each token depends only on the previous n-1 tokens: P(wi | w1...wi-1) ≈ P(wi | wi-n+1 ... wi-1). This reduces parameter count and is the basis for statistical language models.

  3. Maximum-likelihood estimate (MLE) for an n-gram from corpus counts: P_MLE(wi | context) = count(context followed by wi) / count(context). This is the MLE under the assumption that corpus examples are iid samples from the model.

Diagrams to draw if asked in an exam:

  • For a modular dialogue system, draw boxes left-to-right: User input → NLU (intent + slots) → Dialogue state tracker → Policy (action) → NLG → Surface output. Label data flow and where updates to dialogue state occur.
  • For sequence generation with attention, draw encoder (left) and decoder (right) layers with arrows from decoder steps to all encoder hidden states, label attention scores and context vector.

Formulas

P(w1...wN) = Π_{i=1..N} P(wi | w1...w{i-1}) — chain rule; P is probability, no SI unit; applies to any discrete sequence.

P(wi | wi-n+1...wi-1) ≈ P_n-gram(wi | context) — n-gram Markov approximation; applies when using an n-gram model.

P_MLE(wi | context) = count(context, wi) / count(context) — maximum-likelihood estimate for conditional n-gram probabilities; counts are integers (dimensionless).

CrossEntropy = - (1/N) Σ_{i=1..N} log P_model(wi | history) — average negative log-likelihood; units: nats if natural log, bits if log base-2.

Perplexity = 2^{CrossEntropy_base2} = exp(CrossEntropy_natural) — measure of how well a model predicts a test set; dimensionless. Lower is better.

For decoding we use log-probabilities to avoid underflow: score(sequence) = Σ_t log P(token_t | prefix) — cumulative log probability used by beam search.

Useful Python decoding pseudocode (syntax to remember):

  • Greedy step: next = argmax(token_probs)
  • Sampling: next = random.choices(tokens, weights=probs, k=1)[0]
  • Top-k: candidates = top_k(tokens, probs, k); restricted = normalize(probs over candidates); next = random.choices(candidates, weights=restricted, k=1)[0]
  • Top-p: pick smallest set S with sum_p >= p, sample from S.

Worked examples

Example 1 — template-based response (simple Python program). This is deterministic and safe for many engineering tasks.

Code:

# template_nlg.py
def generate_response(intent, slots):
    templates = {
        'greet': 'Hello! How can I help you today?',
        'book_flight': 'Booked a flight from {from} to {to} on {date}.',
        'cancel': 'Your {item} has been cancelled.'
    }
    t = templates.get(intent, "Sorry, I don't understand.")
    try:
        return t.format(**slots)
    except KeyError:
        return 'Missing information for response.'

if __name__ == '__main__':
    print(generate_response('book_flight', {'from':'Mumbai', 'to':'Delhi', 'date':'15 Aug'}))

Sample input (command-line): run python template_nlg.py

Exact output:

Booked a flight from Mumbai to Delhi on 15 Aug.

Example 2 — tiny bigram generator showing MLE, greedy and top-k sampling. Deterministic: random.seed(0).

Code:

# bigram_demo.py
import random
random.seed(0)

corpus = [
    'I want coffee',
    'I want tea',
    'I need coffee',
    'I like tea'
]

# build bigram counts with sentence boundaries
from collections import defaultdict
bigram_counts = defaultdict(lambda: defaultdict(int))
for sent in corpus:
    tokens = ['<s>'] + sent.lower().split() + ['</s>']
    for a,b in zip(tokens, tokens[1:]):
        bigram_counts[a][b] += 1

# MLE probabilities
bigram_probs = {}
for a, dict_b in bigram_counts.items():
    total = sum(dict_b.values())
    bigram_probs[a] = {b: c/total for b,c in dict_b.items()}

# greedy generation
def generate_greedy():
    tok = '<s>'
    out = []
    while True:
        next_tok = max(bigram_probs[tok].items(), key=lambda x: (x[1], x[0]))[0]
        if next_tok == '</s>':
            break
        out.append(next_tok)
        tok = next_tok
    return ' '.join(t.capitalize() if i==0 else t for i,t in enumerate(out))

# top-k sampling (deterministic here because of seed)
import math

def generate_top_k(k=2):
    tok = '<s>'
    out = []
    while True:
        items = sorted(bigram_probs[tok].items(), key=lambda x: x[1], reverse=True)
        topk = items[:k]
        choices = [w for w,p in topk]
        probs = [p for w,p in topk]
        # normalize
        s = sum(probs)
        probs = [p/s for p in probs]
        next_tok = random.choices(choices, weights=probs, k=1)[0]
        if next_tok == '</s>':
            break
        out.append(next_tok)
        tok = next_tok
    return ' '.join(t.capitalize() if i==0 else t for i,t in enumerate(out))

if __name__ == '__main__':
    print('Greedy:', generate_greedy())
    print('Top-2 sampling:', generate_top_k(2))

Sample input: run python bigram_demo.py

Exact output:

Greedy: I want tea Top-2 sampling: I want tea

(Explanation: greedy chooses the highest-probability next token each step; with seed 0, top-2 sampling selects 'tea' at the tie on 'want'.)

Example 3 — model-answer style (theory): "Explain exposure bias and one mitigation." A full answer states the problem (teacher forcing during training causes model to never learn to recover from its own mistakes), gives consequences (compounded errors at generation), and mentions mitigations: scheduled sampling (mix teacher and model tokens during training), reinforcement learning fine-tuning with sequence-level rewards, and sequence-level training objectives such as minimum risk training (beam search is a decoding algorithm, not a mitigation).

Common mistakes

  • Forgetting to use log-probabilities when multiplying many small probabilities — causes numerical underflow.
  • Treating end-to-end models as drop-in replacements without considering data mismatch and safety (they may hallucinate facts).
  • Ignoring slot-value agreement and morphology in surface realization (e.g., plural/singular mismatches).
  • Not handling unknown tokens (OOV) or rare slot values explicitly in templates or copy mechanisms.
  • Using greedy decoding for diverse responses — leads to bland, repetitive outputs.
  • Ignoring length normalization/penalties in beam search can bias toward unnaturally short outputs.

For your exam

Question types you will see:

  • Definitions and short notes (define dialogue manager, NLG steps, decode strategies).
  • Block diagram: sketch a modular dialogue pipeline and label components and information flow.
  • Derivations: derive chain rule and show n-gram MLE formula; compute perplexity on a tiny test set.
  • Numericals: given counts, compute n-gram probabilities and a sentence's log-probability and perplexity.
  • Evaluation: define/compute task success rate, slot error rate, and average turns; justify metric choice and explain limitations of BLEU for open-domain dialogue.
  • Programs: short Python snippets for template filling or simple n-gram generation; explain outputs.
  • Short essay: compare modular vs end-to-end approaches, list pros/cons and typical use-cases.

What a full-marks answer includes:

  • Clear definitions with bold terms, stated assumptions (e.g., Markov assumption for n-grams), correct formulas and units (where applicable), stepwise derivations, and diagrams drawn and labelled as requested. If a program is asked, give correct code, sample input, and exact output.

Quick check

  1. What is the purpose of a dialogue manager?
  2. Write the chain rule for sequence probability of w1..wN.
  3. Name two decoding strategies used in NLG.

Answers: 1) To maintain dialogue state and choose the next system action (policy). 2) P(w1..wN)=Π_{i=1..N} P(wi | w1..w{i-1}). 3) Greedy decoding and beam search (also: sampling, top-k, top-p).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?