Pragmatics, Implicature, and Presupposition › Code Implementation: Building and Probing the Toy Model
Language AI HandbookAll chapters The implementation is deterministic and CPU-only. It uses NumPy and no random sampling. The first cell imports NumPy and the book plotting helpers. The model itself contains no randomness, so no random seed is needed for the computation.
States, Utterances, and Literal Meanings
We encode the literal semantics as a matrix with one row per state and one column per utterance. A 1 means the utterance is true in that state.
PythonIn [3]Expand
states = ["0 passed", "1 passed", "2 passed", "3 passed"]
utterances = ["none", "some", "all"]
# Rows are states, columns are utterances.
# Stipulated inclusive reading of "some": at least one, possibly all.
L = np.array(
[
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 1.0, 1.0],
]
)The matrix is small enough to read. Row 0 says "none" is true when zero servers passed. Row 3 says both "some" and "all" are true when three passed. That overlap is what makes the scalar inference possible. If "some" were false in , then hearing "some" would rule out by literal meaning alone, and there would be no need for pragmatic reasoning. The inclusive literal meaning leaves possible. The speaker's choice lets the listener lower its probability. Under the finite-softmax assumptions used here, it retains positive probability.
The Literal Listener
The literal listener normalizes each column over the states in which the utterance is true. With a flat prior, this is just the truth table divided by its column sum.
PythonIn [4]Expand
def literal_listener_flat(L):
"""P_L0(w | u) with a flat prior over states."""
support = L.sum(axis=0, keepdims=True)
if np.any(support == 0):
raise ValueError("Each utterance needs at least one supporting state")
return L / support
L0 = literal_listener_flat(L)Each column of L0 sums to one. For "some," the column is . For "all," it is . The column for "none" is . The literal listener is maximally uncertain among the states compatible with the utterance, which is what the flat-prior stipulation amounts to.
The Speaker
The speaker's utility is the log of the literal listener's probability, minus a cost. We normalize over utterances for each state. The softmax_rows helper does that normalization and handles the zero-probability utterances.
PythonIn [5]Expand
def softmax_rows(utility, alpha):
"""Normalize finite utilities separately for each state."""
if not np.isfinite(alpha) or alpha <= 0:
raise ValueError("alpha must be finite and positive")
maxima = utility.max(axis=1, keepdims=True)
if not np.isfinite(maxima).all():
raise ValueError("Each state needs an utterance with finite utility")
shifted = utility - maxima
with np.errstate(over="ignore", under="ignore"):
weights = np.exp(alpha * shifted)
return weights / weights.sum(axis=1, keepdims=True)
def speaker(L0, alpha=4.0, costs=None):
"""P_S(u | w), normalized over utterances for each state."""
with np.errstate(divide="ignore"):
utility = np.log(L0)
if costs is not None:
utility = utility - costs[None, :]
return softmax_rows(utility, alpha)The first np.errstate context suppresses the warning for . Those entries become negative infinity. Subtracting each maximum before multiplying by gives the best report a score of zero. All the remaining scores are nonpositive, so exponentiation gives weights between zero and one. A sufficiently negative scaled score can be represented by negative infinity and then gives zero weight.
The Pragmatic Listener
The pragmatic listener multiplies the speaker matrix by the prior and normalizes over states for each utterance.
PythonIn [6]Expand
def pragmatic_listener(prior, speaker_probs):
"""P_R(w | u), normalized over states for each utterance."""
unnormalized = speaker_probs * prior[:, None]
marginal = unnormalized.sum(axis=0, keepdims=True)
return np.divide(
unnormalized,
marginal,
out=np.full_like(unnormalized, np.nan),
where=marginal > 0,
)The extra dimension in prior[:, None] makes each state prior multiply its full speaker row. The normalizer sums over the state axis. With a uniform prior, the common factor cancels when the marginal is positive. For a zero-marginal report, the function returns a column of nan values to show that conditioning is undefined.
Baseline Computation and Sanity Checks
We compute the baseline model and verify the normalization axes. The speaker rows should sum to one. The listener columns should sum to one.
ConsoleOut [7]Expand
Speaker row sums: [1. 1. 1. 1.] Listener column sums: [1. 1. 1.] P(w | 'none') = [1. 0. 0. 0.] P(w | 'some') = [0. 0.497 0.497 0.006] P(w | 'all') = [0. 0. 0. 1.]
The speaker rows sum to one, and the listener columns sum to one. For "some," the posterior is approximately . That is the scalar implicature: "some" makes "all" very unlikely. The equal probabilities for and reflect the symmetric prior and speaker likelihoods, and the small residual on reflects the softmax speaker's non-zero probability of choosing a weaker utterance even when a stronger one is available.
Four Variations
We now compute the four variations from the worked example. The prior change is a listener prior. The restricted vocabulary is an alternative-set change. The "most" model adds an intermediate alternative. The uncertain-speaker model changes the speaker's information state.
PythonIn [8]Expand
# 1. A listener prior that strongly favors all three passing.
prior_all = np.array([0.001, 0.001, 0.001, 0.997])
R_prior = pragmatic_listener(prior_all, S)
# 2. A restricted vocabulary with no "all" alternative.
utterances_r = ["none", "some"]
L_r = np.array(
[
[1.0, 0.0],
[0.0, 1.0],
[0.0, 1.0],
[0.0, 1.0],
]
)
L0_r = literal_listener_flat(L_r)
S_r = speaker(L0_r, alpha=4.0)
R_restricted = pragmatic_listener(uniform, S_r)
# 3. An expanded vocabulary with "most."
utterances_m = ["none", "some", "most", "all"]
L_m = np.array(
[
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 1.0, 1.0, 0.0],
[0.0, 1.0, 1.0, 1.0],
]
)
L0_m = literal_listener_flat(L_m)
S_m = speaker(L0_m, alpha=4.0)
R_most = pragmatic_listener(uniform, S_m)The restricted model has two utterances and the model with "most" has four. In both arrays, the second column still represents "some". Comparing the right column matters when the vocabulary order changes.
Uncertain Speaker
We give the capped-tally speaker an information cell for each display result. Here she assigns equal weight to each state within her cell. We average the log literal-listener probability over that cell and apply the same softmax. A report that is false in any state in the cell has negative-infinite expected utility.
PythonIn [9]Expand
def speaker_expected(L0, cells, alpha=4.0):
"""Speaker who is uncertain within each information cell."""
n_states, n_utts = L0.shape
with np.errstate(divide="ignore"):
logL0 = np.log(L0)
utility = np.full((n_states, n_utts), -np.inf)
for w, cell in enumerate(cells):
utility[w] = logL0[cell].mean(axis=0)
return softmax_rows(utility, alpha)
# The dashboard shows 0, 1, or at least 2.
cells = [np.array([0]), np.array([1]), np.array([2, 3]), np.array([2, 3])]
S_unc = speaker_expected(L0, cells, alpha=4.0)
R_unc = pragmatic_listener(uniform, S_unc)For states and , Ada sees the same capped tally and assigns the same probability to each allowed report. "All" has negative-infinite utility because it would be false in . In fact, the speaker never reports "all" under this observation scheme, so its listener column is undefined. The posterior after "some" is defined and uniform over one, two, or three passes.
Comparison Table
We collect the "some" column from each model into a single matrix and print it as a table.
ConsoleOut [10]Expand
condition 0 1 2 3 baseline 0.000 0.497 0.497 0.006 prior favors 3 0.000 0.071 0.071 0.859 no 'all' option 0.000 0.333 0.333 0.333 add 'most' 0.000 0.850 0.140 0.010 uncertain speaker 0.000 0.333 0.333 0.333
The table matches the worked example. The baseline row has most of its mass on one or two servers. The prior row has most of its mass on three. The restricted and uncertain rows are uniform over one, two, and three. The "most" row shifts mass to one, with near 0.85. The comparison is the point: the same target utterance produces different posteriors under different stipulations, and the differences are not arbitrary. They follow from the structure of the model.
The baseline comparison shows two priors, but the posterior is a continuous compromise between prior and likelihood. A short deterministic sweep makes that tradeoff visible: as Ben's prior mass on three servers rises, the likelihood effect of "some" fights against it, and the posterior on three servers rises too.
PythonIn [11]Expand
import numpy as np
prior_w3_grid = np.linspace(0.02, 0.997, 1001)
posterior_w3_grid = []
for p3 in prior_w3_grid:
remaining = (1.0 - p3) / 3.0
prior_grid = np.array([remaining, remaining, remaining, p3])
posterior_grid = pragmatic_listener(prior_grid, S)
posterior_w3_grid.append(posterior_grid[3, 1])
posterior_w3_grid = np.asarray(posterior_w3_grid)
identity_line = np.array([0.0, 1.0])VisualizationOut [12]Expand

Visualizing the Speaker
The speaker heatmap shows the choice probabilities. Each row is a state, and each column is an utterance. The row sums are one.
VisualizationOut [13]Expand

The speaker in state 0 says "none." The speaker in states 1 and 2 says "some." The speaker in state 3 says "all" with high probability and "some" with low probability. That low probability is the source of the implicature. If the speaker in state 3 never said "some," the implicature would be categorical: hearing "some" would rule out entirely. Because the speaker sometimes says "some" even in , the implicature is probabilistic: hearing "some" downweights without eliminating it.
Visualizing the Listener
The listener heatmap compares the posterior after hearing "some" under the five stipulations. The underlying row probabilities sum to one over the four states. Rounded annotations may sum to a nearby value.
VisualizationOut [14]Expand

The heatmap makes the five conditions comparable at a glance. The baseline row is concentrated on one and two. The prior row is concentrated on three. The restricted and uncertain rows are flat over one, two, and three. The "most" row is concentrated on one. Two settings produce the same posterior even though they change different assumptions. The figure is not evidence about human listeners. It is a visualization of the model's predictions, and its value is that it makes the consequences of the stipulations easy to compare.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!