Choosing a Demeaner Backend

performance
fixed effects
How to pick the right fixed-effects demeaner for your problem.

PyFixest exposes several demeaner backends via the demeaner= argument. All backends produce numerically equivalent results; the choice only affects performance, which itself depends on the structure of the fixed effects and the size of the dataset.

For a deep dive on why some fixed-effects problems are harder than others — and detailed benchmarks comparing all backends — see When Are Fixed Effects Estimations Difficult?.

import pyfixest as pf
from pyfixest.demeaners import LsmrDemeaner, MapDemeaner

df = pf.get_data()

Quick Reference

What are dense / well-connected vs sparse / weakly-connected fixed-effect structures? The typical example for “dense” fixed effects is a balanced panel - each unit appears exactly once for every single time period. In contrast, a “sparse” or “weakly” connected fixed effect structure arises when units appear in only a few time periods. For example, in a matched employer-employee panel, each worker may only appear in a handful of firms.

Backend When to use
MapDemeaner(backend="rust") Fast for dense fixed effects with well-connected graphs. No optional dependencies required.
MapDemeaner(backend="numba") An alternative MAP implementation written in numba. Requires installation via pip install pyfixest[numba].
LsmrDemeaner() Default. Uses modified LSMR from the within Python package (within-py). Its adaptive preconditioner starts with diagonal preconditioning and switches to additive Schwarz if convergence stalls. Well suited to sparse fixed-effect structures (e.g. matched employer-employee data). You can also use additive Schwarz from the start or keep diagonal preconditioning throughout, which can work well for dense fixed effects. Disabling preconditioning is rarely useful outside benchmarking.
LsmrDemeaner(backend="torch", device="cpu") LSMR solver on CPU via PyTorch. Requires pytorch.
LsmrDemeaner(backend="torch", device="cuda") LSMR solver on CUDA GPUs via PyTorch. Experimental. Requires pytorch, plus a CUDA-enabled PyTorch build (see PyTorch install instructions).
LsmrDemeaner(backend="torch", device="mps", precision="float32") LSMR solver on Apple Silicon GPUs via PyTorch MPS. Experimental. In our experience, MPS provides little performance improvement, but we’d love to hear about differing experiences! Requires pytorch.

pyfixest defaults to LsmrDemeaner(backend="within", preconditioner="auto"). Numba is now an optional dependency: you can install it via pip install pyfixest[numba] if you want to use MapDemeaner(backend="numba") or the fast ritest path. The torch-based LSMR backends require pytorch, which you can install manually or via pip install pyfixest[torch]. For GPU acceleration on CUDA, you additionally need a CUDA-enabled PyTorch wheel from the PyTorch installation guide.

Usage

To select a demeaner backend, you need to pass an instance of the desired demeaner to the demeaner argument of feols:

# Default: within LSMR with adaptive preconditioning
fit = pf.feols("Y ~ X1 | f1", data=df)

# Rust MAP – explicit
fit = pf.feols("Y ~ X1 | f1", data=df, demeaner=MapDemeaner(backend="rust"))

# Numba MAP (requires pip install pyfixest[numba])
fit = pf.feols("Y ~ X1 | f1", data=df, demeaner=MapDemeaner(backend="numba"))

# `within` LSMR backend – best for sparse multi-way FE structures.
# Defaults to the adaptive preconditioner: diagonal first, escalating to
# additive Schwarz only when convergence stalls.
fit = pf.feols("Y ~ X1 | f1 + f2", data=df, demeaner=LsmrDemeaner())

# `within` LSMR with the additive Schwarz preconditioner from the start;
# best for sparse / weakly connected fixed effects.
fit = pf.feols(
    "Y ~ X1 | f1 + f2",
    data=df,
    demeaner=LsmrDemeaner(preconditioner="additive"),
)

# `within` LSMR with the diagonal (Jacobi) preconditioner - cheaper to set up,
# often a good choice for denser / well-connected fixed effects.
fit = pf.feols(
    "Y ~ X1 | f1 + f2",
    data=df,
    demeaner=LsmrDemeaner(preconditioner="diagonal"),
)

# you can also turn off the preconditioner; this is almost never recommended
# we only offer it for benchmarking / users who are curious to learn how much
# the preconditioner helps
fit = pf.feols(
    "Y ~ X1 | f1 + f2",
    data=df,
    demeaner=LsmrDemeaner(preconditioner="off"),
)

The MapDemeaner accepts fixef_tol and fixef_maxiter arguments to control convergence. LsmrDemeaner uses fixef_atol and fixef_btol. For the within backend the two tolerances are collapsed to max(fixef_atol, fixef_btol) (the solver takes a single tolerance); torch uses both independently (SciPy LSMR convention).

Both LSMR tolerances default to 1e-8, matching within’s default. They control solver convergence, not the error in each demeaned value or derived statistic. Small demeaning errors can be amplified in quantities such as large t-statistics. Lower both tolerances if you need a tighter solve.

fit = pf.feols(
    "Y ~ X1 | f1",
    data=df,
    demeaner=MapDemeaner(backend="rust", fixef_tol=1e-10, fixef_maxiter=50_000),
)

Caching and Pickling the within Preconditioner

The within LSMR backend can build a preconditioner from the fixed-effect design before the iterative solve for two or more fixed-effect factors. The default is adaptive: it starts with a cheap diagonal (Jacobi) preconditioner and builds the additive Schwarz preconditioner only when convergence stalls. preconditioner="additive" builds additive Schwarz up front, and preconditioner="diagonal" never escalates. For single fixed effects, PyFixest falls back to closed form demeaning (via the MAP algo, which converges in one iteration) and no preconditioner is computed or applied. For large multi-way FE problems, setting up the preconditioner can be a meaningful fraction of total runtime, so it is worth reusing the preconditioner across solves on the same design.

Within a session

Every fit produced with LsmrDemeaner(backend="within") exposes the preconditioner used during demeaning via the preconditioner attribute:

fit = pf.feols("Y ~ X1 | f1 + f2", data=df, demeaner=LsmrDemeaner())
pre = fit.preconditioner
print(pre)
Preconditioner(Adaptive, n=60)

The preconditioner instance returns the reusable preconditioner, along with metadata such as its configuration (pre.config) and how long it took to build (pre.build_duration_seconds). It is a within.Preconditioner, which pyfixest re-exports as pf.Preconditioner. An adaptive preconditioner that escalated during the solve is returned as the additive Schwarz preconditioner.

After creating a preconditioner, you can pass that instance back through LsmrDemeaner(preconditioner=...) on a later fit to skip the setup phase:

fit_reused = pf.feols(
    "Y ~ X1 | f1 + f2",
    data=df,
    demeaner=LsmrDemeaner(preconditioner=pre),
)

pf.etable([fit, fit_reused], digits = 6)
Y
(1) (2)
coef
X1 -0.919***
(0.060)
-0.919***
(0.060)
fe
f1 x x
f2 x x
stats
Observations 997 997
R2 0.609 0.609
Significance levels: * p < 0.05, ** p < 0.01, *** p < 0.001. Format of coefficient cell: Coefficient (Std. Error)

When you use multiple-estimation syntax, FixestMulti shares compatible within preconditioners across sibling models that are fit on the same sample with identical fixed-effect structure. This happens automatically; you only need to use LsmrDemeaner(backend="within") or a within preconditioner option such as preconditioner="diagonal".

For GLMs that rely on iterated weighted least squares (IWLS, in fepois and feglm), the first solve builds a preconditioner or uses the supplied prebuilt handle. Subsequent solves reuse it while projecting with their current working weights. Demeaned columns are recomputed each time because the weights change. The preconditioner can become less effective as the weights move, increasing the number of LSMR iterations, but reuse avoids paying its construction cost on every IWLS iteration. The current weights still determine the target projection.

If an adaptive solve escalates to additive Schwarz, the cache retains the additive replacement, including when the original request was a prebuilt adaptive handle. Later iterations and compatible sibling models reuse it without repeating escalation and construction.

As for OLS/IV, each GLM’s fit.preconditioner exposes the shared cache entry for its retained sample: the initial handle or its additive replacement. It can be inspected, serialized, or explicitly reused on the same fixed-effect design.

Across sessions

Preconditioner instances are pickleable, so the setup phase can be amortised across Python sessions:

import pickle
import tempfile, os

# session 1: build and save
fit = pf.feols("Y ~ X1 | f1 + f2", data=df, demeaner=LsmrDemeaner())
tmp = os.path.join(tempfile.gettempdir(), "precond.pkl")
with open(tmp, "wb") as f:
    pickle.dump(fit.preconditioner, f)

# session 2: load and reuse
with open(tmp, "rb") as f:
    pre = pickle.load(f)

fit2 = pf.feols(
    "Y ~ X1 | f1 + f2",
    data=df,
    demeaner=LsmrDemeaner(preconditioner=pre),
)

pf.etable([fit, fit2], digits = 6)
Y
(1) (2)
coef
X1 -0.919***
(0.060)
-0.919***
(0.060)
fe
f1 x x
f2 x x
stats
Observations 997 997
R2 0.609 0.609
Significance levels: * p < 0.05, ** p < 0.01, *** p < 0.001. Format of coefficient cell: Coefficient (Std. Error)
Warning

Preconditioner instances are tied to specific fixed effect structures. within validates that the preconditioner’s DOF count matches the new design; a dimension mismatch raises ValueError. It does not check whether the FE structure matches when the dimensions happen to coincide; reusing on a different-but-same-size FE design will still run but may converge more slowly or fail to converge. It is the user’s responsibility to ensure that the preconditioner is reused on the same FE structure.