Skip to content

Quantifier Scope

Overview

"Every linguist admires some model" has two readings: for every linguist there is some model they admire (surface scope, \(\forall\exists\)), and there is one model every linguist admires (inverse scope, \(\exists\forall\)). This example derives both from a single lexicon. Generalized quantifiers denote computations in the continuation monad, and the clause combines its subject and object computations by the monad's applicative structure, which has two evaluation orders: left to right yields surface scope and right to left yields inverse scope (Barker, 2002; Shan and Barker, 2006). The weighted chart derives exactly two sentence items for the doubly quantified sentence, carrying the two readings as logical forms, and the Try-it fits a reading preference from truth-value judgments by marginalizing the reading through the chart.

QVR source

The manifest exposes the root module.

[package]
name = "quantifier_scope"
version = "0.1.0"
modules = ["quantifier_scope"]

The continuations module adds the fragment's categories and the rules that combine quantified subjects and objects. These rules build terms in the continuation monad.

# Quantifier scope as evaluation order in the continuation monad.
#
# A generalized quantifier has type (e -> t) -> t, which is Cont(e) for
# the continuation monad Cont(A) = (A -> t) -> t at A = e. A clause whose
# subject and object both denote Cont(e) computations combines them with
# the monad's applicative structure, which has two lawful evaluation
# orders. Subject first gives surface scope, and object first gives inverse
# scope.
#
# The items are std.grammar.ccg.semantics's span(I, J, X, M): a category,
# result first, and a meaning. Each rule below writes its meaning as the
# monad operation it performs, unreduced, with
#
#   map f m   = λk. m (λy. k (f y))
#   lower m   = m (λz. z)
#   ap_LR s v = λk. s (λx. v (λg. k (g x)))     subject first
#   ap_RL s v = λk. v (λg. s (λx. k (g x)))     object first
#
# and std.grammar.ccg.semantics's normal_meaning beta-reduces a sentence's
# meaning to its reading.

import std.grammar.ccg.semantics as M

#! The fragment's categories besides S: noun phrases, nouns, and
#! Cont(A), a computation that produces an A.
export deduction signature Continuations
    extends M.Binding
    atoms NP, N, Cont, Var

#! Quote the fragment's categories and its explicit variable constructor.
#! Cont(A) is quoted as the category of its type, S/(S\A).
export meta define continuation_categories : Seq[MorphClause] !{} =
    let atoms <- M.atoms("Continuations", SeqCons("NP", SeqCons("N", SeqNil)))
    let sentence = ValueCall("M.Atom", SeqCons(ValueString("S"), SeqNil))
    let cont = MorphClause("Continuations.Cont", ValueCall("M.Over", SeqCons(sentence, SeqCons(ValueCall("M.Under", SeqCons(sentence, SeqCons(ValueVar("arg0"), SeqNil))), SeqNil))))
    let var = MorphClause("Continuations.Var", ValueCall("M.Variable", SeqCons(ValueVar("arg0"), SeqNil)))
    return SeqCons(cont, SeqCons(var, atoms))

#! The monadic combinators. A quantified noun phrase is a Cont(NP)
#! computation; a pure function maps over it, and a clause lowers its
#! computations, in one order or the other when there are two.
export deduction signature Scope
    extends Continuations
    rule map_obj : span(I, K, Fwd(A, B), F), span(K, J, Cont(B), G) |- span(I, J, Cont(A), Lam(k, App(G, Lam(y, App(Var(k), App(F, Var(y))))))) #[learnable]
    rule lower_s : span(I, K, Cont(B), G), span(K, J, Bwd(S, B), F) |- span(I, J, S, App(G, F)) #[learnable]
    rule lower_o : span(I, K, B, X), span(K, J, Cont(Bwd(S, B)), V) |- span(I, J, S, App(Lam(k, App(V, Lam(g, App(Var(k), App(Var(g), X))))), Lam(z, Var(z)))) #[learnable]
    rule surface : span(I, K, Cont(B), H), span(K, J, Cont(Bwd(S, B)), V) |- span(I, J, S, App(Lam(k, App(H, Lam(x, App(V, Lam(g, App(Var(k), App(Var(g), Var(x)))))))), Lam(z, Var(z)))) #[learnable]
    rule inverse : span(I, K, Cont(B), H), span(K, J, Cont(Bwd(S, B)), V) |- span(I, J, S, App(Lam(k, App(V, Lam(g, App(H, Lam(x, App(Var(k), App(Var(g), Var(x)))))))), Lam(z, Var(z)))) #[learnable]

The lexicon module states the categories and meanings of the words.

# The lexicon: determiners map a noun to a Cont(NP) computation, and
# every other word is a pure constant. Relations are curried object
# first, so admire y x says that x admires y.

import std.grammar.ccg.semantics as M
import quantifier_scope.continuations (Continuations)

#! The fragment's words.
export lexicon Words for Continuations
    atoms every_q, some_q, linguist_p, model_p, sleep_p, admire_p, kim, lee
    "every" : Fwd(Cont(NP), N) = every_q #[learnable]
    "some" : Fwd(Cont(NP), N) = some_q #[learnable]
    "linguist" : N = linguist_p #[learnable]
    "model" : N = model_p #[learnable]
    "sleeps" : Bwd(S, NP) = sleep_p #[learnable]
    "admires" : Fwd(Bwd(S, NP), NP) = admire_p #[learnable]
    "Kim" : NP = kim #[learnable]
    "Lee" : NP = lee #[learnable]

#! The clauses quoting the words' meanings as `M.Atom` constants.
export meta define word_constants : Seq[MorphClause] !{} =
    let clauses <- M.atoms("Words", SeqCons("every_q", SeqCons("some_q", SeqCons("linguist_p", SeqCons("model_p", SeqCons("sleep_p", SeqCons("admire_p", SeqCons("kim", SeqCons("lee", SeqNil)))))))))
    return clauses

The root module extends the semantic layer of categorial grammar to apply functors and quote chart items. It exports a program that scores sentences and a computation that normalizes their readings.

# Quantifier Scope from Evaluation Order in the Continuation Monad
#
# The grammar extends the monadic combinators of
# quantifier_scope.continuations with std.grammar.ccg.semantics's
# application, which applies a determiner to its noun and a verb to its
# object, and reads its words from quantifier_scope.words. A sentence
# with one quantifier has one derivation; a transitive sentence with two
# has exactly two, surface and inverse, and the chart's goal weight sums
# over them. `reading` gives an item's meaning in normal form, a term of
# std.syntax.lambda.

import std.semiring
import std.data as D
import std.syntax.lambda as L
import std.grammar.ccg.semantics as M
import quantifier_scope.continuations (Scope, continuation_categories)
import quantifier_scope.words (Words, word_constants)

object Term : FinSet 16

object LogWeight : Real 1

meta define scope_quote : Morph !{} =
    let categories <- continuation_categories()
    let words <- word_constants()
    let clauses <- seq_append[MorphClause](categories, words)
    return Morph(clauses)

#! The grammar: the monadic combinators, application, and the words.
deduction QScope[W = std.semiring.LogProb] : Term -> Term [start=S, depth=4] deriving (Quote[M.Sign via scope_quote])
    extends Scope, M.ReifiedBinding, M.Application per instance
    lexicon Words

#! An item's meaning in normal form: `None` for an item whose meaning
#! has a free variable, which no item of this grammar has.
define reading(item : QScope.Item) : D.Option[L.Lambda.Term] !{} =
    let sign <- QScope.Item.quote(item)
    let lf <- M.normal_meaning(sign)
    return lf

#! The grammar's contribution to a probabilistic program: the log-sum
#! over every derivation of S, and thus over both scope readings of a
#! doubly quantified sentence, of the learnable log-weights each uses.
program fit_scope : Term -> LogWeight
    let chart = parse(QScope, sentence)
    score log_Z = chart.goal_weight()
    return log_Z

export fit_scope
export reading

Understanding the model

A generalized quantifier such as "every linguist" denotes a function from properties to truth values, type \((e \to t) \to t\) (Barwise and Cooper, 1981). That is \(\mathrm{Cont}(e)\), where \(\mathrm{Cont}(A) = (A \to t) \to t\) is the continuation monad at answer type \(t\): a quantified noun phrase is a computation that will produce an individual once it is handed the rest of the sentence. A determiner maps a noun, type \(e \to t\), to such a computation, so its type is \((e \to t) \to \mathrm{Cont}(e)\), which unfolds to \((e \to t) \to ((e \to t) \to t)\).

When only one constituent is a computation, composition is the monad's map: apply the pure function under the computation, then lower by running it with the identity continuation. "Every linguist sleeps" comes out as \(\mathsf{every}(\mathsf{linguist})(\mathsf{sleep})\) and nothing else. When both the subject and the object are computations, the clause must sequence them, and the applicative application of a function computation to an argument computation can run either one first. Running the subject first gives \(\mathsf{every}(\mathsf{linguist})(\lambda x.\, \mathsf{some}(\mathsf{model})(\lambda y.\, \mathsf{admire}(y)(x)))\). Running the object first gives \(\mathsf{some}(\mathsf{model})(\lambda y.\, \mathsf{every}(\mathsf{linguist})(\lambda x.\, \mathsf{admire}(y)(x)))\). The scope ambiguity is a choice between two derivations over the same lexical entries, which is what a weighted chart can score.

Walkthrough

The application rules build an application of the functor's meaning to its argument's meaning. The determiners use this rule to combine with a noun and produce a Cont(NP) computation. The scope rules perform the following operations.

Rule Operation
map_obj Map the verb meaning \(F\) over an object computation \(G\), giving \(\lambda k.\,G(\lambda y.\,k(F(y)))\).
lower_s Pass a pure verb phrase meaning \(F\) to a quantified subject \(G\), giving \(G(F)\).
lower_o Apply the verb phrase computation to a pure subject meaning and lower the result.
surface Sequence the subject computation before the verb phrase computation and lower the result.
inverse Sequence the verb phrase computation before the subject computation and lower the result.

Write the subject computation as \(H\) and the verb phrase computation as \(\lambda k.\,G(\lambda y.\,k(F(y)))\). In the surface rule, lowering with the identity continuation reduces the clause meaning to \(H(\lambda x.\,G(\lambda y.\,F(y)(x)))\). In the inverse rule it reduces the clause meaning to \(G(\lambda y.\,H(\lambda x.\,F(y)(x)))\). The chart keeps the derivations and their unreduced meanings. The exported reading computation quotes each item and computes its normal form.

An explicit rule for the applicative unit would add a second derivation of the reading that lower_s already derives, since \(\mathrm{pure}\,f \circledast x = \mathrm{map}\,f\,x\). The Counting semiring check below verifies that each reading has one derivation. The depth=4 bound admits every category the lexicon uses.

Categories are written result first. For instance, Fwd(A, B) is \(A/B\), and Bwd(A, B) is \(B\backslash A\). The determiner constants every_q and some_q take a restrictor and a scope, while the relation admire_p takes the object before the subject. A rule conclusion introduces bound variables with Lam, and those occurrences are represented by de Bruijn indices when the item is quoted.

fit_scope parses the data parameter sentence and scores the chart's goal weight, which for a doubly quantified sentence is the log-sum over both readings. That is the unnormalized string weight with the reading summed out. The judgment model below reads the per-reading weights from the same chart.

Try it

Check the logical forms of the readings

The first block normalizes the full-sentence readings and compares them to independently constructed terms. The two doubly quantified sentences each have two distinct readings, and the other four sentences have one reading each. The closed terms use de Bruijn indices, so index zero refers to the innermost binder.

import itertools
import math
import re
from pathlib import Path

import torch
from quivers.dsl import load, loads
from quivers.qiec.structural_runtime import host_result
from quivers.structural import Term

PACKAGE = Path("docs/examples/source/quantifier_scope")
SOURCE = PACKAGE / "quantifier_scope.qvr"
program = load(SOURCE)
ded = program.deductions["QScope"]

const = lambda name: ("Const", name, ("Unknown", name))
app = lambda f, a: ("App", f, a)
lam = lambda body: ("Lam", body)
var = lambda index: ("BoundVar", index)


def local_names(term):
    """A structural term with the standard library prefix removed."""
    return (
        term.op.removeprefix("std.syntax.lambda:"),
        *(local_names(arg) if isinstance(arg, Term) else arg for arg in term.args),
    )


def normal_reading(item):
    value = program.chart_item("QScope", item)
    result = program.run("reading", value).value
    (term,) = result.fields
    return local_names(host_result(program.qiec, program, term))


def readings(sentence):
    chart = ded(sentence.split())
    return [normal_reading(item) for item, _ in chart.goal_items]


every_linguist = app(const("every_q"), const("linguist_p"))
some_model = app(const("some_q"), const("model_p"))
admires = lambda obj, subj: app(app(const("admire_p"), obj), subj)

# forall x. linguist(x) -> exists y. model(y) & admire(x, y)
SURFACE = app(every_linguist, lam(app(some_model, lam(admires(var(0), var(1))))))
# exists y. model(y) & forall x. linguist(x) -> admire(x, y)
INVERSE = app(some_model, lam(app(every_linguist, lam(admires(var(1), var(0))))))

CASES = {
    "every linguist admires some model": [SURFACE, INVERSE],
    "some model admires every linguist": [
        app(some_model, lam(app(every_linguist, lam(admires(var(0), var(1)))))),
        app(every_linguist, lam(app(some_model, lam(admires(var(1), var(0)))))),
    ],
    "every linguist sleeps": [app(every_linguist, const("sleep_p"))],
    "every linguist admires Lee": [
        app(every_linguist, app(const("admire_p"), const("lee"))),
    ],
    "Kim admires some model": [app(some_model, lam(admires(var(0), const("kim"))))],
    "Kim admires Lee": [admires(const("lee"), const("kim"))],
}

def no_redex(term):
    if term[0] == "App":
        return term[1][0] != "Lam" and no_redex(term[1]) and no_redex(term[2])
    if term[0] == "Lam":
        return no_redex(term[1])
    return True


def closed(term, depth=0):
    if term[0] == "BoundVar":
        return 0 <= term[1] < depth
    if term[0] == "Lam":
        return closed(term[1], depth + 1)
    if term[0] == "App":
        return closed(term[1], depth) and closed(term[2], depth)
    return True


for sentence, expected in CASES.items():
    chart = ded(sentence.split())
    found = [normal_reading(item) for item, _ in chart.goal_items]
    assert len(found) == len(expected) and set(found) == set(expected), sentence
    goal = float(chart.goal_weight().detach())
    assert math.isclose(goal, math.log(len(expected)), abs_tol=1e-7), sentence
    assert all(no_redex(term) and closed(term) for term in found)

The second block counts derivations in the Counting semiring and interprets the readings model-theoretically. Over every admiration relation between two linguists and two models, the inverse reading entails the surface reading and some relations make the surface reading true and the inverse reading false, as the logic requires.

# Give every rule and entry unit weight and count each reading.
def unweighted(path):
    return re.sub(r"[ \t]*#\[learnable\]", "", path.read_text())


grammar_only = unweighted(SOURCE).split("#! The grammar's contribution")[0]
count = loads(
    grammar_only.replace("std.semiring.LogProb", "std.semiring.Counting").replace(
        "M.Application per instance", "M.Application"
    ),
    modules={
        "quantifier_scope.continuations": unweighted(PACKAGE / "quantifier_scope/continuations.qvr"),
        "quantifier_scope.words": unweighted(PACKAGE / "quantifier_scope/words.qvr"),
    },
    roots=(PACKAGE,),
).deductions["QScope"]
for sentence, expected in CASES.items():
    per_reading = [int(w) for _, w in count(sentence.split()).goal_items]
    assert per_reading == [1] * len(expected), (sentence, per_reading)



def denote(term, model, env=()):
    """Interpret a logical form in a finite model."""
    tag = term[0]
    if tag == "Const":
        return model[term[1]]
    if tag == "BoundVar":
        return env[term[1]]
    if tag == "Lam":
        return lambda individual: denote(term[1], model, (individual, *env))
    return denote(term[1], model, env)(denote(term[2], model, env))


def make_model(linguists, models, admire):
    domain = linguists | models | {"kim", "lee"}
    return {
        "every_q": lambda p: lambda q: all(q(d) for d in domain if p(d)),
        "some_q": lambda p: lambda q: any(q(d) for d in domain if p(d)),
        "linguist_p": lambda d: d in linguists,
        "model_p": lambda d: d in models,
        "sleep_p": lambda d: False,
        "admire_p": lambda obj: lambda subj: (subj, obj) in admire,
        "kim": "kim", "lee": "lee",
    }


# The inverse reading entails the surface reading whenever there is a
# linguist, and not conversely: check every admiration relation between
# two linguists and two models.
L, M = {"l1", "l2"}, {"m1", "m2"}
pairs = list(itertools.product(sorted(L), sorted(M)))
separating = 0
for bits in itertools.product([False, True], repeat=len(pairs)):
    model = make_model(L, M, {p for p, b in zip(pairs, bits) if b})
    surface, inverse = denote(SURFACE, model), denote(INVERSE, model)
    assert surface or not inverse
    separating += surface and not inverse
assert separating > 0
print(f"inverse entails surface; {separating} of {2 ** len(pairs)} models separate them")

A judgment model over readings

A listener hears the sentence in a scenario, resolves its scope, and reports whether the sentence is true. The report is wrong with probability \(\epsilon\). The reading distribution is the chart's: \(p(r \mid s) = \alpha[\mathrm{S}, \phi_r] / \sum_{r'} \alpha[\mathrm{S}, \phi_{r'}]\), the weight of the item carrying logical form \(\phi_r\) over the goal weight. The truth value comes from evaluating \(\phi_r\) in the scenario. In scenario A each linguist admires a different model, so only the surface reading is true. In scenario B every linguist admires the same model, so both are. The block sets the scope rules' weights so that the chart puts 0.7 on the surface reading and simulates 800 trials from that model.

# Scenario A: each linguist admires a different model, so only the
# surface reading is true. Scenario B: everyone admires m1, so both are.
SCENARIOS = {
    "A": make_model({"l1", "l2", "l3"}, {"m1", "m2", "m3"},
                    {("l1", "m1"), ("l2", "m2"), ("l3", "m3")}),
    "B": make_model({"l1", "l2", "l3"}, {"m1", "m2", "m3"},
                    {("l1", "m1"), ("l2", "m1"), ("l3", "m1")}),
}
SENTENCE = "every linguist admires some model".split()
EPSILON = 0.1            # judgment noise: p(report the wrong truth value)
TRUE_PREFERENCE = 0.7    # p(surface reading)

terms = readings(" ".join(SENTENCE))
truth = torch.tensor([[float(denote(term, SCENARIOS[s])) for term in terms]
                      for s in ("A", "B")])                  # (scenario, reading)
surface_index = terms.index(SURFACE)


def reading_log_probs():
    """log p(reading | sentence): each reading's chart weight, normalized
    over the sentence's readings by the chart's own goal weight."""
    chart = ded(SENTENCE)
    return torch.stack([w for _, w in chart.goal_items]) - chart.goal_weight()


def preference_parameters():
    named = dict(ded.named_parameters())
    surface = next(p for n, p in named.items() if n.startswith("_rule_module.rule_") and "surface." in n)
    inverse = next(p for n, p in named.items() if n.startswith("_rule_module.rule_") and "inverse." in n)
    return surface, inverse


# Ground truth: set the scope rules' weights so the chart puts
# TRUE_PREFERENCE on the surface reading.
surface_w, inverse_w = preference_parameters()
with torch.no_grad():
    for p in ded.parameters():
        p.zero_()
    surface_w.fill_(float(torch.logit(torch.tensor(TRUE_PREFERENCE))))
true_probs = reading_log_probs().exp().detach()
assert abs(float(true_probs[surface_index]) - TRUE_PREFERENCE) < 1e-6

# Simulate: each trial draws a scenario, a reading from the chart's
# distribution, and a judgment from that reading's truth value.
torch.manual_seed(0)
N_TRIALS = 800
scenario = torch.randint(0, 2, (N_TRIALS,))
reading = torch.multinomial(true_probs, N_TRIALS, replacement=True)
p_true = torch.where(truth[scenario, reading] > 0, 1 - EPSILON, EPSILON)
judgment = torch.bernoulli(p_true)

The fit starts from zero weights and maximizes \(\sum_n \log \sum_r p(r \mid s)\, p(y_n \mid r, \text{scenario}_n)\), with the reading summed out through the chart. Scenario B trials carry no information about scope, and the marginal makes them drop out of the estimate: the fitted preference matches the closed-form maximum likelihood estimate from the scenario A trials alone, and it lies within 0.1 of the generating preference (the standard error at 400 scenario A trials is about 0.03).

# Fit: the likelihood of a judgment marginalizes the reading through
# the chart, p(y | s, scenario) = sum_r p(r | s) p(y | r, scenario).
with torch.no_grad():
    for p in ded.parameters():
        p.zero_()
judge = torch.where(truth > 0, 1 - EPSILON, EPSILON)          # p(y = 1 | scenario, r)
p_y_given_r = torch.where(judgment[:, None] > 0, judge[scenario], 1 - judge[scenario])
optim = torch.optim.Adam(list(ded.parameters()), lr=0.05)
for step in range(400):
    optim.zero_grad()
    log_marginal = torch.logsumexp(reading_log_probs() + p_y_given_r.log(), dim=1)
    (-log_marginal.sum()).backward()
    optim.step()
fitted = float(reading_log_probs().exp()[surface_index].detach())

# Only scenario A separates the readings; its closed-form maximum
# likelihood estimate is (mean judgment - EPSILON) / (1 - 2 EPSILON).
in_a = scenario == 0
closed_form = (float(judgment[in_a].mean()) - EPSILON) / (1 - 2 * EPSILON)
print(f"p(surface): true {TRUE_PREFERENCE}, fitted {fitted:.3f}, closed form {closed_form:.3f}")
assert abs(fitted - closed_form) < 0.01
assert abs(fitted - TRUE_PREFERENCE) < 0.1

Categorical perspective

\(\mathrm{Cont}\) is a strong monad, and a strong monad is the structure (Moggi, 1991) uses to model computational effects. On a non-commutative monad such as \(\mathrm{Cont}\), the two ways of using the strength to combine two computations give two applicative structures that differ in evaluation order. Quantification is such an effect: a quantified noun phrase acts on its continuation. The chart's surface and inverse rules are the two applicative applications followed by lowering at the answer type, and the LogProb chart sums over them as alternative derivations, so the goal weight sums over readings. Dividing each item weight by their total gives the conditional reading distribution. The effect-driven interpretation program of (Bumford and Charlow, forthcoming) develops this functorial view of composition in general.

Connections

The fragment reuses the slash categories of the type-logical example and the normal-form discipline of the Montague NLI example, whose prover could take these readings as premises.

Cited sources

Chris Barker. Continuations and the Nature of Quantification. Natural Language Semantics, 10(3):211–242, 2002. doi:10.1023/A:1022183511876.

Chung-chieh Shan and Chris Barker. Explaining Crossover and Superiority as Left-to-Right Evaluation. Linguistics and Philosophy, 29(1):91–134, 2006. doi:10.1007/s10988-005-6580-7.

Jon Barwise and Robin Cooper. Generalized quantifiers and natural language. Linguistics and Philosophy, 4(2):159–219, 1981. URL: https://link.springer.com/article/10.1007/BF00350139, doi:10.1007/BF00350139.

Eugenio Moggi. Notions of Computation and Monads. Information and Computation, 93(1):55–92, 1991. URL: https://www.sciencedirect.com/science/article/pii/0890540191900524, doi:10.1016/0890-5401(91)90052-4.

Dylan Bumford and Simon Charlow. Effect-Driven Interpretation: Functors for Natural Language Composition. Elements in Semantics. Cambridge University Press, forthcoming. ISBN 9781009285377. Forthcoming; publisher lists expected 2026 publication. Author preprint: arXiv:2504.00316. URL: https://www.cambridge.org/core/elements/abs/effectdriven-interpretation/56671E539160AAA1DACF8555B82A2FE4.