Skip to content

Two-Parameter Logistic IRT

Overview

The 2PL item response theory model (Birnbaum, 1968) for binary item responses y_{ij} of respondent i to item j. Each respondent carries a unidimensional ability theta_i, each item carries a difficulty b_j and a discrimination a_j (positive by construction via a LogNormal prior), and the probability of a correct response is sigmoid(a_j * (theta_i - b_j)).

QVR source

# Two-Parameter Logistic Item Response Theory
#
# The two-parameter logistic IRT model for binary responses
# y_{ij} of respondent i to item j. Each item carries its own
# discrimination and difficulty; respondents carry a
# unidimensional ability.
#
# Generative structure:
#
#   ability_i     ~ Normal(0, 1)                  standardised ability
#   difficulty_j  ~ Normal(0, 1)                  per-item difficulty
#   discrim_j     ~ LogNormal(0, 1)               positive discrimination
#   y_{ij}        ~ Bernoulli(sigmoid(discrim_j * (ability_i - difficulty_j)))
#
# Resp enumerates the full 100 x 20 person-by-item crossing, one
# row per response; the per-row person and item indices are host
# data, read through the plate-gather idiom
# (ability[person_idx], difficulty[item_idx]). The response is scored
# from its logit, so a saturated predictor keeps its precision; the
# program returns the response probabilities.

object Person : FinSet 100
object Item : FinSet 20
object Resp : FinSet 2000
object Val : Real 1

program irt_2pl : Resp -> Val
    let ability : Person <- sample Normal(loc=0.0, scale=1.0)
    let difficulty : Item <- sample Normal(loc=0.0, scale=1.0)
    let discrim : Item <- sample LogNormal(loc=0.0, scale=1.0)

    let theta = ability[person_idx]
    let b = difficulty[item_idx]
    let a = discrim[item_idx]
    let eta = a * (theta - b)
    let p = sigmoid(eta)

    observe y : Resp <- Bernoulli(logits=eta)
    return p

export irt_2pl

Understanding the model

When a person's ability equals an item's difficulty, the success probability is sigmoid(0) = 0.5. Raising ability above difficulty increases it. A larger positive discrimination makes the transition from low to high success sharper, so the item distinguishes more strongly between nearby abilities.

Each response row identifies both a person and an item. For row indices person_idx[n] = 2 and item_idx[n] = 5, the likelihood uses ability 2, difficulty 5, and discrimination 5. These three parameters determine the response probability together (Stan Development Team, n.d.-e). Priors help anchor the latent ability scale. Ability and difficulty must be interpreted on that same scale. Posterior predictive response probabilities express their combined effect on the observed outcome.

Walkthrough

Person and Item index the respondent and question parameters. Resp indexes the observed respondent-item pairs. Here it enumerates the full crossing of 100 persons and 20 items, though a design with missing pairs would simply list fewer rows. The Bernoulli family provides the binary value type of each response, while return p returns real-valued probabilities, reflected in Val : Real 1. Indexing a response and describing its value are different roles, which the program's annotations should keep distinct.

ability, difficulty, and discrim are plate-bound on Person and Item. discrim carries a LogNormal prior so it is positive by construction. The runtime provides person_idx and item_idx at fit time, and the gather idiom ability[person_idx] / difficulty[item_idx] / discrim[item_idx] realizes the standard cross-classified design. The Bernoulli link sigmoid(a * (theta - b)) is the canonical logistic form of the 2PL response function. The observation is scored as Bernoulli(logits=eta), from the linear predictor itself: where eta is large, sigmoid(eta) rounds to 1 in float32 and the log probability of a wrong response computed from it loses precision, while the logit form keeps it. p = sigmoid(eta) is still computed, for the program to return. The support matrix records backend coverage for this likelihood.

Try it

The blocks below simulate the full 100 x 20 response matrix, check the compiled log joint against a hand-written density, and then fit with SVI (stochastic variational inference) and NUTS (No-U-Turn Sampler). The input x_in has one row, representing one run over the full data set.

Generating synthetic data

import torch
from quivers.dsl import load

torch.manual_seed(0)
prog = load("docs/examples/source/irt_2pl.qvr")
model = prog.morphism

n_person, n_item = 100, 20
n_resp = n_person * n_item
ability_true = torch.randn(n_person)
difficulty_true = torch.randn(n_item)
discrim_true = (0.5 * torch.randn(n_item)).exp()

# Every person answers every item: row n is (person n // 20, item n % 20).
person_idx = torch.arange(n_person).repeat_interleave(n_item)
item_idx = torch.arange(n_item).repeat(n_person)
eta_true = discrim_true[item_idx] * (
    ability_true[person_idx] - difficulty_true[item_idx]
)
p_true = torch.sigmoid(eta_true)
y = torch.bernoulli(p_true)

observations = {"person_idx": person_idx, "item_idx": item_idx, "y": y}
x_in = torch.zeros(1, 1)

Checking the log joint

D = torch.distributions
truth = {"ability": ability_true, "difficulty": difficulty_true, "discrim": discrim_true}
oracle = (
    D.Normal(0.0, 1.0).log_prob(ability_true).sum()
    + D.Normal(0.0, 1.0).log_prob(difficulty_true).sum()
    + D.LogNormal(0.0, 1.0).log_prob(discrim_true).sum()
    + D.Bernoulli(p_true).log_prob(y).sum()
)
compiled = model.log_joint(x_in, {**truth, **observations}).sum()
print(f"compiled log joint: {float(compiled):.4f}")
print(f"torch log joint:    {float(oracle):.4f}")
assert torch.allclose(compiled, oracle, rtol=1e-5)

SVI fit

Positive discrimination fixes the orientation of the ability scale. The Normal(0, 1) ability prior anchors its location and scale. Correlations assess recovery without requiring identical locations and scales. Each ability is estimated from 20 binary responses, which bounds how well it can be recovered: the check asks for a correlation of at least 0.85 between posterior-mean and true abilities. Each difficulty rests on 100 responses, and the check asks for a correlation of at least 0.9. Finally, the fitted response probabilities should track the true ones: their mean absolute error should be at most half of what a constant probability of 0.5 leaves on these data.

from quivers.inference import AutoNormalGuide, ELBO, SVI

torch.manual_seed(1)
guide = AutoNormalGuide(model, observed_names={"y", "person_idx", "item_idx"})
optim = torch.optim.Adam(guide.parameters(), lr=5e-2)
svi = SVI(model, guide, optim, ELBO(num_particles=1))
for _ in range(1500):
    svi.step(x_in, observations)

with torch.no_grad():
    draws = [guide.rsample(x_in) for _ in range(500)]
post = {k: torch.stack([d[k] for d in draws]).mean(0) for k in truth}
p_svi = torch.stack(
    [
        torch.sigmoid(
            d["discrim"][item_idx] * (d["ability"][person_idx] - d["difficulty"][item_idx])
        )
        for d in draws
    ]
).mean(0)


def corr(a, b):
    return float(torch.corrcoef(torch.stack([a, b]))[0, 1])


baseline_mae = float((p_true - 0.5).abs().mean())
svi_mae = float((p_svi - p_true).abs().mean())
print(f"ability correlation:    {corr(post['ability'], ability_true):.3f}")
print(f"difficulty correlation: {corr(post['difficulty'], difficulty_true):.3f}")
print(f"probability MAE: {svi_mae:.3f} (constant 0.5: {baseline_mae:.3f})")

assert corr(post["ability"], ability_true) > 0.85
assert corr(post["difficulty"], difficulty_true) > 0.9
assert svi_mae < 0.5 * baseline_mae

NUTS posterior

NUTSKernel samples the 140-dimensional posterior over the full response matrix and is held to the same three recovery checks. Four chains each use 1,000 warmup iterations and 4,000 retained draws. MCMCMethod runs them in four worker processes, each of which compiles the same source, and returns the draws of the serial run. Before comparing posterior means, the example checks rank-normalized split \(\hat R < 1.01\) and bulk and tail effective sample sizes above 400 for every parameter (Vehtari et al., 2021). These diagnostics assess mixing and sampling precision across abilities, difficulties, and discriminations.

from pathlib import Path

from quivers.inference import MCMC, NUTSKernel
from quivers.modeling import MCMCMethod, Model

kernel = NUTSKernel(step_size=0.05, max_tree_depth=8, target_accept=0.9)
mc = MCMC(kernel, num_warmup=1000, num_samples=4000, num_chains=4, seed=2)
bound = Model(Path("docs/examples/source/irt_2pl.qvr").read_text()).bind(
    {**observations, "y": y.bool()}
)
result = MCMCMethod(sampler=mc, cores=4).run(bound).posterior

for k in truth:
    print(f"{k:>10}: max R-hat {result.r_hat[k].max():.4f}, "
          f"min bulk ESS {result.ess[k].min():.0f}, "
          f"min tail ESS {result.ess_tail[k].min():.0f}")
    assert (result.r_hat[k] < 1.01).all()
    assert (result.ess[k] > 400).all()
    assert (result.ess_tail[k] > 400).all()
assert int(result.divergence_counts.sum()) == 0

s = {k: result.samples[k].reshape(-1, v.numel()) for k, v in truth.items()}
p_nuts = torch.sigmoid(
    s["discrim"][:, item_idx] * (s["ability"][:, person_idx] - s["difficulty"][:, item_idx])
).mean(0)
nuts_mae = float((p_nuts - p_true).abs().mean())
print(f"ability correlation:    {corr(s['ability'].mean(0), ability_true):.3f}")
print(f"difficulty correlation: {corr(s['difficulty'].mean(0), difficulty_true):.3f}")
print(f"probability MAE: {nuts_mae:.3f}")
print(f"divergences: {int(result.divergence_counts.sum())}")

assert corr(s["ability"].mean(0), ability_true) > 0.85
assert corr(s["difficulty"].mean(0), difficulty_true) > 0.9
assert nuts_mae < 0.5 * baseline_mae

Categorical perspective

A probability kernel assigns a probability distribution to each input. Such kernels compose by integration in the Kleisli category of the Giry monad (Giry, 1982). The ability and item-parameter priors compose with Bernoulli response kernels. Reindexing along person_idx : Resp -> Person and item_idx : Resp -> Item assigns each response its person's ability and its item's discrimination and difficulty. Conditional on those parameters, the response likelihood is the product over the response rows.

Observing data weights this sampling distribution by a likelihood. The resulting measure need not have total mass one, so the scored program uses weighted-measure semantics (Staton, 2017).

Cited sources

Allan Birnbaum. Some Latent Trait Models and Their Use in Inferring an Examinee's Ability. In Statistical Theories of Mental Test Scores. Addison-Wesley, 1968. URL: https://bookstore.emerald.com/statistical-theories-of-mental-test-scores-pb-9781593119348.html.

Stan Development Team. Regression models. Stan User's Guide, version 2.40, n.d.-e. URL: https://mc-stan.org/docs/stan-users-guide/regression.html (visited on 2026-11-06).

Aki Vehtari, Andrew Gelman, Daniel Simpson, Bob Carpenter, and Paul-Christian Bürkner. Rank-Normalization, Folding, and Localization: An Improved R-hat for Assessing Convergence of MCMC (with Discussion). Bayesian Analysis, 16(2):667–718, 2021. URL: https://doi.org/10.1214/20-BA1221, doi:10.1214/20-BA1221.

Michèle Giry. A Categorical Approach to Probability Theory. In B. Banaschewski, editor, Categorical Aspects of Topology and Analysis, volume 915 of Lecture Notes in Mathematics, pages 68–85. Springer, 1982. URL: https://link.springer.com/chapter/10.1007/BFb0092872, doi:10.1007/BFb0092872.

Sam Staton. Commutative Semantics for Probabilistic Programming. In Programming Languages and Systems (ESOP 2017), Lecture Notes in Computer Science, 855–879. Springer, 2017. doi:10.1007/978-3-662-54434-1_32.