LLGA · Course notes

Control in Generative AI

M2 · P1 (announced) · Year 2 · Period 1

Contents

Introduction and overview

Module Control in Generative AI
Code Not published — the module is announced in period 1 by the master’s brochure; the 2026-2027 SynapseS course description has not been published (the S3/S4 tracks of the catalog are currently empty).
Team and workload Instructor, teaching hours and ECTS: not published · why and how to steer generation — taxonomy of control (conditioning, guidance, hard constraints, post-processing), automaton-based constrained decoding with a detailed masking algorithm, steering vectors, RLHF as control, LLM watermarking with the z-test proved, control of diffusions (CFG, ControlNet, editing by inversion) and of graph generators, evaluation of the fidelity/diversity trade-off and robustness to attacks.
Period M2 · period 1 (announced)
Status in the program M2Graph × LLM route preselected by the Graph × LLM route of the home page; M2 program being finalized by the course instructors; the official description will not be communicated until the course description is published.

Audience: a generative-AI engineer who already knows how to generate and now has to steer the output (format, safety, provenance). Empirical first: each chapter starts from a concrete failure — a broken JSON despite the prompt, a watermark that no longer shows after a paraphrase — and only then names the technique that fixes it (constrained decoding, steering, RLHF/DPO, watermarking).

The module is organized around four families of control, which together turn a generator that merely produces plausible outputs into a reliable tool.

What you will be able to do

Official objectives and syllabus

Official syllabus: course description not published — this module appears neither in the S3 track nor in the S4 track of the 2026-2027 SynapseS catalog (both currently empty), and the master’s wiki indicates that the detailed M2 curriculum is still under development: description, teaching hours and instructor are therefore “not published”. The themes below are those carried by the module in the master’s brochure, as restated by these course materials, mapped to the sections that cover them.

Announced theme (brochure, as restated by the materials) Course section covering it
Why control: safety, fidelity, intellectual property ch. 1 “Why control: safety, fidelity, intellectual property”
Taxonomy of the families of control ch. 2 “Taxonomy: four families of control”
Constrained decoding: grammars, automata, masks ch. 3 “Constrained decoding: grammars, automata, masks”
Steering in activation space ch. 4 “Steering: controlling in activation space”
RLHF as control of behaviors ch. 5 “RLHF: control in behavior space”
Watermarking: proving the origin of a text ch. 6 “Watermarking: proving the origin of a text”
Controlling diffusions: CFG, ControlNet, inversion ch. 7 “Controlling diffusions: CFG, ControlNet, inversion”
Controlling graph generators ch. 8 “Controlling graph generators”
Evaluating control: fidelity versus diversity ch. 9 “Evaluating control: fidelity versus diversity”
Attacks on control and robustness ch. 10 “Attacks on control and robustness”

The exact split between brochure content and the materials’ own extensions can only be settled once the official course description is published; in any case, chapter 0 (reminders: generating, conditioning, decoding) is part of the common structure of the repository’s course materials.

Where this course fits in the program

M2 module offered in period 1 and preselected by the Graph × LLM route of the home page: it synthesizes building blocks seen elsewhere in the master rather than introducing a new heavy formalism.

Prerequisites (Year 1): classifier-free guidance and diffusion models from Multimodal Generative AI (ch. 7 builds directly on them); the KL-regularised policy lemma of Reinforcement Learning ch. 6 (recalled in ch. 5); graph generation from Graph ML ch. 9 (reread in ch. 8). Large Language Models runs in the same period, so ch. 0, 3 and 5 recall what they use from it (decoding rules, function calling, RLHF and DPO) instead of assuming it.

Downstream modules: the textual watermarking of ch. 6 is taken up and extended on the attestation and anonymization side by Explainability, Security, Privacy of LLMs (ch. 9), which also covers safety-side attacks; Graph Generative Models (period 2) develops in depth the graph generators whose control ch. 8 introduces; Speech Technology for Conversational AI mobilizes the same control reflexes in continuous settings (expressivity, latency, guardrails, audio watermarking in its ch. 9) in the voice conversational loop.

Course outline

Session plan

24 h in class (assumed) = 8 sessions of 3 h. The fiche publishes no teaching hours: 24 h is the M2 volume published for the Large Language Models course (CSC_53432_EP: 24 h, 2 ECTS) and is assumed here; the session split below is our proposal for covering these notes in that time. Level 1 = foundations (reviews, definitions, first worked examples), 2 = core methods, 3 = advanced material (attacks, impossibility results, open problems); the level never goes down from one session to the next.

Session Hours Level Content Practice
1 3 h 1 ch. 0 Reminders: generating, conditioning, decoding rules; ch. 1 Why control classify three failures of your own LLM use with Definition 1.1
2 3 h 1 ch. 2 Taxonomy, what masking does to the law, cost of rejection; ch. 3.1 From regex to automaton Ex. 1(a)
3 3 h 2 ch. 3.2 The masking algorithm, BPE subtleties, a function call under a JSON schema, grammars Ex. 1(b)–(d)
4 3 h 2 ch. 4 Steering vectors; ch. 5 RLHF recalled as exponential guidance, Bradley–Terry, DPO, one GRPO step Ex. 3
5 3 h 2 ch. 6 Watermarking: the z-test, power and sample size, distortion-free schemes (Gumbel, SynthID) Ex. 2
6 3 h 2 ch. 7 Controlling diffusions: CFG recalled, ControlNet’s zero-convolutions, inversion and null-text Ex. 5
7 3 h 2 ch. 8 Controlling graph generators; ch. 9 Evaluating control Ex. 4
8 3 h 3 ch. 10 Attacks on control and robustness Ex. 6

Self-study, outside the 24 h: no chapter — every chapter is covered in class; the labs (Ex. 1–3 and 6) each need about 2 h of personal work after the session that introduces them.

How to study this module

The LLGA perspective Control is the exact place where the three pillars of the master — LLMs, multimodal diffusion, graphs — speak the same language: same constraint grammars, same fidelity/diversity trade-off, same attacks. By seeing it first as a cross-cutting problem rather than a collection of per-modality recipes, you will acquire the reflex that distinguishes generative AI engineers and researchers: choosing the level of intervention (data, decoding, activations, behaviors) before choosing the tool.

Independent note Place in the two-year path: as in the rest of the master, this module shows the concrete failure modes first and introduces the names and theorems afterwards.

0. Reminders: generating, conditioning, decoding

Every control technique of this module modifies one of three things: the way a model generates, the signal it is conditioned on, or the decoding rule that turns its scores into an output. This chapter lists what the prerequisite modules taught about each, so that the later chapters can refer to it.

Prerequisites — what is assumed from Year 1, and what is recalled here

  • Autoregressive generation (Text Mining and NLP, ch. 1 and 7; taken further, in the same period as this course, by Large Language Models ch. 1–2): the factorization p_\theta(y \mid x) = \prod_{t} p_\theta(y_t \mid x, y_{<t}), a softmax over the vocabulary \mathcal{V} (BPE: tokens are subword units, not characters). The decoding rules are recalled in Definition 0.1 below, because Large Language Models reaches them (its ch. 6) later in the period;
  • KL-regularised alignment (Reinforcement Learning, ch. 6): the closed form of a reward maximized under a KL penalty. Ch. 5 recalls it and adds the reward model, DPO and one GRPO step, so it does not wait for Large Language Models ch. 5;
  • Diffusion (Multimodal GenAI, ch. 3–4): DDPM, the noise prediction \epsilon_\theta(x_t, t, c), classifier guidance and classifier-free guidance (CFG), DDIM and its inversion — recalled in ch. 7;
  • VAE and ELBO (Multimodal GenAI ch. 1; Deep Learning ch. 9): the variational bound, the reconstruction/regularization trade-off;
  • Graph generation (Graph ML, ch. 9, mandatory): GraphVAE and NeVAE (9.3), GraphRNN (9.4), DiGress (9.5), evaluation (9.6). The flow model GraphAF is not taught there: ch. 8 gives it, like the other two models it uses, a self-contained half page. Graph Generative Models comes after this course (period 2) and develops all of them;
  • Hypothesis testing (Refresher Statistics ch. 6): type I/II error, threshold, p-value, central limit theorem — ch. 6 makes intensive use of it.

Decoding is the first place where control happens, often without being named. Every rule below turns the logits into a law, and most of them do it by a mask followed by a renormalization.

Definition 0.1 — Decoding rules At step t the model outputs logits z \in \mathbb{R}^{|\mathcal{V}|}.

  • Temperature T > 0 (elsewhere T counts the tokens of a text in ch. 2 and 6, as in Large Language Models 9.5, and the diffusion steps in ch. 7): p_i = \frac{\exp(z_i / T)}{\sum_j \exp(z_j / T)}; T \to 0 gives greedy decoding, T = 1 the model’s own law, T > 1 a flatter law.
  • Top-k: keep the k most probable tokens, set the others to zero, renormalize.
  • Top-p (nucleus): keep the smallest set of most probable tokens whose total mass is at least p, renormalize.
  • Min-p: keep the tokens with p_i \geq p_{\min} \cdot \max_j p_j, renormalize.

Example 0.2 — Three truncations of the same step Take the step law p = (0.50,\ 0.30,\ 0.15,\ 0.05) at T = 1.

  • Top-k with k = 2 keeps the first two tokens and gives (0.625,\ 0.375,\ 0,\ 0).
  • Top-p with p = 0.9 keeps three tokens, whose mass 0.95 is the first to reach 0.9, and gives (0.526,\ 0.316,\ 0.158,\ 0).
  • Min-p with p_{\min} = 0.2 uses the threshold 0.1 and keeps the same three tokens.

Each rule is a mask followed by a renormalization: exactly the operation of the hard constraints of ch. 2–3, used here for fluency rather than for validity.

The module’s storyline The previous modules answered “how to generate?”. This one answers “how to generate what we want?”. The course’s thesis: control is not a patch applied after the fact but a unified family of mechanisms — condition, guide, constrain, filter — that recur identically on text (ch. 3-6), images (ch. 7), and graphs (ch. 8), with a common fidelity/diversity trade-off (ch. 9) and a common attack surface (ch. 10).

Module status Course offered in the M2 brochure (period 1): the instructors are not yet confirmed. There is therefore no “research of the instructor” chapter; the content follows the standards of the field and the modules already covered by the master (cross-referenced throughout), and will be completed as needed.

1. Why control: safety, fidelity, intellectual property

Consider an agent that “follows” its prompt in every respect except the output grammar that the business application expects. This chapter explains why such failures are unavoidable without dedicated mechanisms, and motivates each family of control by the failure it addresses.

What breaks Three naive approaches fail in practice: a prompt alone imposes no constraint on the output, rejecting bad outputs and resampling is too costly when good outputs are rare, and a watermark added without care does not survive changes in sampling or editing.

A generator is a law over an immense space. Asking it politely (a prompt) only constrains this law statistically: no theorem guarantees the exact format, the safety of the content or the traceability of the origin.

Definition 1.1 — Controlling a generator Let p_\theta(\cdot \mid x) be a conditional law over outputs y \in \mathcal{Y}^* (token sequences, images, graphs). Controlling means replacing p_\theta with a law \tilde p that

  • (i) lives on a specified subset S \subseteq \mathcal{Y}^* (support constraint: a language, a JSON schema, a chemical valence); or
  • (ii) maximizes in expectation a property c (fidelity constraint: following the instruction, the style, the target); or
  • (iii) carries a verifiable mark of origin (provenance constraint: watermarking).

Chapters 3 to 8 realize (i)-(ii)-(iii) through different mechanisms; ch. 2 will organize them.

Example 1.2 — Three real failures, three needs

  1. Format safety: one asks the LLM for a JSON of the form {"user": ...}; it replies with a trailing comma, a typographic apostrophe, or worse a preamble “Here is the requested JSON”. Any downstream parser breaks. The need: S = the strict JSON language, a 100% guarantee — that is ch. 3.
  2. Fidelity: one asks for a neutral summary in formal French; the model slips into casual style one time out of ten. The prompt guarantees nothing; the need is statistical — soft steering of the law: ch. 4 and 5.
  3. Provenance: a text circulates: human or machine? The classifier is unreliable; the need is cryptographic: a statistical mark planted at generation, testable — ch. 6.

Theorem 1.3 — Intellectual property and law as drivers of control Regulation (EU) 2024/1689 (“AI Act”, art. 50) imposes provenance transparency: providers of generative systems must mark their outputs in a machine-readable way and make them detectable as artificially generated.

Concretely: watermarking (ch. 6) is no longer an academic exercise but a compliance requirement; likewise for audio marking (taken up in Speech Technology, ch. 9) and images. This legal framework motivates the control/robustness articulation (ch. 10): an attackable mark is not a proof.

Control cuts across modalities The module’s guiding thread: the same four mechanisms (condition, guide, constrain the support, filter a posteriori) apply to text, images, and graphs. The tools differ (automata for text; ControlNet and CFG for images; valence masks for graphs), the theory does not. The table in ch. 2 sets the grid; each chapter fills it in for one modality.

2. Taxonomy: four families of control

Many techniques claim to “control” a generator; this chapter sorts them into four families according to where they intervene and what they guarantee, so that every later chapter can be placed on the same grid.

Definition 2.1 — The four families Let c be the control signal (instruction, target property, admissible language).

  1. Conditioning: c enters the model (prompt, prefix, fused embedding); the law becomes p_\theta(\cdot \mid x, c). Zero inference cost, no guarantee — soft control;
  2. Guidance: one biases the sampling toward c without relearning p_\theta — in diffusion (ch. 7), with \hat\epsilon_c and \hat\epsilon_u the noise predictions with and without c, the guided prediction \hat\epsilon_u + w(\hat\epsilon_c - \hat\epsilon_u); activation steering for LLMs (ch. 4), regressor guidance of graph diffusion (ch. 8); the strength w tunes fidelity at the price of diversity;
  3. Hard constraints: one restricts the support — automaton-constrained decoding (ch. 3), valence masks (ch. 8), inpainting. A 100% guarantee of validity; risk: a law renormalized step by step, which is biased away from p_\theta(\cdot \mid x, S) (proposition 2.2) and possibly impoverished;
  4. Post-processing / filtering: generate, check c, reject (best-of-n, resampling, correction); exact but costly when c is rare.

Proposition 2.2 — Masking guarantees validity, not exact conditioning Let S \subseteq \mathcal{Y}^* be a set of admissible outputs and p_\theta an autoregressive law; the prefix y_{<t} includes the input x.

At each step, the mask allows the set A_t(y_{<t}) of tokens v, EOS included, after which the prefix can still be completed into an element of S. With the allowed mass Z_t(y_{<t}) = \sum_{v \in A_t(y_{<t})} p_\theta(v \mid y_{<t}), the masked law is \tilde p_\theta(y \mid x) = \prod_t \frac{p_\theta(y_t \mid y_{<t})}{Z_t(y_{<t})}\ \text{ on } S, \qquad 0 \text{ outside } S.

  1. Validity: the support of \tilde p_\theta is contained in S.
  2. Bias: \tilde p_\theta differs in general from the conditional law p_\theta(y \mid x, S) = \frac{p_\theta(y \mid x)\,\mathbf{1}[y \in S]}{p_\theta(S \mid x)}. Exact conditioning weights each allowed token by the probability p_\theta(S \mid y_{<t} v) that the model’s own continuation still lands in S; the mask replaces this weight by 1.
  3. Bound: if every output of S has at most T steps and the mask never removes more than a mass \varepsilon (Z_t \geq 1 - \varepsilon on every admissible prefix), then for every y \in S

Key result — the masked law is within a factor (1-\varepsilon)^{\pm T} of the conditional (1-\varepsilon)^{T} \;\leq\; \frac{\tilde p_\theta(y \mid x)}{p_\theta(y \mid x, S)} \;\leq\; (1-\varepsilon)^{-T}.

Proof.

  1. Validity. A token is allowed only if the prefix it creates can still be completed in S, and EOS only when the prefix itself is in S.
  2. Ratio. For y \in S, the definition gives \tilde p_\theta(y \mid x) = \frac{p_\theta(y \mid x)}{\prod_t Z_t(y_{<t})}, hence \frac{\tilde p_\theta(y \mid x)}{p_\theta(y \mid x, S)} = \frac{p_\theta(S \mid x)}{\prod_t Z_t(y_{<t})}. The product depends on the path y, so the factors do not telescope into the constant p_\theta(S \mid x).
  3. Exact conditioning. By the chain rule, p_\theta(y \mid x, S) is the product over the steps of p_\theta(v \mid y_{<t}) \, \frac{p_\theta(S \mid y_{<t} v)}{p_\theta(S \mid y_{<t})}, \qquad v = y_t . The weight p_\theta(S \mid y_{<t} v) needs a sum over all continuations, which is intractable in general.
  4. Bound. Each Z_t lies in [1-\varepsilon, 1], so the product lies in [(1-\varepsilon)^T, 1]. Since p_\theta(S \mid x) = \sum_{y \in S} \tilde p_\theta(y \mid x) \prod_t Z_t(y_{<t}) is an average of such products, it lies in the same interval. ∎

Example 2.3 — A two-token counterexample Vocabulary \{a, b\}, outputs of exactly two tokens. The first token is uniform. After a the model gives p(a \mid a) = 0.1 and p(b \mid a) = 0.9; after b it is uniform. The admissible set is S = \{aa, ba, bb\}.

  • Conditional law: p(S) = 0.05 + 0.25 + 0.25 = 0.55, so p(aa \mid S) = 0.05 / 0.55 \approx 0.09 and p(ba \mid S) = p(bb \mid S) \approx 0.45.
  • Masked law: both first tokens can still reach S, so step 1 stays uniform. After a, only a is allowed and receives all the mass. Hence \tilde p(aa) = 0.5 and \tilde p(ba) = \tilde p(bb) = 0.25.

The mask multiplies the probability of aa by more than five. Exact conditioning would have weighted the first step by p(S \mid a) = 0.1 and p(S \mid b) = 1.

What to use when the bias matters Three routes, in increasing cost.

  • Accept it, when the model already puts almost all its mass on S: with \varepsilon = 10^{-3} and T = 200, the ratio stays within [0.82, 1.22]. This is the usual case for a model trained on data that are in S, where p_\theta(\cdot \mid S) \approx p_\theta \approx p_\star, the data law.
  • Estimate the weights p_\theta(S \mid y_{<t} v): sequential Monte Carlo over many partial outputs (Lew et al., 2023), or grammar-aligned decoding, which learns them from past samples (Park et al., NeurIPS 2024).
  • Reject (proposition 2.4): exact, at a cost of 1/p_\theta(S \mid x) draws.

Graph Generative Models (period 2) applies the same analysis to valence masks.

Proposition 2.4 — Rejection costs 1/p_\theta(S \mid x) Filtering by rejection (drawing iid until landing in S) realizes p_\theta(\cdot \mid x, S) exactly, but the number of draws follows a geometric law of expectation 1/p_\theta(S \mid x).

Proof. Each draw is an independent Bernoulli trial with success probability q = p_\theta(S \mid x); the waiting time for the first success is geometric, \mathbb{E}[N] = \sum_{k \geq 1} k(1-q)^{k-1}q = 1/q . For complex unconstrained JSON, q can be 10^{-2} (100 draws on average); for a valid molecule without constraint, GraphAF measures 68% (ch. 8); for a sentence satisfying all of ten rare constraints, q collapses exponentially — hence the structural superiority of the mask, which pays only a single pass. ∎

Family Guarantee Cost Diversity Law modifier
Conditioning (prompt, instruction) none zero preserved changes p_\theta itself
Guidance (CFG, steering, RLHF) statistical (\uparrow w) 1-2 passes decreases with w p^{1-w} \cdot \mathrm{score}(c)^w
Hard constraint (automaton, mask) 100% on S 1 pass + mask bounded by |S| stepwise renormalization, close to p(\cdot \mid S) only if little mass is masked (prop. 2.2)
Rejection / best-of-n 100% (if exact test) 1/p(S) passes conditioned exact conditioning p(\cdot \mid S)

Hard or soft: how to choose? A favorite exam question. If failure is catastrophic (the parser breaks, the molecule is invalid): hard constraint. If failure is gradual (tone, style, relevance): guidance, with the strength tuned by the fidelity/diversity curve of ch. 9. In practice one stacks: format constraint (hard) + alignment (RLHF) + watermark (provenance) — the three layers of 2026 production systems, which ch. 10 shows fall… together if one is not careful.

3. Constrained decoding: grammars, automata, masks

The technical heart of the module for text: guaranteeing that an output authorized token by token belongs to a formal language — regular expression, context-free grammar (JSON, SQL), or logical constraint. The founding idea (PICARD, then Outlines and XGrammar): decoding is a walk in an automaton, and the LLM is only allowed to follow valid transitions.

3.1. From regex to automaton

Definition 3.1 — DFA and regular language A deterministic finite automaton is a quintuple A = (Q, \Sigma, \delta, q_0, F): states Q, alphabet \Sigma, transition \delta : Q \times \Sigma \to Q, initial state q_0, accepting states F.

One extends \delta to words by \delta^*(q, uv) = \delta^*(\delta^*(q, u), v). The recognized language is L(A) = \{w \in \Sigma^* : \delta^*(q_0, w) \in F\}.

Construction: regex \to \varepsilon-NFA (Thompson, linear in the pattern size), then determinization by subset construction (2^{|Q|} states at worst, rare in practice).

Course example, the ISO date: \d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]) — a nontrivial F: “2026-02-31” must be syntactically accepted (calendar semantics is not a simple regular language: we return to this).

Proposition 3.2 — Prune before masking: co-accessibility For masking, one replaces A with its co-accessible sub-automaton: one removes the states q from which no accepting state is reachable (computation: reverse traversal of the transitions from F, \mathcal{O}(|Q| + |\delta|)). It is this sub-automaton that guarantees that a prefix always remains extensible into a complete word: without pruning, the decoder could lock itself in a dead end (no admissible token, including EOS) and generate indefinitely.

3.2. The masking algorithm, in detail

Theorem 3.3 — Constrained decoding by state→tokens index (Willard & Louf, 2023) Let \mathcal{V} be the tokenizer vocabulary (multi-character tokens!). One precomputes, for each state q of the pruned DFA, the set of admissible tokens \mathrm{Adm}(q) = \big\{ v \in \mathcal{V} \ : \ \delta^*(q, \mathrm{str}(v)) \ \text{is defined and co-accessible} \big\}, with the table \mathrm{next}(q, v) = \delta^*(q, \mathrm{str}(v)).

Constrained decoding replaces each distribution with p^{\mathrm{mask}}_\theta(v \mid y_{<t}) \propto p_\theta(v \mid y_{<t})\, \mathbf{1}\big[v \in \mathrm{Adm}(q_t)\big], \qquad q_{t+1} = \mathrm{next}(q_t, v_t), and allows EOS only if q_t \in F.

Then every output is in L(A): the guarantee is structural, by induction over the steps (proposition 2.2, validity). The law obtained is the stepwise-renormalized one of proposition 2.2, not p_\theta(\cdot \mid L(A)).

Proof.

  • Complexity. Precomputation: |Q| \times |\mathcal{V}| token reads, each \mathcal{O}(|v|) transitions — once and for all (and shareable between requests of the same grammar: XGrammar further accelerates by separating context-independent tokens, pre-checked globally, from dependent ones, the only ones resimulated).
  • Online: one table lookup per step returns the precomputed boolean mask of q_t, applied by a single vectorized operation over the logits. Looping in Python over \mathrm{Adm}(q_t) would cost \mathcal{O}(|\mathrm{Adm}(q_t)|) per step instead. Either way, the overhead is negligible next to the transformer pass.
  • BPE subtlety: a token is not a character; "12" and "12/" are two distinct tokens; the definition of \mathrm{Adm} copes with this because \delta^* reads the string of the token, character by character — the DFA does not even know it is being run over BPEs.

Instructive counterexample: a token can cross the boundary of the language ("}," is valid at the end of JSON, "},x" is not); this is precisely why one must index over tokens and not over characters. ∎

# pedagogical skeleton: automaton-based constrained decoding (cf. lab 1)
import torch

class DfaMask:
    """dfa.walk(q, s): state reached by reading the string s from q, or None
    (dead prefix); the DFA is already pruned (prop. 3.2).
    token_str: {token_id: decoded string}, special tokens (EOS included) left out."""

    def __init__(self, dfa, token_str, vocab_size, eos_id):
        self.accepting, self.eos_id = dfa.accepting, eos_id
        self.next = {}                         # q -> {token_id: q2}
        self.allowed = {}                      # q -> boolean tensor, precomputed
        for q in dfa.states:                   # O(|Q| x |vocab| x |v|), once
            self.next[q] = {}
            ok = torch.zeros(vocab_size, dtype=torch.bool)
            for tid, s in token_str.items():
                q2 = dfa.walk(q, s)            # read character by character
                if q2 is not None:
                    self.next[q][tid] = q2
                    ok[tid] = True
            self.allowed[q] = ok

    def mask(self, logits, q):
        out = logits.masked_fill(~self.allowed[q], float("-inf"))  # -inf = forbidden
        if q in self.accepting:                # mask first, then restore EOS
            out[self.eos_id] = logits[self.eos_id]
        return out

# generation loop (the DFA is the state of the control, the LLM provides the logits)
#   q = dfa.q0
#   while True:
#       logits = model(y).logits[0, -1, :]
#       v = int(torch.multinomial(torch.softmax(dm.mask(logits, q), -1), 1))
#       if v == dm.eos_id:  break                        # only possible when q in F
#       q = dm.next[q][v]
#       y = torch.cat([y, torch.tensor([[v]])], dim=1)   # invariant: prefix of L(A)

Example 3.4 — A date by hand Constraint with a month check, \d{2}/(0[1-9]|1[0-2])/\d{4}. After "26/0", the state encodes “second digit of the month in progress, 0 already seen”; the token "0" is masked (only 1-9 complete a month 01-09), and so is "/". Conversely, if the first digit of the month were 1, the second would be restricted to 0-2.

Writing the table \mathrm{Adm}(q) for these states is exercise 1; the classic pitfall: allowing the token "13" as a single BPE block when the state accepts only "1" followed by "0-2" — "13" must be masked as a whole.

Example 3.5 — A function call under a JSON schema An agent may call one tool, get_weather, whose schema has two fields: city, a string, and unit, either "C" or "F". With a fixed key order and fixed spacing, the valid calls form a regular language:

\{"city": "[^"\\]*", "unit": "(C|F)"\}

Decoding walks this automaton in four phases.

  1. Forced prefix. At the start, only tokens that continue the literal {"city": " are admissible (a long token may run on into the city name). Outlines and XGrammar even skip the model call when a single continuation exists.
  2. Free string. Inside the city name, every token whose characters avoid " and \ is admissible. So is a token that closes the string and continues the literal, such as ",.
  3. Enumeration. After "unit": ", only the tokens that start C or F survive: the model’s preference between the two units is renormalized over two options.
  4. End. After the closing }, only EOS remains.

The output parses by construction, but whether "Paris" is the city the user meant is a semantic question (ch. 10). A schema with recursion, such as a tree of comments of any depth, is no longer regular: it needs the grammar engines of the next note.

Beyond regular languages: grammars and JSON Schema Regular languages cannot express nesting ({"a": {"b": ...}} of arbitrary depth). One needs context-free grammars: PICARD (Scholak et al., EMNLP 2021) constrains a T5 on SQL by incremental parsing (forbidden logits are set to -\infty as soon as the token makes the derivation dead).

XGrammar compiles EBNF/JSON Schema into nearly free online masks: a pushdown automaton, with the context-independent tokens checked once at compile time. In 2026 industrial practice: every LLM tool call (function calling) goes through a grammar mask — the output is valid JSON by construction (example 3.5). Cf. Large Language Models, ch. 8 for the agent layer.

4. Steering: controlling in activation space

Constrained decoding acts on the outputs. Steering acts inside the network: if concepts (“positivity”, “gender”, “refusal”) are encoded by directions of the activation space, then moving them should move the behavior. This is the most fascinating and least guaranteed control of the module.

Definition 4.1 — Steering vector (ActAdd, Turner et al. 2023) Let h^{(l)}(x) \in \mathbb{R}^d be the residual activation of layer l after reading the prefix x. For two contrasted prompts x^+ (“Love”) and x^- (“Hate”), one defines v = h^{(l)}(x^+) - h^{(l)}(x^-) \in \mathbb{R}^d, and, during generation, one replaces h^{(l)}(x_t) \leftarrow h^{(l)}(x_t) + \alpha\, v, at the first positions of the prompt (ActAdd) or at every position (contrastive activation addition); \alpha, a few units in Turner et al., is the guidance strength.

The model, the weights, the prompt: nothing changes — only a vector is added.

Example 4.2 — The founding experiments, described step by step (to replay in lab 3) Model: GPT-2-XL in the paper; the lab uses GPT-2 small. The paper runs two distinct experiments, with two distinct vectors.

  1. Sentiment, with the Love–Hate vector. Compute the vector v_{\mathrm{LH}} of definition 4.1 at layer 6, with x^+ = \texttt{Love} and x^- = \texttt{Hate}. Continue a hostile prompt such as “I hate you because” without steering, then with \alpha > 0: the continuations turn affectionate. A sentiment classifier makes the shift measurable.
  2. Topic, with a weddings vector. Take the contrast pair “I talk about weddings constantly” / “I do not talk about weddings constantly”. Count the wedding-related words (wedding, bride, groom…) in the continuations: their frequency rises with \alpha.
  3. Cost, with the same weddings vector. Measure the perplexity on OpenWebText documents sorted by their frequency of wedding words. At a moderate \alpha it falls on wedding-related documents and stays nearly flat on the others; a large \alpha gives degenerate text.
  4. Layer. The effect depends strongly on the layer (middle layers work best) — one more hyperparameter.

Proposition 4.3 — Why a simple addition shifts the output (first-order analysis) Let W_U denote the unembedding matrix (output layer). The logit of token w equals \ell_w = \langle W_U^{(w)}, h^{(L)} \rangle (final layer, ignoring the softmax).

If the steered residual h^{(L)} + \alpha v^{(L)} stays within the network’s linearity domain, then \Delta \ell_w \;=\; \alpha\, \langle W_U^{(w)}, v^{(L)} \rangle\ : all tokens aligned with the direction v are favored proportionally to \alpha — a global, monotone reweighting, even before any nonlinear effect.

Proof. Differentiability: to first order, h^{(L)} \mapsto \ell_w is affine; \Delta \ell_w = \nabla_h \ell_w^\top (\alpha v) = \alpha \langle W_U^{(w)}, v\rangle. This is exactly the structure of guidance (ch. 2, family 2): each token’s logit is shifted by a “compatibility with the direction” score.

The difference from the mask: here no logit is sent to -\infty — the law keeps full support, the control is soft; and the linear approximation becomes false as \alpha grows, hence the observed degeneration. ∎

The steering family in 2026: reading, writing, weights

  • Read: probing and concept directions (taken up in period 2 by the Explainability module, ch. 1);
  • write: ActAdd (difference of two activations), contrastive activation addition (differences averaged over pairs of behaviors), inference-time intervention (moving activations toward the truthfulness direction), representation engineering (Zou et al., 2023: extracting via self-interpretation directions of honesty, refusal, bias and subtracting/adding them);
  • on weights: task arithmetic (Ilharco et al., ICLR 2023): adding to the weights the difference between a fine-tuned model and the base model — the same “add a direction” gesture moved from one space to another, composable (adding two tasks, canceling one by subtraction).

Common limits: empirical choice of layer and \alpha, non-monotone effects, fragile out-of-distribution generalization — and no support guarantee: to truly forbid a format, only ch. 3 applies.

5. RLHF: control in behavior space

RLHF was presented as alignment in Large Language Models ch. 5, taught in the same period; here we reread it as a control mechanism. Its closed form is a lemma of Year 1, recalled below; the chapter then adds the reward model, DPO and one GRPO step, and shows that RLHF is — mathematically — the twin of classifier-free guidance in ch. 7. This double reading is the module’s synthesis point.

Theorem 5.1 — RLHF = exponential guidance of the output law (recall) The alignment program with KL penalty reads \pi^* = \arg\max_{\pi}\ \mathbb{E}_{y \sim \pi(\cdot \mid x)}\big[r(x, y)\big] \;-\; \beta\, \mathrm{KL}\big(\pi(\cdot \mid x)\,\|\,\pi_{\mathrm{ref}}(\cdot \mid x)\big). Its unique solution is

Key result — closed form of the KL-regularized policy \pi^*(y \mid x) \;=\; \frac{1}{Z(x)}\, \pi_{\mathrm{ref}}(y \mid x)\, \exp\big(r(x, y)/\beta\big), \qquad Z(x) = \sum_{y'} \pi_{\mathrm{ref}}(y' \mid x) e^{r(x, y')/\beta}.

Proof. This is the KL-regularised policy improvement lemma of Reinforcement Learning, ch. 6, with \pi_0 = \pi_{\mathrm{ref}}(\cdot \mid x) and answers y in place of actions. In one line: writing r = \beta \log\frac{\pi^*}{\pi_{\mathrm{ref}}} + \beta \log Z turns the objective into \beta \log Z - \beta\,\mathrm{KL}(\pi \,\|\, \pi^*), which Gibbs’ inequality maximizes at \pi^* only.

Control reading: the aligned policy is the reference law reweighted by an exponential factor in the reward, exactly as CFG reweights p(x_t) by p(c \mid x_t)^w (ch. 7).

1/\beta, the inverse temperature of the reward, plays the role of the guidance strength w, and the KL is the budget of allowed deviation — high fidelity to r, low diversity if \beta is small. ∎

The closed form needs a reward. In RLHF it is learned from human comparisons between two answers.

Definition 5.2 — Reward model (Bradley–Terry) A labeler sees a prompt x and two answers and prefers y_w to y_l. The Bradley–Terry model posits \mathbb{P}(y_w \succ y_l \mid x) = \sigma\big(r_\phi(x, y_w) - r_\phi(x, y_l)\big), and the reward model r_\phi is trained by maximum likelihood on the comparisons: \mathcal{L}_{\mathrm{RM}}(\phi) = -\,\mathbb{E}_{(x, y_w, y_l)}\Big[\log \sigma\big(r_\phi(x, y_w) - r_\phi(x, y_l)\big)\Big]. Only differences of rewards enter: r_\phi + f(x) predicts the same preferences. This invariance is what lets DPO drop the term \beta \log Z(x).

Proposition 5.3 — DPO: the same solution, without a reward model By rewriting r = \beta \log \frac{\pi^*}{\pi_{\mathrm{ref}}} + \beta\log Z, and substituting into definition 5.2, the term \beta \log Z(x) cancels in the difference, and the preference between y_w \succ y_l is expressed directly in policies: the DPO loss \mathcal{L}_{\mathrm{DPO}} = -\log \sigma\Big(\beta \log\tfrac{\pi_\theta(y_w \mid x)}{\pi_{\mathrm{ref}}(y_w \mid x)} - \beta \log\tfrac{\pi_\theta(y_l \mid x)}{\pi_{\mathrm{ref}}(y_l \mid x)}\Big) is the likelihood of the preferences under the closed form of theorem 5.1: DPO learns the same exponential guidance by direct regression on pairs.

PPO and GRPO reach the same optimum by sampling instead of regression. One step of GRPO, by hand, shows the mechanism.

Example 5.4 — One GRPO step on a verifiable reward Prompt x: a short arithmetic question. Sample a group of G = 4 answers from the current policy \pi_{\theta_{\mathrm{old}}}; an exact-match check gives the rewards (1, 0, 0, 1).

  1. Group-relative advantages: the group mean is 0.5 and the (population) standard deviation 0.5, so the advantages A_i = (r_i - 0.5)/0.5 are (+1, -1, -1, +1). No critic is needed: the group is its own baseline.
  2. Clipped objective: with the ratio \rho_i = \frac{\pi_\theta(y_i \mid x)}{\pi_{\theta_{\mathrm{old}}}(y_i \mid x)}, maximize the group average of \min\big(\rho_i A_i,\ \mathrm{clip}(\rho_i, 1 - \epsilon, 1 + \epsilon)\, A_i\big) \;-\; \beta\, \widehat{\mathrm{KL}}\big(\pi_\theta \,\|\, \pi_{\mathrm{ref}}\big).
  3. First gradient: at \theta = \theta_{\mathrm{old}} every \rho_i = 1, so the gradient of the first term is the group average of A_i \nabla_\theta \log \pi_\theta(y_i \mid x). It raises the two correct answers and lowers the two wrong ones.
  4. Trust region: with \epsilon = 0.2, an answer stops contributing once its ratio leaves [0.8, 1.2] in the direction of its advantage.

The clip and the KL term are the per-step version of the KL budget of theorem 5.1. PPO does the same with a learned critic in place of the group mean.

Reward hacking: when control misses its target The reward is a spec; the model optimizes the spec, not the intention. The mechanism (well documented): the closed-form solution 5.1 concentrates mass on the peaks of r — including artifactual peaks (long answers, sycophancy, formats favored by the reward model).

The KL brakes (budget!), without forbidding: as \beta \to \infty (KL budget zero), \pi^* = \pi_{\mathrm{ref}}; as \beta \to 0, collapse onto the argmax of r. Same structure as the CFG fidelity/diversity trade-off — ch. 9 for the measurement, ch. 10 for the attack (exploiting the rewarder’s artifacts is a control hijack).

6. Watermarking: proving the origin of a text

Provenance constraint (def. 1.1 iii): modify the generation so that outputs carry a secret statistical mark, verifiable without wiggle room. The green/red scheme of Kirchenbauer et al. (ICML 2023) is the most taught because its test can be proved at the M2 level; its canonical statement on this site is Large Language Models, Theorem 9.3, with the same symbols. This chapter recalls the test, then spends its time on what the LLM course does not cover: power and sample size, distortion-free schemes, and the bridge with audio watermarking (Speech Technology, ch. 9) and with ch. 9 of the Explainability module.

Definition 6.1 — Green/red watermark (Kirchenbauer et al., 2023) Key: secret k.

At every step: one hashes the previous token with k (PRF h_k), the result serves as a pseudo-random seed to partition the vocabulary: a green list G_k(y_{t-1}) of fraction \gamma (typically \gamma = 0.5), the rest in the red list.

Generation: before the softmax, one adds \delta to the green logits (typ. \delta = 2): \ell^{(t)}_v \leftarrow \ell^{(t)}_v + \delta \cdot \mathbf{1}\big[v \in G_k(y_{t-1})\big].

Detection: knowing k, one recounts the greens.

Theorem 6.2 — The z-test (H0: unmarked text) Let a suspect text of T tokens contain s_G = \sum_{t=1}^T \mathbf{1}\big[y_t \in G_k(y_{t-1})\big] green tokens, and form the statistic

Key result — watermark z-score z \;=\; \frac{s_G - \gamma T}{\sqrt{T\, \gamma (1 - \gamma)}}.

Under the null hypothesis “text written without knowledge of k” (hence human, or an unmarked model), z converges in law to \mathcal{N}(0, 1) as T \to \infty, and one rejects H_0 at threshold \alpha if z > \Phi^{-1}(1 - \alpha).

Proof.

  1. Law under H0. For a text that was not generated according to the lists, the membership of y_t in the pseudo-random green list is a Bernoulli(\gamma) draw (the PRF heuristic). Hence s_G \sim \mathrm{Bin}(T, \gamma), neglecting repeated contexts.

  2. Normality. \mathbb{E}[s_G] = \gamma T and \mathrm{Var}(s_G) = T\gamma(1-\gamma); the De Moivre–Laplace theorem (binomial CLT, Refresher Statistics ch. 6) gives z \Rightarrow \mathcal{N}(0,1).

  3. Threshold. P(false positive) = \alpha: with z_{\mathrm{threshold}} = 4, \alpha \approx 3.2 \times 10^{-5} — a human text is accused once in ~30,000.

  4. Power under H1. For a marked text, each step draws a green with probability p_\delta > \gamma (the bump \delta favors greens); \mathbb{E}[z \mid H1] \approx (p_\delta - \gamma)\sqrt{T}/\sqrt{\gamma(1-\gamma)}, which grows in \sqrt{T}.

    With \gamma = 0.5, \delta = 2, p_\delta \approx 0.7–0.8 for a real model, and T = 200, \mathbb{E}[z] \approx 5.7–8.5 — detection is nearly certain. ∎

Why 0.7–0.8 and not more? If the logits were i.i.d. and independent of the green list, the law of large numbers over a large vocabulary would give p_\delta \to \frac{\gamma e^\delta}{\gamma e^\delta + 1 - \gamma} \approx 0.88 \qquad (\gamma = 0.5,\ \delta = 2). Real models are often nearly certain of the next token, and a bump of \delta cannot move such a low-entropy step: the watermark only writes where the model hesitates.

Example 6.3 — The test in numbers (exercise 2 in full) T = 200, \gamma = 0.5. A marked text observes s_G = 150 (75% greens): z = (150 - 100)/\sqrt{200 \times 0.25} = 50/\sqrt{50} \approx 7.07 — massive rejection of H0.

A typical human text would have s_G \in [87, 113] at 95% (z \in [-1.96, 1.96]).

Bonus question: how many tokens are needed to distinguish \gamma = 0.5 from p_\delta = 0.6 at level 5% (two-sided, as above) with power 0.9? The usual sample-size formula for a proportion gives T \approx \big(\Phi^{-1}(0.975)\sqrt{0.5 \times 0.5} + \Phi^{-1}(0.9)\sqrt{0.6 \times 0.4}\big)^2 / (0.6 - 0.5)^2 = (0.98 + 0.63)^2 / 0.01 \approx 260.

The required length scales as (p_\delta - \gamma)^{-2}: halving the bias toward green tokens multiplies by four the length of text needed to detect it — this is the scaling law of watermarking.

The green/red scheme distorts the law: it shifts mass toward greens. A second scheme, due to Aaronson (2022), marks the text without changing the law of any single step.

Proposition 6.4 — Exponential-minimum (Gumbel) sampling is distortion-free At step t, let p = p_\theta(\cdot \mid y_{<t}), and let the key and the recent context give one pseudo-random number r_v \in [0, 1] per token v, treated as i.i.d. uniform. Emit y_t = \arg\max_{v}\ r_v^{1/p_v}.

  1. No distortion: over the draw of the r_v, \mathbb{P}(y_t = v) = p_v for every v.
  2. Detection: with the key, compute the score S = \sum_{t=1}^T -\log\big(1 - r_{y_t}\big). Under H0 it follows the law \mathrm{Gamma}(T, 1): mean T, variance T. Marked texts score higher, because the emitted tokens tend to have large r_v.

Proof.

  1. Set E_v = -\log r_v: these are i.i.d. exponential variables of rate 1.
  2. Maximizing r_v^{1/p_v} is minimizing E_v / p_v, and E_v / p_v is exponential of rate p_v.
  3. The minimum of independent exponentials of rates p_v is reached at v with probability p_v / \sum_u p_u = p_v: the step law is exactly p.
  4. Under H0 the text does not depend on the key, so each r_{y_t} is uniform and -\log(1 - r_{y_t}) is exponential of rate 1. The sum of T independent such terms is \mathrm{Gamma}(T, 1). ∎

Two caveats follow from the proof. A step where the model is certain (p_v = 1) emits its token whatever r, so it contributes an unmarked \mathrm{Exp}(1) term: as for green/red, the signal lives in the entropy. And for a fixed key and a fixed prompt, generation is deterministic: “distortion-free” holds over the keys, not across repeated samples of the same prompt — a diversity cost that ch. 9 can measure.

Proposition 6.5 — The family: distortion, robustness, undetectability Three other descendants structure the field.

  1. Unigram (Zhao et al., 2023): the green list is fixed (context-independent) — robust to paraphrase (tokens survive reordering), at the price of lower detectability at given T.
  2. Kuditipudi et al. (TMLR 2024): the key is a long random sequence, and token t is drawn from the model’s law with the t-th key element (inverse transform or exponential minimum). Detection aligns the text with the key by an edit distance, so insertions and deletions only shift the alignment: distortion-free and robust to edits.
  3. SynthID-Text (Dathathri et al., Nature 2024): tournament sampling — several candidate tokens are drawn from the model and a keyed function picks the winner, match after match. It is deployed in production at Gemini’s scale, with a test aggregated over the text.

In contrast: the negative result of Sadasivan et al. (2023) — against a paraphraser good enough, every detector (watermark included) tends toward blindness.

Christ, Gunn & Zamir (2024) show the other extreme: a cryptographic watermark can be made undetectable without the key (marked outputs are computationally indistinguishable from the model’s), but such constructions are fragile to edits. Ch. 10 returns to this in attack mode.

Tuning: \gamma, \delta, and the triple trade-off Increasing \delta → easy detection (p_\delta \to 1) but degraded text (the choice is biased toward greens even when a red was the “right” word); decreasing \gamma → rare green lists, a sharper signal but a stiffer constraint on quality.

In production one targets \gamma = 0.25-0.5, \delta = 1-2: imperceptible quality loss (evaluated by perplexity and human tests), z > 4 reached from T \approx 50-100. The same bipolar tuning signal quality / law fidelity structures audio watermarking (WavMark, AudioSeal — cf. Speech Technology module ch. 9): two modalities, one theory.

7. Controlling diffusions: CFG, ControlNet, inversion

Control of diffusion models was taught in Year 1 (Multimodal GenAI, ch. 4): CFG with its proof, and the ControlNet formula. Here we recall both in a few lines, state precisely what the CFG identity does and does not guarantee, prove why ControlNet’s zero-convolutions do not block learning, and spend the rest of the session on editing real images by inversion.

7.1. CFG: recall, and what the identity does not say

Theorem 7.1 — CFG is an exponential reweighting at each noise level (recall of Multimodal GenAI, Theorem 4.1) Write \hat\epsilon_c = \epsilon_\theta(x_t, t, c) and \hat\epsilon_u = \epsilon_\theta(x_t, t, \varnothing) for the noises predicted with and without conditioning, and \hat\epsilon_w = \hat\epsilon_u + w\,(\hat\epsilon_c - \hat\epsilon_u) for the CFG prediction (w = 1: conditional model, w = 0: unconditional). Since each prediction is a score up to the factor -\sqrt{1 - \bar\alpha_t}, at every noise level t the CFG combination is the score of the reweighted law

Key result — CFG reweights each noisy marginal p_{t,w}(x_t \mid c) \;\propto\; p_t(x_t \mid c)^w \, p_t(x_t)^{1-w}.

By Bayes’ rule its score is \nabla \log p_t(x_t) + w\,\nabla \log p_t(c \mid x_t): classifier guidance with weight w, obtained without a classifier by training one network with conditioning dropout.

Proof. Proved in Multimodal GenAI, 4.1: the combination is (1-w)\hat\epsilon_u + w\hat\epsilon_c, and a weighted sum of scores is the score of the weighted product of densities. ∎

Per noise level, not for the final image The identity holds at each t separately. But the family p_{t,w} is not obtained by noising one single law: noising p_0(x \mid c)^w p_0(x)^{1-w} does not give p_t(x \mid c)^w p_t(x)^{1-w}.

A DDPM or DDIM sampler driven by \hat\epsilon_w therefore does not sample p_0(x \mid c)^w p_0(x)^{1-w} exactly (Chidambaram et al., 2024; Bradley & Nakkiran, 2024, who read CFG as a predictor–corrector).

So the twin of theorem 5.1 — the same exponential family, with w \leftrightarrow 1/\beta — is exact noise level by noise level, and only a good heuristic for the law of the final output.

7.2. ControlNet: spatial control, without breaking the pre-training

Proposition 7.2 — Zero-convolutions give an identity start without a dead gradient (Zhang, Rao & Agrawala, ICCV 2023) Let F(x ; \Theta) be a frozen UNet block acting on the activation x. ControlNet branches off a trainable copy with parameters \Theta_c, initialized at \Theta, and connects it through two zero-convolutions Z_1, Z_2 (1\times1 convolutions with zero weights and biases at initialization), as recalled from Multimodal GenAI, 4.4: y \;=\; F(x;\Theta) \;+\; Z_2\Big(F\big(x + Z_1(c;\Theta_{z_1});\ \Theta_c\big);\ \Theta_{z_2}\Big), where c is the control map (Canny edges, depth, skeletal pose…). At initialization, y = F(x;\Theta), yet the gradient with respect to the weights W_2 of Z_2 is nonzero.

Proof.

  • The copy sees the normal input. At initialization Z_1(c) = 0, so the copy receives x and outputs its pretrained activations h_c = F(x;\Theta_c) = F(x;\Theta), which are nonzero.

  • Identity property at the start. Z_2(h_c) = W_2 \, h_c = 0 since W_2 = 0 — the branch outputs exactly zero, and the composed model is identically the pre-trained model: fine-tuning starts from the initial quality, without “catastrophic shift”.

  • The gradient does not vanish. The derivative of the output with respect to W_2 is \partial y / \partial W_2 = h_c \neq 0 (for a 1\times1 convolution, the outer product of the upstream gradient with h_c).

    The first update pulls W_2 away from zero, which then unlocks the gradients toward \Theta_c and Z_1 (which were zero as long as W_2 = 0, by the chain rule).

Compare the naive alternative (branching the copy directly, without Z_2): at step 0, the copy’s activations are added to those of the frozen UNet, and the output is no longer the pretrained one. If the branch is a freshly initialized network, uncontrolled noise is added instead; either way, the coherence of the output is destroyed for many steps. ∎

Why a “copy” and not a “new network” The copy inherits the pre-trained features: control learns the correspondence control map → existing rich features, not vision from scratch — hence the data efficiency (a few thousand pairs suffice for a new type of control). This is a general pattern of the module: condition around a frozen model and protect the interface with an identity initialization (the mask of ch. 3 is the exact analogue for discrete slots: allow only what preserves the invariant).

7.3. Editing a real image: inversion and null-text

To edit a real image with a text-to-image model, one first needs the noise that the model would turn into this exact image. DDIM is deterministic, so it can be run backwards; the difficulty is that guidance breaks the reversal.

Proposition 7.3 — DDIM inversion and its failure under CFG DDIM defines a deterministic step linking x_t and x_{t-1} via the prediction \hat x_0(x_t, c); inversion traverses the relation backwards (reminder: Multimodal GenAI, 4.2): x_{t+1} = \sqrt{\bar\alpha_{t+1}}\, \hat x_0(x_t, c) + \sqrt{1 - \bar\alpha_{t+1}}\; \hat\epsilon_c(x_t, c).

  1. The approximation. The exact reversal would need the noise predicted at x_{t+1}, which is unknown; one uses the noise predicted at x_t. The error per step is small when the prediction changes little between neighbouring steps.
  2. Why CFG breaks it. Editing needs a large guidance weight (w \approx 7.5 for Stable Diffusion). The guided prediction multiplies the difference \hat\epsilon_c - \hat\epsilon_u by w, so it varies much faster from one step to the next, and the per-step errors are amplified and accumulate.
  3. The symptom. Inverting with w = 1 and regenerating with w = 7.5 does not give the original image back: the reconstruction drifts.

Definition 7.4 — Null-text inversion (Mokady et al., CVPR 2023) Keep the prompt embedding c and the guidance weight w fixed, and optimize instead one null embedding c_\varnothing^{(t)} per step.

  1. Pivot. Run DDIM inversion with w = 1, where it is accurate, to get the trajectory x^*_T, \dots, x^*_0, where x^*_0 is the (encoded) real image.
  2. Optimization. Set \bar x_T = x^*_T. For t = T, \dots, 1, write x_{t-1}(\bar x_t, c_\varnothing^{(t)}, c) for one guided DDIM step with weight w, and run about ten gradient steps on \min_{c_\varnothing^{(t)}}\ \big\|\, x^*_{t-1} - x_{t-1}\big(\bar x_t,\ c_\varnothing^{(t)},\ c\big) \big\|^2 , initialized at the previous step’s null embedding; then set \bar x_{t-1} to this guided step.
  3. Result. The guided trajectory now follows the pivot, so regenerating with the per-step embeddings reproduces the real image at full guidance.

Only the unconditional branch depends on c_\varnothing^{(t)}, so the gradient flows through one of the two network passes of each guided step. Editing (Prompt-to-Prompt: substituting the cross-attention maps; InstructPix2Pix: learning editing on synthetic data) then operates along this faithful trajectory, by changing the prompt while keeping the optimized null embeddings.

Example 7.5 — CFG by hand (pen and paper, on a single step) Vocabulary of 3 artistic “directions”, logits of step t without conditioning: (\text{painting}: 2.0,\ \text{photo}: 1.5,\ \text{3D}: 0.5); with condition “watercolor”: (3.0,\ 0.5,\ 0.5).

  • Without guidance the softmax of u is \approx (0.55,\ 0.33,\ 0.12).
  • At w = 3: guided logits u + w(c - u) = (1-w)\,u + w\,c = (5.0,\ -1.5,\ 0.5) — softmax \approx (0.988,\ 0.001,\ 0.011).

In logit space the softmax of the combination is proportional to p_u^{1-w} p_c^{w}, the discrete form of theorem 7.1. The target style crushes the distribution; w = 8 → a single mode survives: the curve of ch. 9, readable on a single step. Graph Generative Models (period 2) reuses these numbers as a molecular CFG, in its example 7.3.

8. Controlling graph generators

Synthesis chapter. Graph generators were introduced in Year 1 (Graph ML, ch. 9, sections 9.3–9.6); Graph Generative Models develops them in depth, but only in period 2, after this course. So this chapter is self-contained: half a page per model (8.1), then their controls read through the grid of ch. 2 (8.2), to show that the theory of control there is identical to that of text and images.

8.1. Three generators, in half a page each

Definition 8.1 — Three molecular graph generators A molecule is a graph whose nodes carry atom types and whose edges carry bond orders; each atom v has a maximal valence, and r_v denotes its remaining valence during generation.

  1. NeVAE (Samanta et al., AAAI 2019; Graph ML 9.3): a VAE. A GNN encoder maps the molecule to one latent vector per node; the decoder samples the atom types, then adds bonds one at a time, each a categorical choice of a pair of atoms and a bond order, while it updates the remaining valences r_v.
  2. GraphAF (Shi et al., ICLR 2020): an autoregressive normalizing flow. The molecule is a sequence of decisions — a new atom, then its bonds to earlier atoms. Each discrete decision x_t (a one-hot vector) is dequantized, \tilde x_t = x_t + u with u uniform on [0,1)^K, and mapped to a Gaussian code by an affine transformation whose parameters a graph network computes from the partial graph: z_t = (\tilde x_t - \mu_t) \odot \sigma_t^{-1}. Generation draws z_t \sim \mathcal{N}(0, I), inverts \tilde x_t = \mu_t + \sigma_t \odot z_t and keeps the argmax category. The Jacobian is triangular, so the likelihood is exact.
  3. DiGress (Vignac et al., ICLR 2023; Graph ML 9.5): discrete diffusion on node and edge categories. The forward process moves every category toward the marginal distribution of the data by a transition matrix, q(x_t \mid x_0) = \mathrm{Cat}(x_t;\ x_0 \bar Q_t) for one-hot rows; a graph transformer learns to predict the clean graph from a noisy one with a cross-entropy loss, and sampling iterates the resulting posteriors.

8.2. Their controls, on the grid of ch. 2

Proposition 8.2 — Three controls, three families, one grid

  1. Hard constraint: chemical valence. Each decoding step masks the bonds b with b > r_u or b > r_v. NeVAE’s masks remove valence violations by construction, without post-processing; GraphAF resamples a bond that breaks a valence and reaches 100% validity with this check (68% without it).

    This is word for word proposition 2.2: validity guaranteed by construction, and a law renormalized step by step over the legal bonds — close to the conditional law only when the model already gives little mass to illegal bonds;

  2. Property optimization: RL fine-tuning. To maximize a property Q(G) (penalized logP, QED), GraphAF fine-tunes the pre-trained flow as a policy with a PPO-type policy gradient, as GCPN does (You et al., NeurIPS 2018). The reward is Q on the finished molecule, plus intermediate penalties for invalid steps.

    Q is computed by a chemistry toolkit on a discrete graph and is not differentiable in z_t: this is the behavior-space control of ch. 5, not guidance. Gradient ascent in a latent space needs a differentiable surrogate predictor of Q, as in the latent optimization of JT-VAE (Jin, Barzilay & Jaakkola, ICML 2018);

  3. Property conditioning during sampling: regressor guidance. DiGress trains a regressor g_\eta to predict the property from noisy graphs. At each denoising step it reweights the model’s posterior by a factor that favors graphs whose predicted property is close to the target y: \tilde p(G_{t-1} \mid G_t, y) \;\propto\; p_\theta(G_{t-1} \mid G_t)\, p_\eta(y \mid G_{t-1}), with p_\eta approximated to first order through the gradient of g_\eta with respect to the one-hot encoding of G_t. This is classifier guidance (theorem 7.1, its Bayes form), on discrete states; classifier-free variants for graphs came later.

Two further controls complete the grid. The first, extending an imposed scaffold, is in the DiGress paper itself (its Sec. 5 and Appendix E): after every reverse step, the scaffold’s nodes and edges are reset to their given values. This is the mixing rule of RePaint (Lugmayr et al., CVPR 2022) for image inpainting (Multimodal GenAI, 4.4), with no retraining, except that the paper mixes in the clean scaffold where RePaint mixes in a copy noised to the current step.

It guarantees the scaffold, a hard constraint on a subgraph, but in general not the exact conditional law of the rest of the graph: the paper’s Fig. 8 reports occasional long-range inconsistencies and suggests a resampling like RePaint’s as a possible remedy.

The second, text-to-graph generation, conditions on an LLM’s encoding of a description (Graph ML 9.7, Graph Generative Models ch. 7).

Control Mechanism (ch. 2) Where (Year 1 → period 2) Text analogue Image analogue
Chemical validity mask (stepwise renormalization) NeVAE (Graph ML 9.3), GraphAF (8.1) automaton of ch. 3 —
Target property Q RL fine-tuning (behavior space) GraphAF, after GCPN RLHF (ch. 5) reward fine-tuning
Property during sampling regressor guidance DiGress (Graph ML 9.5) steering (ch. 4) classifier guidance (ch. 7)
Imposed scaffold inpainting (hard, on a subgraph) DiGress, its Appendix E (Graph ML 9.5, Graph Gen. ch. 5) forced prefix inpainting
Text → graph heavy conditioning (LLM) Graph ML 9.7, Graph Gen. ch. 7 prompting full text-to-image

What graphs teach control Two specific lessons.

  1. Local constraints (valence) are trivially masked, global constraints (connectivity, ring size) are not: the corresponding automaton would be exponential — the search for “tractable global constraints” is open;
  2. the evaluation of control is the most mature there (validity/uniqueness/novelty + FCD; Graph ML 9.6, then Graph Generative Models ch. 6) — it is the template of ch. 9.

9. Evaluating control: fidelity versus diversity

Controlling without measuring is believing. This chapter sets the protocol: two axes (fidelity, diversity), one curve (the strength sweep), one decomposition (precision/recall), and a bound showing that the trade-off is structural, not an engineering defect.

Definition 9.1 — Fidelity and diversity Control fidelity: \mathrm{Fid}(S) = \frac{1}{n}\sum_i \mathbf{1}[y_i \in S] (pass rate; or a continuous metric — property score, similarity to the prompt).

Diversity: mean intra-batch distance \mathrm{Div} = \frac{2}{n(n-1)}\sum_{i<j} d(y_i, y_j) (self-BLEU for text, LPIPS distance for images, Tanimoto distance between molecular fingerprints for molecules); or entropy of the effective law.

Quality in the data-fidelity sense: FID (recall of the Multimodal GenAI module ch. 7), perplexity under a reference model.

Theorem 9.2 — The trade-off is structural (entropy bound) Let S \subset \mathcal{Y}^* be the admissible set (|S| = m finite).

For sequences, consider outputs of at most L tokens, padded with EOS to length exactly L, over a vocabulary of size k that counts EOS. They form a subset of \mathcal{Y}^{L}, so m \leq k^L.

The maximal entropy H_{\max} on this space is L \log k, reached by the uniform law.

Every law \tilde p supported on S satisfies

Key result — entropy ceiling of a constrained law H(\tilde p) \;\leq\; \log m \;=\; H_{\max}(\mathcal{Y}^{L}) \;-\; \log\frac{k^L}{m}.

Proof. Entropy is maximal for the uniform law (Gibbs’ inequality: for every p on S, \mathrm{KL}(p \,\|\, \mathrm{Unif}_S) = \log m - H(p) \geq 0, with equality iff uniform).

Support constraint → entropy ceiling lowered by \log(k^L/m): each division of the number of admissible outputs by e costs 1 nat of maximal diversity.

Guidance acts likewise but smoothly: p_w \propto p^{1-w}\mathrm{score}(c)^w concentrates mass on the modes compatible with c — the effective entropy decreases monotonically in the usual cases (theorems 5.1 and 7.1: the KL from the start is exactly the price paid); hence the curve. ∎

Proposition 9.3 — The control curve (protocol) For each strength w \in \{0, 0.5, 1, 2, 4, 8, \dots\} (or the watermark’s \delta, steering’s \alpha, RLHF’s \beta^{-1}): generate a fixed batch (same seeds), measure (\mathrm{Fid}(w), \mathrm{Div}(w)), plot the trajectory.

Reading:

  1. a method dominates if its curve is above/to the right of another’s everywhere;
  2. the “elbow” (fidelity stops growing, diversity collapses) is the recommended tuning point;
  3. complete with the precision/recall decomposition (Kynkäänniemi et al., NeurIPS 2019): precision measures the quality of the occupied modes, recall the coverage of the data’s modes — over-guidance kills recall (abandoned modes) before precision.

Classic anti-protocol: plot only fidelity (“100% valid JSON!”) and keep silent that the model now emits only three templates — mode collapse, control version.

Example 9.4 — Toy curve, by hand Law over 4 outputs with probabilities (0.4,\ 0.3,\ 0.2,\ 0.1); exponential control p_w \propto p\, e^{w c} with score c = (3,\ 3,\ 0,\ 0), so that the admissible set is S = \{1, 2\} (m = 2).

  • At w=0: entropy 1.28 nats, fidelity \mathrm{Fid} = p(S) = 0.70.
  • At w=1: weights \propto (8.03,\ 6.03,\ 0.2,\ 0.1) \to probabilities (0.56,\ 0.42,\ 0.014,\ 0.007), entropy 0.78 nats, fidelity 0.979.
  • At w=2: weights (161.4,\ 121.0,\ 0.2,\ 0.1) \to (0.571,\ 0.428,\ 0.0007,\ 0.0004), entropy 0.69 nats, fidelity 0.999.

As w \to \infty the law tends to (4/7,\ 3/7,\ 0,\ 0): the score does not separate the two admissible outputs, so their ratio 4:3 is preserved and the entropy tends to 0.683 nats, just below the ceiling \log m = \log 2 \approx 0.693 of theorem 9.2.

Fidelity is bought with entropy, and the price is paid almost entirely between w = 0 and w = 1. Generalize in exercise 4.

10. Attacks on control and robustness

Control is a promise; this chapter tests the promise. Four surfaces, in the module’s order: the mask, steering/RLHF, the watermark, spatial control.

Theorem 10.1 — Attacking constrained decoding (hostile content inside the format) The mask guarantees y \in S — syntax, never semantics. An injected prompt can fill a perfectly valid JSON with {"instruction": "ignore the previous rules"}; a constrained tool call can be diverted into hostile parameters (prompt injection in agents: cf. Large Language Models, 9.4, the site’s guaranteed source, deepened in period 2 by the Explainability module, ch. 5).

Second: the complexity of the grammar is a surface — an ambiguous grammar explodes the number of states (subset construction 2^{|Q|}) and allows a denial of service of the control itself; finally the tokenizer interaction: changing the tokenizer invalidates the state→tokens index (recompilation).

Defenses: downstream semantic validation (schema + bounds: \delta-constraints beyond the regular), state-size limits, server-side pre-compiled grammars (the defense in depth of Large Language Models 9.4, taken further in the Explainability module, ch. 6).

Proposition 10.2 — Attacks on the watermark (and impossibility results)

  1. Edits: paraphrase, synonym substitution, emoji/homoglyph insertion, LLM rewriting — every exchange of a green token for a red one costs \approx 1/\sqrt{T\gamma(1-\gamma)} in z; to bring \mathbb{E}[z] = 6 below 2 one must rewrite a substantial fraction of the tokens, at the price of quality;
  2. Spoofing: can an attacker without the key mark an innocent text to accuse a provider? Public-key schemes and the reliability analysis (Kirchenbauer et al., ICLR 2024 — “On the Reliability”; already referenced in the LLMs module) quantify these false accusations: key management becomes the real problem (revocation, multi-keys, aggregated tests);
  3. Undetectability: Sadasivan et al. (2023) show that a good enough paraphraser drives every detector toward chance; Christ, Gunn & Zamir (2024) show that a watermark can be made undetectable without the key, but their construction does not survive substantial edits: invisibility and robustness pull in opposite directions.

Operational conclusion: a watermark is a provenance marker, not a cryptographic proof of origin; stacking it (text + audio + image, multi-key styles) is the realistic strategy.

Attacks on guidance and steering, in brief Steering (ch. 4) has no support guarantee: a behavior removed on a test prompt reappears out of distribution (jailbreaks by rephrasing, other languages, encodings); RLHF is vulnerable to reward hacking (ch. 5) and preference attacks; CFG/ControlNet: adversarial prompts (forbidden contents rephrased), image injections (diverted inpainting, editing of persons — deepfakes), hence mandatory marking (theorem 1.3) and downstream moderation. A vast program crossing the Explainability (LLM security) and Responsible AI modules.

Definition 10.3 — Robustness budget (the quantity to remember) For a fidelity control c and a family of attacks \mathcal A, one defines the degradation

Key result — robustness budget \Delta(w) = \mathrm{Fid}(w) - \mathbb{E}_{a \sim \mathcal A}[\mathrm{Fid}(w, a)].

A robust control has flat \Delta in w; the evaluation of ch. 9 must therefore be repeated under attack — the complete protocol fits in one sentence: plot the fidelity/diversity curve, with and without an adversary, at fixed quality budget.

Exercises / Labs

  1. ★ Lab: constrained decoding on regex (the module’s lab). (a) Build the DFA of ^\d{2}/\d{2}/\d{4}$ by hand (states, co-accessible pruning), table \mathrm{Adm}(q) on a mini-vocabulary including the multi-character tokens "12/", "19"; (b) implement DfaMask (code of ch. 3) with a small GPT’s tokenizer; (c) plug in as a HuggingFace LogitsProcessor and generate 1,000 dates; (d) measure the pass rate with/without mask and the time overhead compared to free generation.

    Proof. Guidance (expected results): without constraint, the pass rate of a small model on the exact requested date plateaus (2026-08-26, 26/08/2026 formats mixed).

    With mask: 100% — including false but syntactically valid dates (31/02/2026): semantics requires one more layer (bounds validation), the conclusion of ch. 10 experienced in the lab.

    Overhead: ~0% (the mask is negligible next to the transformer pass); the real cost is the precomputation of the index, paid once.

    Bonus: compare the histogram of the masked months with that of rejection sampling (proposition 2.4). They differ as soon as the mask removes different amounts of mass on different paths: the bias of proposition 2.2, measured. ∎

  2. ★ The z-test in full. With \gamma = 0.5 and \delta = 2:

      1. simulate a million human texts of 200 tokens (vectorized binomial draws of s_G) and empirically verify \mathbb{P}(z > 4) \approx 3 \times 10^{-5} — with only ten thousand texts you would expect 0 or 1 exceedance;
      1. estimate p_\delta empirically by simulating the biased softmax at temperature 1 over a vocabulary of 50,000 tokens with i.i.d. Gaussian logits, of standard deviation 1 and then 2.

    Then: (c) plot the power of the test as a function of T \in [20, 500]; (d) derive the minimal T for power 0.9 at the threshold z = 4 (compare with example 6.3); (e) repeat with \gamma = 0.25 and conclude on the tuning.

    Proof. Guidance:

    • (a) the distribution of z sticks to \mathcal N(0,1) from T \geq 50 (De Moivre-Laplace); the exact binomial tail at T = 200 is about 2.5 \times 10^{-5}, slightly below the normal value;
    • (b) p_\delta \approx 0.88 for both values of \sigma: with i.i.d. logits independent of the green list, the law of large numbers gives \gamma e^\delta / (\gamma e^\delta + 1 - \gamma) whatever the variance. The values 0.7–0.8 of ch. 6 come from real models, whose low-entropy steps resist the bump;
    • (c) sigmoidal power in \sqrt{T};
    • (d) T \approx 40 with the simulated p_\delta \approx 0.88; about 100 with a real model’s p_\delta \approx 0.75;
    • (e) \gamma = 0.25 divides the variance under H0 (\times 0.75) and concentrates the signal — slightly better at fixed \delta, but lower text quality: the triple trade-off of ch. 6 is verified numerically. ∎
  3. ★ Steering step by step. On GPT-2 small, replay the two experiments of example 4.2 with their own vectors, for l \in \{2, 5, 8, 10\} and \alpha \in \{-8, -4, -2, 0, 2, 4, 8\}: (i) the weddings vector, and the frequency of wedding words; (ii) the Love–Hate vector at layer l, and the sentiment of the continuations (an off-the-shelf sentiment classifier). For both, measure the perplexity and the intra-batch diversity (self-BLEU).

    Proof. Guidance: the topic and sentiment effects are clear and quasi-linear in \alpha at small \alpha (prop. 4.3); perplexity moves little at moderate \alpha then derails.

    Diversity drops as |\alpha| grows — the same fidelity/diversity curve as CFG (ch. 9), again. Discuss: why does steering “succeed” on broad latent concepts and fail to impose a precise format (answer: full support — ch. 2). ∎

  4. ★★ Theoretical fidelity/diversity frontier. Prove the entropy bound 9.2 (Gibbs), then generalize example 9.4: arbitrary initial law, score c, plot (\mathrm{Fid}(w), H(w)) for w \in [0, 10] and verify that the curve converges to \big(\max c,\ H(p \mid \arg\max c)\big) — the corner (\max c, 0) when the maximizer of c is unique (in example 9.4 it is not, hence the limit 0.683 nats). What happens to the curve if c is noisy?

    Proof. Guidance: normalize p_w \propto p\, e^{w c} (exponential family) and write A(w) = \log \sum_y p(y) e^{w c(y)}, so that A'(w) = \mathbb{E}_w[c] and \frac{d}{dw}\mathbb{E}_w[f] = \mathrm{Cov}_w(f, c).

    Differentiating H(w) = -\mathbb{E}_w[\log p] - w\,\mathbb{E}_w[c] + A(w) gives dH/dw = -\mathrm{Cov}_w(\log p, c) - w\,\mathrm{Var}_w(c); for a uniform initial law the first term vanishes and H decreases for w > 0, otherwise it can rise briefly when c favors outputs that p makes rare.

    With noise, a plateau appears before the collapse: the analyst chooses the elbow. ∎

  5. ★★ Zero-convolution: the gradient under the magnifier. For the ControlNet branch of proposition 7.2 at initialization: (a) show that the branch output is exactly zero; (b) compute \partial y / \partial W_2 and show it is nonzero; (c) show that \partial y / \partial \Theta_c = 0 at initialization and explain why this is not a deadlock; (d) compare with random initialization (branching F_c without Z): simulate 10 descent steps on a toy task and compare the initial losses.

    Proof. Guidance:

    • (a) Z_2 = W_2 h = 0;
    • (b) \partial y/\partial W_2 = h_c \neq 0: since Z_1(c) = 0, the copy receives x and returns h_c = F(x;\Theta), the pretrained activations;
    • (c) chain rule through W_2 = 0 (the gradients toward \Theta_c and Z_1 both carry the factor W_2), unlocked as soon as W_2’s first update happens;
    • (d) the variant without zero-conv starts from a high loss and destroys the frozen model’s output — the experiment reproduces the motivation figure of the ControlNet paper. ∎
  6. ★★★ Attacking your own watermark (bonus). After lab 2: paraphrase the marked texts (via an LLM, instruction “rewrite with the same ideas”), measure the drop in z as a function of the rate of replaced tokens, and estimate the rate needed to fall below z = 2. Conclude on the sentence “a watermark is a marker, not a proof”.

    Proof. Guidance: each change that turns one green token red lowers s_G by one, hence z by 1/\sqrt{T\gamma(1-\gamma)} (prop. 10.2).

    A token replaced at random was green with probability p_\delta and is green with probability \gamma afterwards, so it lowers \mathbb E[z] by about (p_\delta - \gamma)/\sqrt{T\gamma(1-\gamma)} at its own position — and by as much again at the next position, whose green list it reseeds.

    Going from \mathbb E[z] = 7 to 2 means leaving only 2/7 of the positions marked. With the hash of the previous token, a position stays marked only if neither it nor its predecessor was replaced, with probability (1-\rho)^2 for a replacement rate \rho: hence \rho \approx 1 - \sqrt{2/7} \approx 0.47, nearly half of the tokens — the text that survives the attack is so transformed that content traceability (plagiarism) becomes the issue again, not that of the machine. Loop closed with ch. 10. ∎

Projects and assessment

The official assessment, from the fiche: not displayed — the 2026–2027 SynapseS catalogue has published no course description for this module (its S3 and S4 tracks are empty), so no modality, weight or exam is given. Everything below is therefore a proposal: one project, solo or in a group, assessed on a report and a talk, and a written exam for a final or resit session.

The projects exercise objectives O2 (generative modelling theory: the bias of masking, CFG and exponential tilting), O3 (LLMs: constrained decoding, steering, RLHF and DPO, watermarking) and O8 (trustworthy AI: provenance, attacks, robustness budgets), with O7 through the labs and O4–O5 through the graph generators of ch. 8. Exercise 1 (the automaton mask as a LogitsProcessor) is reused by the Year 2 transverse projects Y2.2, Y2.4 and Y2.5 of the projects page, and the second group project below feeds Y2.4.

Solo projects

  1. [Solo · ≈ 25 h] Paper study: “A Watermark for Large Language Models” (Kirchenbauer, Geiping, Wen, Katz, Miers & Goldstein, ICML 2023). Does the z-test keep its power on a small open model, how many edits erase the mark, and what does the mark cost in text quality?
    • Implement: the green/red scheme (definition 6.1) and the unigram variant (Zhao et al., 2023) as LogitsProcessors; the z-test (theorem 6.2); three attacks — synonym swaps, homoglyphs, paraphrase by a small instruction model.
    • Data: prompts from the “realnewslike” split of C4, as in the paper; OPT-1.3B or a smaller open model on a free GPU; the human continuations of the same documents as the null sample.
    • Deliverables: code, a 4–6 page report, a 10-minute talk. Chapters: ch. 6, ch. 9, ch. 10.
    • Success: power curves against T, \gamma and \delta with intervals; no false positive at z > 4 on at least 1,000 human texts; the drop of z against the edit rate compared with the prediction of exercise 6; the perplexity cost measured under a larger model.
  2. [Solo · ≈ 25 h] Prompt, steering or DPO: three ways to impose a formal register. At an equal quality budget, which control buys the most formality for the least loss of diversity?
    • Implement: prompting (conditioning); contrastive activation addition (Panickssery et al., ACL 2024, published under the name Rimsky) with a vector from formal/informal sentence pairs (ch. 4); a small DPO fine-tune with LoRA (proposition 5.3) on pairs ranked by a formality classifier; a sweep of each strength — prompt variants, \alpha, 1/\beta.
    • Data: news articles of CNN/DailyMail to summarize; the sentence-level formality ratings of Pavlick & Tetreault (TACL 2016) for the contrast pairs and the classifier; Qwen2.5-0.5B-Instruct.
    • Deliverables: code, a 4–6 page report, a 10-minute talk. Chapters: ch. 4, ch. 5, ch. 9.
    • Success: the three fidelity/diversity curves of proposition 9.3 on the same axes, with bootstrap intervals over 3 seeds; ROUGE against the reference summaries reported as the quality budget; the elbow of each method named and justified.
  3. [Solo · ≈ 25 h] Paper study: “Null-text Inversion for Editing Real Images using Guided Diffusion Models” (Mokady, Hertz, Aberman, Pritch & Cohen-Or, CVPR 2023). How much of the drift of DDIM inversion under guidance does null-text optimization remove, and how many inner steps does it need?
    • Implement: DDIM inversion with w = 1 and regeneration at w = 7.5, to exhibit the drift (proposition 7.3); null-text optimization (definition 7.4), with the gradient through the unconditional branch only; one Prompt-to-Prompt word swap.
    • Data: Stable Diffusion v1.4, the model of the paper, through the diffusers library, in half precision on a free 16 GB GPU; 20 captioned images of COCO 2017 validation.
    • Deliverables: code, a 4–6 page report, a 10-minute talk. Chapters: ch. 7, ch. 9.
    • Success: PSNR and LPIPS of the reconstruction for 0, 1, 5 and 10 inner steps, with intervals over the 20 images, against plain inversion at w = 7.5; three edits shown with their failure cases.

Group projects

  1. [Group of 3 · ≈ 30 h each] How biased is masked decoding? On languages small enough to enumerate, how far is the masked law from the true conditional, and what does it cost to correct it?
    • Implement: the mask of ch. 3 as a LogitsProcessor (exercise 1); the exact law p_\theta(\cdot \mid S) by scoring every element of S; the masked law from the per-step masses Z_t (proposition 2.2); rejection (proposition 2.4); sequential Monte Carlo with particles weighted by \prod_t Z_t (Lew et al., 2023); grammar-aligned decoding (Park, Wang, Berg-Kirkpatrick, Polikarpova & D’Antoni, NeurIPS 2024) as the paper study.
    • Data: three finite languages — the 366 dates of 2024 written DD/MM/YYYY, a list of 200 country names, the calls of a two-field JSON schema with enumerated values (example 3.5); GPT-2 and Qwen2.5-0.5B on a laptop CPU.
    • Split: one member on the automata and the exact enumeration; one on rejection, SMC and grammar-aligned decoding; one on the evaluation (KL, validity, diversity of ch. 9).
    • Deliverables: code, a 6–8 page report, a 15-minute talk. Chapters: ch. 2, ch. 3, ch. 9. The same question for valence masks continues in Graph Generative Models, ch. 3.
    • Success: the exact divergence between the conditional and the masked law for each language and model; every measured ratio inside the band of proposition 2.2 for the observed \varepsilon; the divergence of SMC against the number of particles, at a counted number of forward passes.
  2. [Group of 3 · ≈ 30 h each] Secure structured tool calls: a grammar-constrained agent under prompt injection. A mask guarantees valid calls; does it reduce, leave unchanged or hide the success of injections that stay syntactically valid?
    • Implement: an agent whose tool calls are constrained by their JSON schemas (example 3.5, with Outlines, XGrammar or the mask of exercise 1); indirect injections that keep every call valid (theorem 10.1); a probe of grammar complexity (compile time and states against nesting and enumerations); three defenses — semantic validation of arguments, least-privilege tools, spotlighting of untrusted content.
    • Data: the AgentDojo benchmark (Debenedetti et al., NeurIPS 2024 Datasets and Benchmarks), its banking and workspace suites; a small open instruction model with tool calling.
    • Split: the constrained tool layer; the red team (injections and complexity probe); the defenses and the evaluation.
    • Deliverables: code, a 6–8 page report, a 15-minute talk. Chapters: ch. 3, ch. 10. Builds on Large Language Models, 9.4 and its agents of ch. 8; feeds the dispatcher project Y2.4.
    • Success: utility and attack success rate without the mask, with it, then with each defense, with intervals over the tasks; the share of successful attacks whose calls were valid; a measured blow-up of states or compile time, and the limit that stops it.
  3. [Group of 4 · ≈ 30 h each] One control curve, three modalities. Does one protocol — strength sweep, fidelity/diversity curve, robustness budget — describe guidance on images, text and molecules, and where does the analogy break?
    • Implement: a CFG sweep on a small class-conditional diffusion model trained with condition dropout (ch. 7); a steering sweep on GPT-2 (ch. 4); a conditional SMILES language model trained with a property-bin token dropped 10% of the time, guided in logit space as in example 7.5 (ch. 8); the protocol of proposition 9.3 and the budget of definition 10.3, under one attack per modality.
    • Data: Fashion-MNIST, its classes as conditions; the prompts of example 4.2; ZINC250k, with RDKit for QED and validity.
    • Split: one member per modality; one on the shared harness (fidelity, diversity, precision and recall, attacks).
    • Deliverables: code, a 6–8 page report, a 15-minute talk. Chapters: ch. 4, ch. 7, ch. 8, ch. 9, ch. 10. Connects Multimodal GenAI, ch. 4 and Graph Generative Models, ch. 7.
    • Success: the three curves on normalized axes with intervals over 3 seeds; the elbow of each; at least one place where the single-step prediction of exercise 4 fails, explained.

Written exam (proposal)

Format: 2 hours, one handwritten A4 sheet of notes allowed, no electronic device; four questions, 20 points.

  1. Question (4 points). For each mechanism, give its family (definition 2.1), its guarantee and its main cost: (a) a JSON-schema mask on tool calls; (b) CFG with w = 5; (c) resampling until a validator accepts; (d) a green/red watermark. Then say when you choose a hard constraint rather than guidance. Expected:

      1. hard constraint: validity by construction, one pass plus a mask, and a law renormalized step by step, hence biased (proposition 2.2);
      1. guidance: statistical fidelity, two network passes per step, diversity lost as w grows (ch. 9);
      1. post-processing: the exact conditional law, at an expected 1/p_\theta(S \mid x) draws (proposition 2.4);
      1. guidance used for provenance: a statistical test, a quality cost that grows with \delta.
    • A hard constraint when a failure is catastrophic (a parser, a valence), guidance when it is gradual (tone, style).
  2. Question (6 points). A green/red watermark uses \gamma = 0.25.

      1. A text of 400 tokens contains 150 green tokens: compute z and conclude at the threshold z = 4.
      1. How many green tokens must an attacker exchange for red ones to bring z below 4? Assume that each exchange lowers s_G by exactly one.
      1. With the exponential-minimum scheme instead, another text of 400 tokens has score 480. Conclude, first with a normal approximation of the null law, then with its exact tail, about 8 \times 10^{-5}.

    Expected:

      1. the standard deviation is \sqrt{400 \cdot 0.25 \cdot 0.75} = \sqrt{75} \approx 8.66, so z = 50 / 8.66 \approx 5.77 > 4: reject H0 (one-sided p-value \approx 4 \times 10^{-9}).
      1. each exchange lowers z by 1/8.66 \approx 0.115; z < 4 requires s_G < 134.6, so s_G \leq 134: 16 exchanges.
      1. under H0 the score is \mathrm{Gamma}(400, 1), of mean 400 and standard deviation 20, so the normal approximation gives z = 4, just at the threshold. The exact tail is larger than the normal one (3 \times 10^{-5}): at that level, do not accuse.
  3. Question (5 points). Masking at each step the tokens that make a set S unreachable.

      1. Show on an example that it does not sample the conditional law p_\theta(\cdot \mid x, S).
      1. Prove that if every output of S has at most T steps and the mask never removes more than a mass \varepsilon, the masked law is within a factor (1-\varepsilon)^{\pm T} of the conditional one.

    Expected:

      1. the two-token example 2.3: the masked law gives aa the probability 0.5, the conditional law 0.05/0.55 \approx 0.09.
      1. on S the masked law is the model’s law divided by \prod_t Z_t, so the ratio is p_\theta(S \mid x) / \prod_t Z_t.
    • Each Z_t lies in [1-\varepsilon, 1], so the product over at most T steps lies in [(1-\varepsilon)^T, 1], and p_\theta(S \mid x) is an average of such products under the masked law: the ratio lies in the band.
  4. Question (5 points). Let the numbers r_v, one per token of the vocabulary, be i.i.d. uniform on [0, 1], and let p be a law on the vocabulary. Prove that y = \arg\max_v r_v^{1/p_v} has law p. Then give the null law of the detection score of proposition 6.4 over T tokens.

    Expected:

    • E_v = -\log r_v are i.i.d. exponential of rate 1, and maximizing r_v^{1/p_v} is minimizing E_v / p_v, exponential of rate p_v.
    • The minimum of independent exponentials is reached at v with probability p_v / \sum_u p_u = p_v: no distortion at each step.
    • Under H0 the text ignores the key, each r_{y_t} is uniform, each term is \mathrm{Exp}(1), and the sum is \mathrm{Gamma}(T, 1): mean T, variance T.

Grading rubric (proposal)

Criterion Weight What earns the marks
Problem formulation 15 % the control written on the grid of ch. 2: family, admissible set or target, strength parameter; assumptions stated
Correct implementation 25 % masks, guidance and tests checked first on a case with a known answer (an enumerable language, a toy law, a null sample)
Experimental rigour 25 % strength sweeps with fixed seeds, fidelity and diversity reported together, baselines at an equal compute budget, intervals
Link to the theory 15 % which result of the course (proposition 2.2, theorem 6.2, theorem 7.1, theorem 9.2) predicts what, and whether the measurement agrees
Robustness and honesty 10 % at least one attack or failure case reported (ch. 10); negative results kept
Communication and reproducibility 10 % clear report and talk; one command reproduces the main figure

References