The math behind choicer: multinomial logit
Source:vignettes/articles/multinomial_logit_math.Rmd
multinomial_logit_math.RmdThis document provides a detailed mathematical description of the
multinomial logit (MNL) model as implemented in
src/mnlogit.cpp.
Table of Contents
- Notation
- Model Definition
- Log-Likelihood Function
- Gradient Computation
- Hessian Computation
- Elasticity Computation
- Diversion Ratio Computation
- BLP Share Inversion
- Willingness to Pay
- Consumer Surplus and the Logsum
- Goodness of Fit
- Choice-Based Sampling and WESML Weighting
- Implementation Details
Notation
| Symbol | Description |
|---|---|
| Index for individuals (choice situations) | |
| Index for alternatives available to individual | |
| Choice set for situation ; it contains inside alternatives and, when requested, the implicit outside alternative 0 | |
| The alternative chosen by individual | |
| Weight for individual | |
| Row vector of covariates for individual and alternative () | |
| Coefficient vector () | |
| Alternative-specific constant (ASC) for alternative | |
| Systematic (deterministic) utility | |
| Probability that individual chooses alternative |
1. Model Definition
1.1 Utility Specification
The utility that individual derives from alternative is:
where the systematic utility is:
and is an i.i.d. Type I Extreme Value (Gumbel) error term with location 0 and scale 1.
1.2 Alternative-Specific Constants (ASCs)
The ASC parameters capture the average effect of unobserved factors for each alternative. For identification, one ASC must be normalized:
Without outside option (
include_outside_option = FALSE): The first inside alternative’s ASC is fixed to zero (). The parameter vector contains free ASC parameters.With outside option (
include_outside_option = TRUE): The outside option (alternative 0) has utility , serving as the reference. All inside alternatives have free ASC parameters.
Code reference: src/mnlogit.cpp
2. Log-Likelihood Function
2.1 Choice Probability
Under the Type I Extreme Value distribution assumption, the probability that individual chooses alternative follows the multinomial logit (softmax) formula:
If an outside option is included, the denominator includes
.
The outside option is implicit: it has no row in
,
no free coefficient, and is prepended internally to the vector of inside
utilities. Global alternative IDs (alt_idx) need not equal
an alternative’s local row position in
;
the former map ASCs across situations, whereas choice_idx
records the local chosen position (or 0 for the outside option).
Code reference: src/mnlogit.cpp
2.2 Log-Likelihood
The log-likelihood is the weighted sum of the log-probabilities of the observed choices:
where is the full parameter vector and is the alternative chosen by individual .
Expanding the log-probability:
Code reference: src/mnlogit.cpp
2.3 Log-Sum-Exp Trick for Numerical Stability
To prevent numerical overflow when computing the denominator, the implementation subtracts the maximum utility before exponentiation:
where .
This gives:
The log-probability becomes:
Code reference: src/mnlogit.cpp
3. Gradient Computation
3.1 General Formula
The gradient of the log-probability of the chosen alternative with respect to utility is:
where is the indicator function (1 if is the chosen alternative, 0 otherwise).
3.2 Gradient with Respect to
Since , the contribution to the gradient from individual is:
This simplifies to:
The full gradient is:
Implementation note. Define the difference vector
with entries
.
Then the sum above is
,
a single BLAS matrix-vector product (X_i.t() * diff_vec).
When an outside option is present,
covers only the
inside alternatives and
is sliced accordingly (diff_vec.subvec(1, m_i)).
Code reference: src/mnlogit.cpp
3.3 Gradient with Respect to
Since , the contribution to the gradient from individual for alternative is:
The gradient is computed only for the free ASC parameters: - Without outside option: (fixed), so we compute for - With outside option: we compute for all inside alternatives
The delta gradient reuses the same difference vector computed for the beta block; its entries are scattered into the appropriate positions of the gradient vector via an irregular index mapping.
Code reference: src/mnlogit.cpp
4. Hessian Computation
4.1 Analytical Hessian — Full-Vector Form
The Hessian of the log-likelihood for individual is:
where is individual ’s choice set (including the outside option when present) and is the “score vector” for alternative :
Here is the covariate vector for alternative , is the standard basis vector in indicating the free ASC position for alternative , and is the number of free ASC parameters ( without outside option, with outside option). For the outside option itself, (no covariates, no free ASC).
This can be written compactly as:
where the variance is taken under the discrete distribution . The full Hessian is and the function returns (Hessian of the negative log-likelihood).
4.2 Block Decomposition
The parameter vector is with (covariate coefficients) and (free ASC parameters). Because has at most nonzero entries — in the block and at most one in the block — the dense outer product has only three nontrivial submatrices. Summing over alternatives, the individual Hessian decomposes into three blocks:
Beta-beta block (, symmetric):
where the sum runs over the inside alternatives only (since ). This is the probability-weighted covariance of the covariates:
Delta-delta block (, symmetric):
When a situation lists an alternative once, is that alternative’s choice probability; rows that repeat an alternative add their probabilities into its one entry. The diagonal of is and the off-diagonal entry is ; is zero off the constants of the alternatives the situation offers.
Beta-delta block (, generally not symmetric):
This block measures the probability-weighted covariance between the covariates and the ASC indicators.
Why the decomposition equals the full-vector form. Partition . Then:
Subtracting block by block yields exactly , , above.
4.3 Compact Blocks and Accumulation
Because is zero off the situation’s own constants, and vanish outside them: situation ’s Hessian lives on its compact block, the coefficients and the free constants of the alternatives it offers (in increasing order). The kernel forms (its upper triangle), () and the constants’ block (, from the vector as it is added) and adds times them into the upper triangle of an accumulator, which is mirrored once after the loop. A situation costs , whatever the number of alternatives ; adding its dense and cost , which dominated with thousands of constants (281 s for 24,560 situations and 2,611 parameters at one thread, against 0.13 s for the compact blocks).
Each thread adds into its own packed upper triangle while the
threads’ triangles fit in a budget (2 GiB by default; the kernels’
internal acc_bytes), and above it into the shared result:
the coefficients’ rows through small private buffers, the constants’
block by atomic additions. Both are allocated before the parallel loop,
and the kernel first compares an upper estimate of its memory with
options(choicer.max_memory) or the machine’s physical
memory, stopping with an error that names the number of threads that
fits.
Non-finite values. The dense form subtracted over every parameter, so a non-finite mean (overflowing utilities, a covariate near the largest double) reached its row’s entries outside the block as , NaN; and a non-finite weight multiplied the zeros outside the block. The compact kernel adds those values where the dense form did: the spread of a non-finite mean during the loop (once per row and thread for a NaN mean, which turns the whole row NaN), and the spread of a non-finite weight after it.
4.4 ASC Normalization and Indexing
The free-delta position for inside alternative (0-based local index within individual ’s choice set, with ) is:
where alt_idx0_i[a] is the 0-based global alternative ID
from alt_idx0. When there is no outside option, the first
inside alternative
()
has its ASC fixed to zero by the identification convention, so it
contributes no free ASC entry and is skipped in the BD and DD
accumulation.
Implementation note. Each term is formed as the dense form formed it — every product of means rounded before it is subtracted — and added in the same order, so at one thread the compact Hessian is the dense one bit for bit, except where the dense form’s BLAS call fused a product into the subtraction (in designs with a single coefficient or a single constant), where the two differ in their last bits.
Code reference: src/mnlogit.cpp, function
mnl_loglik_hessian_parallel.
5. Elasticity Computation
5.1 Elasticity Definitions
The elasticity measures the percentage change in choice probability with respect to a percentage change in an attribute. For attribute with coefficient :
Own-Elasticity (elasticity of with respect to ):
Cross-Elasticity (elasticity of with respect to where ):
5.2 Derivation
Starting from the choice probability:
Taking the derivative with respect to :
For own-elasticity ():
Therefore:
For cross-elasticity ():
Therefore:
5.3 Weighted Average of Individual Elasticities
The implementation computes a weighted average of the individual probability elasticities:
where is the elasticity for individual .
This estimand is not, in general, the elasticity of the aggregate share . The latter is
and requires a definition of the common market-level perturbation
when the attribute varies over individuals. elasticities()
deliberately reports the average of individual elasticities above; rows
index responding alternatives and columns index perturbed alternatives.
With an outside option, index 0 is included in the returned matrix; its
attribute value is zero, so the outside-option perturbation column is
zero.
Code reference: src/mnlogit.cpp
6. Diversion Ratio Computation
6.1 Definition
The diversion ratio from alternative to alternative measures the fraction of demand lost by that is captured by when becomes less attractive (e.g., due to a price increase). It is a key metric in antitrust analysis and merger simulation.
where is the (weighted) aggregate demand for alternative and is the price of .
6.2 Derivation for MNL
From the MNL choice probability derivatives (Section 5.2), the demand derivatives with respect to price (with coefficient ) are:
Substituting into the diversion ratio formula:
The price coefficient cancels, so the diversion ratio does not depend on which covariate we differentiate with respect to. This is a consequence of the IIA property.
6.3 Aggregate Diversion Ratio Matrix
The implementation computes the full diversion ratio matrix where:
6.4 Properties
Column sums equal one. For a given alternative , the off-diagonal entries in column sum to 1, meaning all diverted demand is accounted for:
where we used .
IIA proportionality. When all individuals face the same choice set and the same covariates (so does not vary across ), the diversion ratio simplifies to:
where is the market share of alternative . This means diversion is proportional to the receiving alternative’s market share, independent of any characteristics of the losing alternative other than its own share. This is a well-known limitation of MNL due to IIA.
6.5 Implementation
The function accumulates two quantities in parallel across individuals:
- Numerator matrix: for each pair
- Denominator vector: for each
The final matrix is computed as for , with , in place in the numerator’s sum (§12.3); a column whose denominator is at most (an alternative no situation offers, say) is set to zero.
Code reference: src/mnlogit.cpp
7. BLP Share Inversion
7.1 Problem Statement
Given target market shares (with an outside option, too, all of them summing to one), find the alternative-specific constants at which the model’s predicted shares equal them, with held at its value:
where is the predicted market share for alternative . With every alternative available in every choice situation, any interior target is attained by a unique , up to the normalization below (Berry 1994). Where choice sets differ, attainability restricts the targets (§7.2); a solution, where it exists, is still unique up to that normalization, the logit’s shares being connected substitutes (Berry, Gandhi and Haile 2013).
7.2 Identification and Checks of the Targets
With an outside option, whose utility is normalized to zero, every inside constant is identified. Without one, the shares depend only on differences of constants among alternatives that share choice situations, directly or through others: each such group (a connected component of the graph that links the alternatives through the choice situations of positive weight) identifies its constants up to a common level, and its shares add up to the weight of its situations. Each component’s reference, its smallest alternative code, is held at its start, after the start is normalized by subtracting its first element, so that the first constant is zero.
Targets that no constants attain stop the inversion before any evaluation of the shares, with an error: an alternative offered in no choice situation of positive weight; targets that do not sum to one (the outside share included), or, without an outside option, a component’s targets that do not add up to its situations’ weight, within a relative (within it they are rescaled); targets that leave no share to the outside option in a component; and a target not strictly below the weight of the choice situations that offer the alternative, or, without an outside option, not strictly above the weight of those that offer it alone (an alternative alone in its component is exempt: its share is its situations’ weight). These are necessary conditions: a target that passes them may still be unattainable, and the iteration then does not converge.
7.3 The Iteration
Write
for the log-share residuals and
for the base: the outside option, or, without one, the reference of
’s
component. The free constants solve
;
with an outside option,
is the outside-share correction of Fukasawa (2024). Berry, Levinsohn and
Pakes’s (1995) contraction, method = "original", updates
(with the component’s reference held,
).
The derivative of in the free constants is
a part with a dominant diagonal,
,
plus a term common to every row, the response of the base’s share. The
step, method = "simple", treats the two in turn. A common
shift
of the component’s free constants moves each
by
to first order, where
exactly (the share Jacobian is symmetric and its rows sum to zero), and
solves
,
to first order the shift that matches the base’s share. The rest of each
residual takes the exact diagonal of the derivative:
The diagonal alone misjudges the common shift. Where the base’s share is small and each alternative dominates choice situations of its own, falls below and that step diverges where Berry’s contraction converges: in three choice situations, each won by one of alternatives 2 to 4 ( of 3 for the winner, for the other two and 0 for a rarely chosen alternative 1, with constants ), it is at the solution. A choice situation that lists an alternative twice contributes its total probability. One evaluation of the shares gives , and together.
Safeguards keep the step from failing where Berry’s contraction
converges. A step is at most
in magnitude: the scaling may lengthen the unscaled step
to 5 log units, not beyond (an alternative chosen almost wherever it is
offered has a diagonal near zero). In an iteration where a component’s
outside share underflows to zero, the step drops the outside correction
and the common shift
(
over
).
An evaluation whose shares are not finite halves the step, up to ten
times. An iteration whose best residual has not improved for 30
iterations (a stall) halves its later steps. If its residual at the
stall is more than twice the best, the steps diverge, and it first
returns to its best point, once per best point; otherwise it goes on
from where it is, each such stall doubling the iterations the next one
waits for. Going on matters: far from the solution the common shift can
strand constants where their shares barely respond (alternatives offered
with the base only in situations that others dominate), and the way back
can climb for dozens of iterations at a residual above the best so far,
a climb that returning to that best point at every stall would never
complete. And the scaling can amplify a small residual of an alternative
that nearly owns its choice situations, whose diagonal is near zero,
into a step that wrecks the shares of its neighbours there; the two then
oscillate, and the residual decays too slowly. Berry’s contraction never
amplifies a step, so it races the step once the step stops making
progress: when 100 iterations fail to halve the best residual (or a
trial point’s shares stay non-finite after every halving, and the step
stops), the contraction starts from the same start and the two take
steps in turn, each with its halvings. The first to reach the tolerance
returns. The contraction stops if 100 of its own evaluations of the
shares fail to halve its best residual while the step’s best is lower;
the step then has 200 iterations at a time to halve its own best
residual, and whenever it fails to, the contraction goes on from where
it stopped: the step can also carry the constants of alternatives that
make up the whole choice set of some choice situations so far down that
the residual barely responds to their common level, and then make no
progress at all. Where the contraction converges in
evaluations, the step converges within
,
and within
where the contraction halves its best residual within every 100 of its
evaluations,
being the evaluations before the contraction joined; the bound leaves
out the step’s halvings after the contraction joined and any 200
iterations in which the step alone halved its best residual. Berry’s
contraction itself, as method = "original", takes only the
halving of steps whose shares are not finite.
method = "anderson", the default, accelerates the same
step, Anderson acceleration of type II (Walker and Ni 2011). Write
for the step at
,
and
and
for the last
differences (memory, default 10, cut to the number of free
constants) between successive iterates and between their steps, newest
first. Each iteration solves the least squares
,
the combination of past changes in the step that best cancels the
current one, and moves to
the capped step above while there are no differences. On a linear
map, undamped and with unlimited memory, this is essentially GMRES
(Walker and Ni 2011), so it handles the slow modes of segmented choice
sets that the step alone crawls along. The least squares go through a
Householder QR of
,
one per iteration, and the oldest differences are dropped while the
triangular factor’s condition estimate,
,
exceeds max_condition (default
).
Its safeguards are on the residual, never on a merit function: when five
iterations bring no residual below 0.9 times the best so far, or the
shares at an extrapolated point are not finite, it clears its
differences and takes the plain step from where it is, halved while its
shares are not finite; only where its residual has grown past twice the
best does it go back to its best point, once per best point, since a
path to the solution can climb through larger residuals first (the
step’s stalls above). Where a component’s outside share underflows it
takes the step unextrapolated, keeping no differences, until the share
returns: the step then has another form (no outside correction, no
common shift), and its level drifts by about the same amount at every
iteration, which the least squares would try to cancel instead of
follow. It races the contraction like the step, each of its iterations
one evaluation of the shares besides trial points whose shares are not
finite (left out of the bound, as the step’s halvings are), so the bound
holds for it too.
method = "squarem" extrapolates the step by SQUAREM
(Varadhan and Roland 2008), PyBLP’s default. With
,
each cycle takes
and
,
sets
and
,
and moves to
(scheme 3; scheme 1 takes
,
scheme 2
),
bounded to [step_min, step_max], 1 and 1 at
first; one more step
from that point starts the next cycle. Each time
reaches step_max at a point whose residual is finite, the
bound is multiplied by step_factor (4), so the
extrapolation lengthens while it succeeds; where the shares at an
extrapolated point are not finite, the cycle takes
instead, and a bound
had reached is divided by step_factor, not below its start.
With these bounds it never steps shorter than
,
so it cannot damp an oscillating step as Anderson’s least squares can.
It races the contraction too.
On the 121 simulated designs of choicer’s test bed (multinomial, nested and mixed logits; 2 to 5,000 alternatives; full, regional and chained choice sets; far starts), solved to , the step converged on every one; where Berry’s contraction converged too (113 designs), the step needed a median 0.36 of its evaluations, and never more than 1.05 times as many; no iteration stalled, and the contraction never joined. On 80 designs built like the example above, solved to , it did not converge within 3,000 evaluations on one, which it was still approaching (it took 9,472, the contraction’s turns included), and Berry’s contraction failed on 22; where both converged, the step needed a median 0.16 of Berry’s evaluations. On 999 small designs drawn to be hard (3 to 6 alternatives in 2 to 8 choice situations of random sizes, single-alternative ones included; covariates and constants integers in and ; half with an outside option), at tolerance and 1,000 evaluations, the step failed on 103 and Berry’s contraction on 592, never where the contraction converged; where both converged, the step needed a median 0.12 of the contraction’s evaluations.
With method = "anderson" the same 121 designs converged
in medians of 13, 12 and 16.5 evaluations for the multinomial, nested
and mixed logits (32, 18.5 and 174 with "simple"), never
more than 1.25 times "simple"’s, and the 24-alternative
market of four regions from 10 far starts in 27 to 36 evaluations, where
"simple" needed 3,143 to 3,655. On the 999 small hard
designs above and 999 more drawn alike it failed on 61, 29 and 20 at
1,000, 20,000 and 200,000 evaluations, against 210, 80 and 39 for
"simple", and needed a median 0.45 to 0.48 of
"simple"’s evaluations where both converged. On simulated
claims-, census- and small-scale data (up to
rows), at tolerance
,
it took 0.25 to 1.03 times "simple"’s time, which made it
the default.
7.4 Stopping Rule and Result
The iteration stops at the first evaluation whose residual is at most
tol (default
),
and returns that point. The residual is
without an outside option,
the reference of
’s
component, and with one
together with each component’s outside share’s
;
every share, the outside option’s included, then matches its target to a
relative error of about tol. The error in
is of order tol times the conditioning of the share
equations, which choice sets with few alternatives in common can raise
to hundreds or more.
max_iter counts evaluations of the shares (default
1,000; 0 returns the normalized start). When the iteration stops
otherwise, at max_iter or at shares that are not finite, it
returns the evaluated point of smallest residual and warns with class
choicer_blp_unconverged; the condition’s
convergence element holds the status, the iterations, the
evaluations and the residual.
7.5 The Layout of delta
-
No outside option.
deltahas length (theblp()method prepends the normalized zero to the fitted length- ASC block), and the returned vector’s first element is zero; it is not the length- free-parameter block. -
Outside option. The supplied and returned
deltahave length and contain the inside alternatives only;target_shareshas entries, the outside option’s first. -
blp(). The method checks the targets in R first (one share per alternative, finite, positive, summing to one), starts from the fitted constants (ordelta_init), and returns the matrix with the inside alternatives’ labels as row names and the attribute"convergence": the record of §7.4 (converged, status, iterations, evaluations, residual,toland method), there whether or not the iteration converged. The exported functions return the bare matrix.
7.6 Evaluating the Shares
After the first evaluation, the probabilities are read from exponentials kept across evaluations wherever those allow it. The first, at , keeps for each row , where is the largest utility in situation (with an outside option, its 0 included, so that is kept too). An evaluation at then forms
(
without an outside option):
exponentials per evaluation in place of one per row, which takes 0.4 to
0.6 of the time. A row whose exponential underflowed when it was kept
can carry at most
into a share, where
.
So an evaluation at
,
or one at which some share falls below
(at most about
),
exponentiates every row afresh at
and keeps those exponentials in place of the old ones; one at a
that is not finite exponentiates afresh and leaves the kept values as
they were. The probabilities agree with those computed afresh to within
rounding, so the iteration’s path, and the returned
,
can move as two solutions within tol differ (by about
tol times the conditioning, §7.4). The kept values take one
double per row (and one per situation with an outside option), within
half the memory limit (options(choicer.max_memory = ), else
the physical memory) less what the call holds; where they do not fit,
every evaluation exponentiates afresh.
The shares sum the probabilities over choice situations, and rounding in those sums sets a floor under the residual that grows with the situations each thread adds: on one thread, with four alternatives in every situation, about at situations (about 4.2 million; with an outside option) and at ( rows). Above situations per thread the sums are compensated (Kahan’s summation; so are the weights’ total, each component’s weight and the weights that bound the targets, §7.2, above situations in all), which brings the floor to the precision of a double, or less at both sizes, for up to 14% more time per evaluation on the exp-space pass and 2.5–4% on the usual pass.
Code reference: src/blp_engine.h
(the components, the checks, the step and the stopping rule), src/fixed_point.h
(the iteration), MnlBlpModel in src/mnlogit.cpp
(the pass) and R/blp.R.
8. Willingness to Pay
8.1 Definition
When one covariate is a price with coefficient , the willingness to pay (WTP) for attribute is the marginal rate of substitution between the attribute and price — the price change that leaves utility unchanged after a unit change in the attribute:
Since utility is linear, the same ratio applies to ASCs: the WTP for alternative ’s unobserved quality is .
8.2 Delta-Method Standard Errors
WTP is a nonlinear function of the estimated coefficients. By the delta method, with the estimated coefficient covariance matrix,
where is the block of for . The gradient is analytic (exact), so no numerical differentiation is involved. Confidence intervals use the normal approximation:
Because the estimates and covariance are stored in natural (unscaled)
units, no scaling adjustment is needed even when the model was estimated
with scale_vars.
Caveat. The ratio of two asymptotically normal estimators has heavy tails when the denominator is imprecisely estimated; the delta-method interval is a first-order approximation that deteriorates as falls. For a weakly identified price coefficient, simulation methods (Krinsky–Robb) or Fieller intervals are more reliable.
Code reference: R/wtp.R
9. Consumer Surplus and the Logsum
9.1 The Logsum (Expected Maximum Utility)
Under Type I Extreme Value errors, the expected maximum utility over individual ’s choice set is, up to an additive constant (Euler’s constant ):
When the model includes an outside option with normalized utility , the sum includes its term. The implementation uses the same max-subtraction trick as the log-likelihood (Section 2.3).
9.2 Expected Consumer Surplus
With utility linear in price (no income effects), the marginal utility of income is (positive for a negative price coefficient), and expected consumer surplus in money units is (Train 2009, Ch. 3):
Identification caveat. Like utility itself, the logsum is only defined up to an additive normalization (in particular the ASC normalization), so CS levels are not interpretable on their own. The economically meaningful quantity is the difference between scenarios,
computed by evaluating the logsum on counterfactual data
(newdata) and on the baseline. The normalization constant
cancels in the difference. The routine does not impose
;
interpreting the denominator as positive marginal utility of income
requires the analyst to verify the fitted price sign.
9.3 Delta-Method SE for the Mean Consumer Surplus
For the weighted mean , the implementation reports a delta-method standard error. The building block is the derivative of the logsum, which by the envelope-style identity is a probability-weighted average of utility derivatives:
with , , and a zero contribution from the outside option row (). Then:
- For non-price parameters: .
- For the price coefficient, which enters both the logsum and the factor:
The SE is , where is the weighted average of the per-individual gradient vectors and the full coefficient covariance. All ingredients (, , ) come from a single prediction pass.
Code reference: R/surplus.R
10. Goodness of Fit
10.1 McFadden Pseudo R-Squared
where is the number of estimated parameters and is a null-model log-likelihood. Two nulls are available:
Equal shares (default). Every alternative in individual ’s choice set is equally likely:
where is the number of inside alternatives. This closed form is exact for unbalanced choice sets and arbitrary weights.
Market shares. The maximized log-likelihood of a constants-only (ASC-only) model. When every alternative is available in every choice situation, the ASC-only model’s fitted probabilities equal the observed market shares , giving the closed form
with the unweighted choice counts and the common observation weight (usually after normalization). The outside option enters as its own category when present; never-chosen alternatives contribute . This closed form requires identical choice-set composition across individuals — equal set sizes are not sufficient — and uniform weights; otherwise an ASC-only model must be refit explicitly.
10.2 Hit Rate
The hit rate is the weighted share of choice situations in which the observed choice has the highest predicted probability:
With an outside option, the outside good competes for the maximum
with probability
,
and a predicted outside choice is a hit when the outside good was in
fact chosen
().
Ties among inside alternatives are resolved by the first local row
(which.max in R). The outside option replaces that inside
winner only when its probability is strictly larger, not when tied.
Code reference: R/gof.R
11. Choice-Based Sampling and WESML Weighting
11.1 Endogenous Stratified (Choice-Based) Sampling
Under random (exogenous) sampling each choice situation is drawn independently of its outcome. Under choice-based (endogenous stratified) sampling the strata are defined by the chosen alternative , and situations are drawn with stratum-specific frequencies — for example, deliberately oversampling individuals who chose a rare alternative. Let be the population share of alternative and the sample share of choosers of .
For the multinomial logit there is a well-known special case: with a full set of alternative-specific constants, choice-based sampling biases only the constants, and the slope coefficients remain consistent (Manski & McFadden 1981). Outside that case — most importantly when the ASCs are not saturated, or when the constants themselves are of interest (welfare, counterfactual entry) — naive (unweighted) maximum likelihood is inconsistent for the population parameters, and the weighting below is required.
11.2 The WESML Weighted Log-Likelihood
Manski and Lerman (1977) restore consistency by weighting each situation’s contribution by the ratio of population to sample share of its chosen alternative,
The maximizer is invariant to multiplying every by a common positive constant, so the weights may be normalized to mean 1 without changing the estimates.
11.3 Robust (Sandwich) Variance: the Meat
WESML is a weighted M-estimator solving , where is the per-situation score ($H_i = ^2 P_{i j_i}/,^$ its Hessian ($$4). Its robust (Huber–White) asymptotic variance is the sandwich
The weight enters the bread linearly, but the meat carries the weight squared: the contribution of situation to the estimating equation is , so the variance of that contribution involves .
This is exactly why the two naive variances are wrong under weighting:
- the inverse-Hessian assumes the information-matrix equality , which fails once the are non-degenerate;
- the ordinary BHHH/OPG uses the weight to the first power, not the second.
A consistency check: rescaling all weights by a constant sends and , so — the sandwich is invariant to the weight scale, whereas is not.
11.4 Scope: Robust vs. Design-Based Variance
The estimator implemented here is the robust weighted-M-estimator (Huber–White) variance, whose meat is uncentered. This is the asymptotic variance under variable-probability sampling (each population unit sampled independently with a stratum-dependent probability). Under a fixed-quota design the design-based variance centers the scores within strata and may be smaller; that stratum-centered estimator is out of scope here. See Manski & McFadden (1981) for the design-based treatment and Cosslett (1981) for the asymptotically efficient conditional-maximum-likelihood alternative.
11.5 Implementation and Cluster-Robust Extension
The meats come from compiled kernels that never form the
matrix of scores
(
situations by
parameters): the BHHH kernel mnl_bhhh_parallel() adds
over each situation’s compact block (§4.3), with
weights = w for the BHHH information and
weights = w^2 for the robust meat, the
weight-free score
entering both. With the bread
the variance is
,
computed equilibrated by two solves against the
factors of the equilibrated bread, without forming an inverse (§12.6).
The fit-time variance (se_method),
vcov(fit, type = ), the recomputation of a variance dropped
from a fit and wesml_vcov() all compute it from the same
kernels (.assemble_score_vcov(), or
compute_hessian() for a Hessian or BHHH variance recomputed
lazily), so a fit’s variance is the one vcov() returns post
hoc: bit for bit at one thread, and up to the last bits with more, where
the threads’ shares of the situations change from call to call.
For cluster labels
,
se_method = "cluster" replaces the meat by
mnl_cluster_meat_parallel() forms it without the score
matrix either: the situations sorted by cluster, each cluster’s weighted
compact scores summed over the parameters its situations touch, its
outer product added once the cluster ends. The sorted situations are cut
into about four chunks of similar row counts per thread, and a cluster
that a chunk boundary cuts is merged, in chunk order, after the parallel
loop. The labels are checked before any kernel runs. No
or other finite-cluster correction is applied. Clustering changes the
estimated covariance, not the likelihood or point estimate. User-facing
entry points: wesml_weights() computes the Manski–Lerman
weights from the population shares
,
while sample_by_choice() draws a choice-based sample and
attaches those weights;
run_mnlogit(..., se_method = "sandwich") estimates with the
robust variance; wesml_vcov() returns it post hoc. Passing
run_mnlogit(..., weights_col = ) collapses a row-level
weight column to one weight per choice situation (validated constant
within id), and a provenance guard prevents a WESML-labeled
sample from being silently fit unweighted.
Code reference: mnl_bhhh_parallel() /
mnl_cluster_meat_parallel() in src/mnlogit.cpp;
.assemble_score_vcov(), .logit_meat() and
.sandwich_combine() in R/classes.R
(.score_meat() there forms the same meats from the score
matrix of mnl_scores_parallel(), as the tests’ reference);
equilibrated_sandwich() in src/vcov.cpp;
wesml_weights() / sample_by_choice() in R/sampling.R.
12. Implementation Details
12.1 Parameter Vector Structure
The full parameter vector is organized as:
| Block | Indices | Length | Description |
|---|---|---|---|
| Coefficients for design matrix | |||
| , , or | Free alternative-specific constants |
where
when use_asc = FALSE,
without outside option (first ASC normalized to 0), or
with outside option.
Code reference: src/mnlogit.cpp
12.2 Data Organization
- Design matrix : Stacked matrix of dimension , where is the number of (inside) alternatives for individual
- Alternative indices: 1-based indexing in R, converted to 0-based in C++
- Choice indices: 1-based local row positions within each situation’s block for inside alternatives, 0 for the outside option when included
- Prefix sums : Used for efficient indexing into the stacked data:
12.3 OpenMP Parallelization
The implementation parallelizes over choice situations using OpenMP:
- Each thread keeps its working arrays (utilities, probabilities, score
differences, and a copy of a situation’s covariate rows where
Armadillo’s product needs one) and local accumulators: the
log-likelihood and gradient, or a packed upper triangle of the Hessian
or BHHH matrix (§4.3; one thread adds into the result itself, and above
the budget the threads share it). All are allocated before the parallel
loop, once the kernel’s memory estimate has been checked, so that no
choice situation allocates - A situation’s utilities,
plus its alternatives’ constants, are formed inside the loop from its
rows of
in place, sixteen rows at a time (then eight, four and two) with their
sums held in registers while one loop runs over the
columns. Nothing of the stacked length is formed per evaluation, and the
thread that reads a situation’s rows for its utilities then uses them
for its gradient. (A single product
ahead of the loop, as before 0.3.0, wrote a vector as long as the design
once per column and did not speed up with the threads.) Each row’s sum
takes its columns in order from zero (a product and an addition per
column, fused into one operation where the package is compiled for a
processor that has it) and its constant last, so a row’s utility depends
neither on the situation it is stacked in, nor on the thread count, nor
on the BLAS that R is linked to - The Hessian’s and BHHH matrix’s
triangles are added after the loop in thread order (above the budget,
the constants’ entries atomically during it); the log-likelihood and
gradient in an order that can vary between calls - Dynamic scheduling
balances the load, each dispatch handing a thread about 256 stacked
rows, at least one situation (schedule(dynamic, chunk);
CHOICER_CHUNK_ROWS at compile time), so that situations of
a few rows do not pay a dispatch each; fewer where the largest situation
has more than eight times the mean rows, so that no dispatch holds more
than about 2,048 rows whatever the situations’ order - The elasticity
and diversion-ratio kernels (§5.3, §6.5) add each situation’s terms into
a
sum: one thread into the result itself,
threads into copies of their own while those fit in 2 GiB (added up in
thread order after the loop), and beyond that into the shared result
atomically, each thread keeping the outside option’s row and column,
which every situation touches, to itself. Their memory (the result, the
threads’ copies and working arrays) is checked before anything is
allocated, as the estimation kernels’ is; with one thread the sums do
not depend on the 2 GiB budget
Code reference: src/mnlogit.cpp;
the utilities, BaseUtil in src/choicer_internal.h
12.4 Negated Objectives
The likelihood/gradient kernel and analytical-Hessian kernel return, respectively: - (negated log-likelihood) - (negated gradient) - (negated Hessian)
This is for compatibility with minimization routines (e.g.,
nloptr) that expect a loss function to minimize rather than
a likelihood to maximize.
12.5 Finite-Value Guards
If a situation’s chosen log probability is non-finite, the likelihood
kernel substitutes
for that contribution and emits one warning after leaving the OpenMP
region. If the assembled negated objective is still non-finite, it
returns
and a zero gradient; isolated non-finite gradient entries are set to
zero. These sentinels let a line search backtrack from pathological
trial parameters and are not part of the regular finite-utility
likelihood. The kernel’s list also holds overflow,
TRUE where it replaced anything (a clamped log probability,
the sentinel, a gradient entry set to zero): the optimizers do not see
it, and the polish (§12.7) rejects a trial point that sets it.
Code reference: src/mnlogit.cpp;
the flag, logit_sanitize() in src/choicer_internal.h
12.6 Inverting the Information
Every reported variance of
is the inverse of an estimate of the information matrix, or a sandwich
built on one:
with
the negated Hessian
of §4 (se_method = "hessian") or the BHHH matrix
of §11.3 ("bhhh"), or
with the bread
and meat
of §11.3 ("sandwich") or §11.5 ("cluster"). In
the data’s units the diagonal of
can span many orders of magnitude: a covariate measured in thousands
next to one measured in thousandths, or the constant of an alternative a
handful of individuals chose next to that of one most chose. Inverted as
it is, such a matrix can be refused as computationally singular although
only the units make it so (solve() refuses a matrix whose
estimated reciprocal condition number falls below the machine epsilon,
and the units alone can push it there), and a sandwich built on it can
lose digits. Every fit, whatever the coordinates its optimizer used
(scale_vars; §1.5 of the mixed logit article), therefore inverts
the equilibrated matrix:
with
the vector of the diagonal entries of
and the functions applied elementwise:
holds the powers of two nearest, on a log scale, to the inverse square
roots of the diagonal’s magnitudes, with an entry of 1 where the
diagonal entry is zero or not finite and every entry clamped to
.
For the sandwich,
with
and
from
.
Any
leaves
unchanged in exact arithmetic, and powers of two make the products with
exact too, barring overflow or underflow: only the
factorization and the solves round (for the sandwich, also the
symmetrization below), on a matrix whose diagonal is within a factor of
two of one in magnitude except where a diagonal entry is zero or not
finite, or an entry of
is clamped. The magnitude of the diagonal is used so that an information
that is not positive definite (away from a maximum) is equilibrated too,
and its negative variances reported: their standard errors are
NA, with a message.
is formed in one working copy, which LAPACK factors in place
(
with partial pivoting) with solve()’s checks: a pivot that
is exactly zero is an error, and so, when every factor is finite, is a
reciprocal condition number (estimated in the 1-norm) below the machine
epsilon; either error leaves the fit without a variance, its standard
errors NA, with a message. The identity is then solved
against the factors into the result, as reference LAPACK’s
dgesv does for solve(), with two
matrices besides
(
the number of parameters) where solve() holds three. The
sandwich is solved twice against the factors of
,
first
and then the transposed system
,
without forming an inverse: two
matrices besides
and
where an explicit inverse and two products hold four, and
operations against
.
is symmetrized,
,
before
is applied. At
each such matrix takes 2.3 GB. The working copy is freed as the call
returns, and the package’s own passes over whole matrices (the scaling,
the scan of the factors for non-finite entries, the transposition and
the symmetrization) run in parallel over columns, without sums across
threads, so they do not depend on the number of threads. The fit and
post-hoc vcov(fit, type = ) and wesml_vcov()
take this same route.
Against an exact computation on the package’s reference battery and tests (963 inversions of 477 distinct matrices, of 2 to 13 parameters), a raw inversion refused 52 as singular; equilibrated, 44 of them, with raw condition numbers from to , had condition numbers below 20 and came out with standard errors within about relative of exact, while the other eight stayed ill-conditioned or singular. Equilibration removes the ill-conditioning that the parameters’ units cause, not the likelihood’s own: a matrix that stays ill-conditioned after it (a likelihood nearly flat along a combination of parameters, which no rescaling of the parameters one by one removes) keeps only the digits its condition number allows, by any inversion, and one singular to working precision is refused either way.
Code reference: invert_hessian(),
.sandwich_combine() and .jacobi_scale() in R/classes.R;
equilibrated_inverse() and
equilibrated_sandwich() in src/vcov.cpp.
12.7 Polishing the Optimizer’s Solution
run_mnlogit(polish = ) follows the optimizer with the
Newton phase of the mixed logit
(§5.7 there), which finishes the climb to the maximum of the same
log-likelihood and certifies it; the estimator does not change. With
the gradient of
and
the curvature, the information
of §4 (polish = "newton") or the BHHH matrix
of §11.3 ("bhhh", its weights unsquared), the polish
converges when the Newton decrement
over the mean weight
,
falls below tol_decrement
().
On a positive definite
the remaining Newton step then moves every linear combination of the
estimates by at most
of its Hessian standard error; with "bhhh" the bound is in
robust standard errors (for an unweighted fit; with weights, in the
metric of
with
’s
weights unsquared), and a small BHHH decrement on its own shows only a
stationary point. The steps, their damping and maximum length, and the
line search are those of the mixed logit’s §5.7 (the multinomial logit
has no bounds).
The multinomial logit’s log-likelihood is concave: with the rows of situation ’s design, the constants’ indicators included, and its probabilities, is positive semidefinite everywhere. Wherever it is positive definite (the model identified at the current point) and not singular to working precision, the Newton step needs no damping, and the maximum the polish certifies is the global one.
A trial point fails where the likelihood kernel reports that its
objective or gradient is not the log-likelihood’s (§12.5): a chosen log
probability clamped to
,
a total that is not finite, or a gradient entry set to zero. The
constant of an alternative never chosen has a negative score at every
,
and that of one chosen wherever it is offered a positive one, so neither
has a finite estimate (run_mnlogit() warns of them); the
polish holds the constants of such inside alternatives at the
optimizer’s values, and the certificate concerns the other parameters
given them. Where the reference itself (the base alternative, or the
outside option) is the one without, the other constants diverge
together, and the polish does not report convergence unless the
reference is never chosen and the held constants anchor all the others,
which stops their rise. An alternative is anchored if its constant is
held, or if it is offered in a choice situation whose chosen alternative
is anchored. With every constant that can rise anchored, any direction
of the constants that raises a set of them meets the situation that
anchored the member of the set anchored first; there the chosen
alternative, outside the set, has a probability that falls to zero, and
with it the log-likelihood. A held alternative chosen only where it is
offered alone anchors nothing.
The polish’s maximum step and its stall rule are measured in the
optimizer’s coordinates
(§1.5 of the mixed logit article). Under
scale_vars = "none" those would be the parameters’ own
units, in which a column measured in thousandths needs coefficient steps
of hundreds, so the scales come instead from the BHHH diagonal at the
optimizer’s solution, as "bhhh" takes them at the start
values: one pass of the gradient kernel. The variance is computed at the
polished estimates, by se_method, and the polish’s last
curvature, evaluated at the point it returns, is not evaluated again
where it is the variance’s own matrix: after "newton" the
Hessian of "hessian" and the bread of
"sandwich" and "cluster", after
"bhhh" the BHHH matrix of "bhhh".
On census- and claims-style designs (2,504 and 2,602 alternatives
with 24,560 and 245,031 choice situations; 499 and 500 alternatives with
17,339 and 153,721 situations; ten covariates; constants without a
finite estimate removed; single runs at eleven threads, times modeled
from the kernels’ calls) the default fit
(scale_vars = "bhhh") stopped at the maximum in 29 to 42
evaluations, and the Newton polish certified it at once: with its
Hessian serving the variance, it added one gradient pass and one
Cholesky factorization, 3 to 13% of the modeled time of the fit and its
variance. With scale_vars = "none" the optimizer stopped up
to 9.2 log-likelihood units short, at its limit of 1,000 evaluations on
three of the designs, and the polish closed the gap in 1 to 6 steps.
With half of the covariates rescaled by
and the other half by
,
20 steps at unit scales left a decrement of 1,130 to 2,060, where 8 or 9
at the BHHH scales certified the maximum.
Code reference: run_polish(),
.polish_held(), .polish_anchors(),
.polish_fit() and .polish_scales() in R/classes.R;
newton_step() in src/newton.cpp;
the curvature and its reuse in run_mnlogit(), R/mnlogit_utils.R;
the kernel’s report, logit_sanitize() in src/choicer_internal.h.
References
- McFadden, D. (1974). Conditional logit analysis of qualitative choice behavior. In P. Zarembka (Ed.), Frontiers in Econometrics (pp. 105-142). Academic Press.
- Train, K. E. (2009). Discrete Choice Methods with Simulation (2nd ed.). Cambridge University Press.
- Berry, S. T. (1994). Estimating discrete-choice models of product differentiation. RAND Journal of Economics, 25(2), 242-262.
- Berry, S., Levinsohn, J., & Pakes, A. (1995). Automobile prices in market equilibrium. Econometrica, 63(4), 841-890.
- Berry, S., Gandhi, A., & Haile, P. (2013). Connected substitutes and invertibility of demand. Econometrica, 81(5), 2087-2111.
- Fukasawa, T. (2024). Fast and simple inner-loop algorithms of static / dynamic BLP estimations. arXiv:2404.04494.
- Walker, H. F., & Ni, P. (2011). Anderson acceleration for fixed-point iterations. SIAM Journal on Numerical Analysis, 49(4), 1715-1735.
- Varadhan, R., & Roland, C. (2008). Simple and globally convergent methods for accelerating the convergence of any EM algorithm. Scandinavian Journal of Statistics, 35(2), 335-353.
- Manski, C. F., & Lerman, S. R. (1977). The estimation of choice probabilities from choice based samples. Econometrica, 45(8), 1977-1988.
- Manski, C. F., & McFadden, D. (1981). Alternative estimators and sample designs for discrete choice analysis. In C. F. Manski & D. McFadden (Eds.), Structural Analysis of Discrete Data with Econometric Applications (pp. 2-50). MIT Press.
- Cosslett, S. R. (1981). Maximum likelihood estimator for choice-based samples. Econometrica, 49(5), 1289-1316.