Changelog¶
0.13.4¶
An IV formula with no fixed effects reads interactions among its instruments correctly with pyfixest 0.60. In
y ~ 1 | d ~ C(q) + C(q):x0, the second|part is the instrument block, but it was read as the fixed-effect part and its:rewritten as^, which pyfixest then rejected. A second part containing~is now left as written. pyfixest 0.60 is the version Python 3.10 installs.
0.13.3¶
An exactly collinear covariate is dropped however large the sample or its weights. The collinearity check, pyfixest’s sequential Cholesky test with
collin_tol, compared each column’s pivot with an absolute tolerance. An exactly collinear column’s pivot is rounding error of the order of its diagonal times the machine epsilon, so on a large or heavily weighted sample it could fall on either side of 1e-10, and whether the column was dropped depended on the order of the sums. On 100,000 commuters, a Poisson fit kept a non-citizen indicator that nativity and the other citizenship levels determine exactly. A column is now also dropped when its pivot is at most 1e-9 of its own diagonal; every column the absolute test drops is still dropped.The check runs in hdfe-stream’s own kernel (
core.collinear), in place of pyfixest’s: the same algorithm, with the factor stored so that its inner products read contiguous memory. With 3,000 covariates it takes 3 s instead of 21 s, with 6,000 covariates 26 s instead of 6 minutes.The Newton pass keeps each thread’s sums for the whole pass.
core.newton’s row kernel (feglm_streamandfepois_streamwith no fixed effect or one, and the packages built onGLMDesign.newton_pass) zeroed and added up every thread’s copy of the sums for every chunk; at a wide information’s c x c per thread and model, that cost as much as the rows. They are now zeroed once and added up once per pass. A penalized Poisson path with about 1,000 indicator columns on 30,000 rows is about 25% faster; narrow passes are unchanged or a few percent faster.
0.13.2¶
A wide design with fixed effects no longer holds memory that grows with the rows. Chunks were 2,000,000 rows and pass 0’s buckets at least 500,000 rows whatever the design’s width, so with about 2,000 indicators and one fixed effect
feols_streampeaked at 22 GB at 300,000 rows, ignoringmax_memory_gb. Chunks are now about 256 MB of the design and buckets about 384 MB of rows (at least 50,000); from about 190 to 620 columns, buckets of up to 1 GB, each read in one chunk. Up to 12 columns nothing changes.Pass 0’s row restrictions (connected set, singletons, separation) on a wide design read a narrow copy of the columns they need, written a batch at a time, instead of a query over the evaluated design, in which Polars held a morsel of every design column per thread (12.5 GB from a million rows on, with 2,000 indicators). The rows dropped are the same.
With 503 indicators and worker and firm fixed effects on 8.5 million rows, the fit takes 101 s at 11.0 GB (95 s at 17.2 GB with 0.13.1’s sizes); with 167, 42 s at 4.0 GB (41 s, 6.5 GB). With about 2,000 indicators and one fixed effect the peak is about 4 GB at 300,000 rows.
core.crossprodwith fixed effects uses the same chunks and buckets.
0.13.1¶
core.crossprodforms the cross-products of sparse rows from each row’s nonzeros. A chunk with at most 20% of its entries nonzero (and at least 32 columns), as a design of indicators without fixed effects is, has its products summed over each row’s nonzeros into its own split’s sums, with no per-thread copies of the sums. Other chunks, including the residualized rows of every fit with fixed effects, keep BLAS. On 150,000 rows of 1,973 indicator columns (about 150 nonzeros a row), the products were 20, 8 and 4 times faster with 1, 5 and 20 splits. The estimators’ own passes are unchanged.
0.13.0¶
Faster logit, probit and Poisson fits with no fixed effect or one, a public Newton pass
for packages built on hdfe_stream.core, and lower peak memory for wide designs without
fixed effects.
feglm_streamandfepois_streamwith no fixed effect or one fit by Newton’s method on compact stored rows instead of IRLS on partitioned Parquet files. Each step is one read of the rows. The fixed effect is profiled out exactly, and for a design of indicators the products run over each row’s nonzeros only. The result is the sameHDFEResultas before: the same sample (singletons, then separated levels), coefficient names, collinearity rule, vcov flavors and small-sample factors, fit statistics, andfixef,resid,predictandsample.On a logit of 1 million people on 153 indicators, the fit takes about 10 s without a fixed effect (about 30 s before) and about 12 s with 2,462 PUMA fixed effects (about 65 s before). In the benchmark of 20 million rows on 10 dense covariates, the logit took 6.0 s (8.9 s before) and the probit 7.0 s (9.5 s).
Each pass forms the information one of two ways, chosen by the design’s shape: a fused row kernel, which works from each row’s nonzeros for a design of indicators, up to about 96 columns for dense rows and about 1,000 for indicators; and BLAS matrix products beyond, which are 1.3 to 2 times faster there. The heteroskedasticity-robust variance’s sums come from the same kernel, so without clustering the final read makes no copy of the design.
The fit follows
max_memory_gbas the other fits do: each thread’s copy of a pass’s sums takes its share of at most half the headroom (fewer threads on a pass when memory is tight), a pass whose sums do not fit raisesMemoryErrorbefore it reads the rows, the information kept for logit-stream’s draws is left off the result when it would take more than half the headroom, anddiagnostics["peak_rss_gb"]records the peak.The estimates move slightly, toward the maximum: Newton’s method stops on the decrement, IRLS on the change in deviance, which at its default tolerance can leave the coefficients about 1e-6 (relative) from the maximum.
Without a fixed effect, pass 0 reads the source a batch at a time rather than copying the sample first. Once the decrement passes the test, the last step is taken without another read when it is too small to change the information (each row’s linear predictor moves by less than about 1e-8).
save_resid=Falsekeeps this path and leaves the residual file unwritten, as for IRLS.With
device="cuda"(experimental) the Newton steps run on the GPU, with one fixed effect as well as without; before, a GPU did nothing for a GLM with one fixed effect.Two or more fixed effects, multiple estimation,
bias_correctionand the separation check switched off still fit by IRLS. With multiple estimation or the check switched off, a model with no fixed effect or one gets Newton’s method first, and IRLS takes the final step.
IRLS with an
iwls_tolbelow rounding (about 1e-12 relative) stops once a step no longer lowers the deviance. It previously could reject a step whose deviance was higher by rounding alone and raise “IRLS step-halving failed”.core.newton(glm_design,GLMDesign,NewtonMoments): the stored design of a logit, probit or Poisson model with no fixed effect or one, and a pass that gives the log-likelihood, gradient and information of several models in one read, each on its own splits (cross-validation folds, say), with the fixed effect profiled out exactly. It is a stable API for estimators that run their own iteration, such as a penalized GLM’s path.core.distinct.count_distinct: distinct counts of columns or combinations of columns, among the rows a filter keeps. The default is HyperLogLog’s approximate count in one streaming pass, as before. Withexact=Truethe count is exact: one streaming pass when Polars’ hash tables (about 50 bytes a value for one column, 120 for two) fit half the memory headroom, and otherwise k passes, each counting the values whose hash falls in one of k parts.scan_source(exact_distinct=True)uses it. The fits still choose how to stream a fixed effect from the approximate count.Pass 0’s row write without fixed effects is chosen by the design’s width. Polars’ streaming sink of the evaluated design, the faster write, buffers up to a row group per thread of every design column, so on a wide design its memory grew with the number of rows up to several million. The rows are now sunk when that buffer (threads x
row_group_sizex columns x 8 bytes) fits a quarter of the memory headroom, as for a design of tens of columns. Otherwise the source’s own columns are read a batch at a time, the design evaluated on each batch, and the rows written with a Parquet writer. With about 2,000 indicators,feols_streampeaked at 16.9 GB at 1 million rows; it now peaks at 11.2 GB, the same as at 300,000 rows, and is about 30% faster (133 s instead of 188 s). The write itself fell from 16.5 GB to 2.6 GB.The batch write applies when every design and weight expression is row-wise, as formula-built designs always are, and with the CPU engine. Otherwise the evaluated design is sunk as before.
0.12.1¶
Lower peak memory for designs with many columns, such as a categorical expanded into hundreds or thousands of indicators. Estimates are unchanged.
Pass 0’s scan (counts, means and variances) aggregates the design’s expressions directly instead of first evaluating every design column. Polars’ streaming engine buffered whole chunks of the evaluated columns, so the scan’s memory grew with the number of rows. With about 2,000 indicators it reached 6 GB at 1.6 million rows; it now takes a few hundred MB. This applies with and without fixed effects.
core.crossprodwithout fixed effects reads the source’s own columns a batch at a time and evaluates the design on each batch. It previously read a query that held the evaluated design, which Polars’collect_batchesdid not keep bounded. With about 2,000 indicators the pass ran past 14 GB at 1.6 million rows. It now peaks at about 8.4 GB from 400,000 rows up, set by the batch size rather than by the number of rows, and is about 7% faster at 400,000 rows. With 50 variables the pass’s peak fell from 2.4 GB to 1.1 GB at 5 million rows, in the same time.Both changes apply when every design and weight expression is row-wise, as formula-built designs always are. Otherwise, and in
core.crossprodwhen cluster codes are joined onto the rows, the design is evaluated as before.
0.12.0¶
Adds Rambachan and Roth’s sensitivity analysis for parallel trends, and studentized intervals
to the refit bootstrap for the packages built on hdfe_stream.core. Fits are unchanged.
HDFEResult.trend_sensitivity: confidence intervals for an event study’s post-treatment effect that remain valid when parallel trends fails by up to M, measured against the pre-treatment coefficients (Rambachan and Roth, 2023), for a regression with leads and lags named byi(). The restrictions (relative magnitudes, smoothness, and both together, each with an optional sign or monotonicity restriction), the four intervals (FLCI, conditional, and the two hybrids) and their defaults are those of the authors’ R package HonestDiD 0.2.8, and the intervals agree with it at every point of its grid. The linear programs of the conditional tests are solved in compiled code, each from the previous solution, which makes a relative-magnitudes analysis a few hundred times faster than the R package. See Sensitivity to parallel trends for the few deliberate differences.core.sensitivity(stable names): the same from any event study’s coefficients and covariance (trend_sensitivity,event_study_sensitivity), for the packages built onhdfe_stream.core; diff-stream’s estimators use it.core.crossprod(stable namescross_products,CrossProducts): the cross-products of a set of variables with the fixed effects partialled out, as a fit partials them out, summed separately for each value of an integer column, such as a fold or shard number. One pass over the rows after the solve gives every fold’s cross-products, which is what K-fold cross-validation of a lasso, ridge or elastic net needs without reading the data again. Without fixed effects the pass reads the source itself rather than a copy of it.save_rows=Truealso writes the residualized rows to Parquet, with anycarry=columns, for estimators that need more passes over them.CrossProducts.sample()reports the sample asHDFEResult.sample()does.HDFEResult.plot_event_study: an event study’s coefficients and intervals (pointwise or simultaneous) by event time, with the omitted reference period at zero, as pyfixest’siplotdraws it (core.plots.event_study_plotfor any event study).Studentized bootstrap intervals (
core.refit). ARefitBootstrapResultgiven each refit’s standard errors (original_seand_se_draws) gives bootstrap-t intervals,confint(method="studentized")(equal-tailed) andmethod="symmetric", andstandard_error_draws(). A draw with a finite estimate but no finite standard error counts as failed for these intervals only, so they then needallow_incomplete=True.Each copy of a resampled cluster has a cluster ID of its own (
core.refit,core.resample). Whenrefit_drawsresamples clusters (within=), the task’sgroup_columnnames a column holding the copy’s ID, so that a refit whose estimates depend on the clusters (a clustered weight matrix, say) counts two copies of one cluster as two clusters. The original cluster column is unchanged.Plots need matplotlib, which is not a dependency: install it, or the new
plotextra (pip install hdfe-stream[plot]). Everything else works without it.
0.11.1¶
Two fixes to HDFEResult.solve_normal_equations, which packages built on hdfe-stream use
for the influence of a fit’s rows on what is predicted from it.
A model with one fixed effect (
y ~ x | firm) raised anIndexError. It now solves its normal equations, which with one fixed effect need no iterative solve.A fixed effect nested in another (
y ~ x | county + state, every county in one state) made the solve run to the solver’s iteration limit: thousands of iterations, 17 to 51 seconds on 2,000 rows against 0.2 seconds for fixed effects that are not nested. Once the first fixed effect is partialled out, the nested one has nothing left to explain, and the solver chased rounding error. Right-hand sides that are negligible after that step are now solved by zero without iterating, as the fit already did. The solutions were and are correct; only the time changes. Fixed effects that are partly nested (a few levels inside one level of another) were not affected.
0.11.0¶
Adds a refit bootstrap and a warning class for experimental methods to hdfe_stream.core, for
the packages built on it. Fits are unchanged.
A refit bootstrap for packages built on
hdfe_stream.core(core.refit). It resamples whole units, or whole clusters of units (each copy’s units with IDs of their own), with replacement, writes each draw to disk in bounded memory, and refits a consumer’s estimator on it, in the same process or in worker processes with their share of the job’s threads and memory. The workers start once and fit one draw after another (restarted every 200 draws), with one resample per worker on disk at a time. Failed draws are recorded, never redrawn;RefitBootstrapResultgives bootstrap standard errors and percentile, basic and normal intervals. Its parts are stable names too:core.partition(whole-group partitions on disk),core.resample(DiskGroupResampler) andcore.process(ProcessBatch). They were diff-stream’s, and diff-stream’srefit_bootstrapnow uses them.ExperimentalWarning(hdfe_stream.ExperimentalWarning, alsohdfe_stream.core.report.ExperimentalWarning): a warning class for methods that go beyond what their authors developed. Packages built onhdfe_stream.coresubclass it for their own experimental features, so filtering this class silences all of them.
0.10.0¶
Works with pyfixest 0.70 as well as 0.60, and accepts pyfixest 0.70’s formula syntax. Fits with many variables no longer slow down sharply under a tight memory limit. The RMSE with analytic weights is defined as in fixest.
pyfixest 0.60 through 0.70. Formulas,
etable,summaryandiplotwork with either. Install either version withhdfe-stream[formula].Fixed-effect interactions can be written
firm_id:year, as in pyfixest 0.70.firm_id^yearstill works with both versions, without a deprecation warning.Instrumental variables can be written
y ~ x + [endog ~ instrument] | fe(pyfixest 0.70 and later).y ~ x | fe | endog ~ instrumentworks with both versions.Several outcomes can be written
sw(y, y2) ~ x.y + y2 ~ xstill works.Varying slopes can be expressions (pyfixest 0.70 and later):
worker_id[t, t ** 2]. They can also be on an interacted dimension,worker_id:firm_id[t]. Slopes without the intercept,worker_id[[t]], are not available yet and say so.Coefficient and model names are pyfixest’s own for the version installed. With pyfixest 0.70, a model’s
fmlis pyfixest 0.70’s spelling of it (y ~ 1 + x,a:b).For packages built on
hdfe_stream.core:hdfe_stream.core.formula.parse_formulareturns the models of a formula in one form for both pyfixest versions, in place of reading pyfixest’s parsed formula directly.pyfixest_formula_apiis unchanged.The RMSE of a fit with analytic weights no longer depends on the scale of the weights. It is now the weighted sum of squared residuals divided by the sum of the weights, as in fixest and pyfixest 0.70, where it was divided by the number of rows. The two are the same when the weights average 1, and without weights or with frequency weights. With other analytic weights the RMSE changes: multiplying every weight by
cused to multiply it bysqrt(c). Coefficients, standard errors and R-squared are unchanged. pyfixest 0.60 still divides by the number of rows.Benchmarks re-run with pyfixest 0.70.0, whose default demeaner (LSMR) is the one compared against; the alternating-projections (MAP) demeaner is no longer benchmarked. pyfixest 0.70.0’s Poisson fit fails on the 1,000,000- and 5,000,000-worker panels, which 0.60.0 fit at 1,000,000.
Fits with more than 8 variables are much faster under a tight memory limit. The solve needs an array with a row for every fixed-effect level and a column for every variable. When that array was more than a fifth of the memory left under
max_memory_gb, the fit instead wrote a file of every cell’s sums (30 GB or more on a large panel) and read all of it back for each group of 8 variables. Now the array goes into a file of its own, which is far smaller (0.8 GB for 2 million levels and 50 variables), and the solve reads it one group at a time. In diff-stream, Sun-Abraham on 10 million units with a 4 GB limit took ten times as long as without a limit (1,742 seconds against 173) and used 36.5 GB of scratch disk. It now takes about 1.3 times as long (242 seconds against 191, measured on a machine with half the cores) and about 5 GB. The estimates agree with the fit that keeps the array in memory to 1e-15. Fits with 8 or fewer variables, and fits where the array fits in memory, are not affected.The array’s file stops counting against the memory limit once the first pass ends. The pages of a memory-mapped file count as memory in use, and with them counted a fit near its limit could find no room left and choose slower methods for the solve. The file is now released when the first pass finishes and read back a block at a time. In the same fit, the solving step went from 95 to 56 seconds.
0.9.2¶
Faster fits on large panels with many variables, and less scratch disk. Results are unchanged.
Large fits with more than 8 variables are faster. An example is Sun-Abraham’s estimator in diff-stream, which has a variable for each cohort and period. Before, the fit worked through the variables 8 at a time, and for each group of 8 it read the whole file of stored cell sums from disk. When that file is bigger than the computer’s memory, those repeated reads were most of the run time. The fit now gets what it needs from the sums as it writes them, so the file is not read again. On 8 million units (64 million rows), the solving step dropped from 284 to 19 seconds and the whole fit from 542 to 294 seconds. The process also holds less memory: its peak fell from 20.6 to 7.1 GB, because the file’s pages no longer pile up in memory. When the file is small enough to stay in memory, there is little change in speed.
Less scratch disk. That file of cell sums is now written only when something reads it: the
withinsolver, the cell-based way of building the normal equations (the default for 8 or fewer variables), or the old one-group-at-a-time path described above. For other fits, a wide design for example, it is not written at all. In the same Sun-Abraham fit with a million units, scratch disk use fell from 3.6 to 0.4 GB, and the saving grows with the number of rows.Memory limit. Building what the fit needs in one go takes the number of fixed-effect levels times the number of variables times 8 bytes. If that is more than a fifth of the memory left under
max_memory_gb, the fit works through the variables 8 at a time, as in 0.9.1, which is slower but uses less memory. Therhs_blockoption still sets the size of those groups.
0.9.1¶
HDFEResult.solve_normal_equations. Solves a linear fit’s normal equations for right-hand sides built from rows: for weight columns v_j of a frame, u_j = S^- Z’v_j, with S the fit’s weighted Gram matrix of fixed effects and covariates. The result,NormalEquationsSolution, gives the solutions as fixed-effect tables and covariate coefficients, andpredictgives z’u_j for any rows. For a weighted sum of predictions, w_i z_i’u_j is the weight that estimation row i’s outcome gets in it, which is what imputation estimators (Borusyak, Jaravel and Spiess) need for their standard errors; diff-stream uses it for BJS with high-dimensional fixed effects. It needs a fit made withkeep_intermediates=True. Nothing else changes.pyarrow 16 or later. The floor was pyarrow 14, but pyarrow 14 and 15 were built against NumPy 1 and fail to import with NumPy 2, which the other floors allow: the lowest versions resolved on Python 3.12 gave an installation that could not import. The NumPy floor is unchanged.
0.9.0¶
Building blocks for treatment-effect estimators in
hdfe_stream.core, moved from match-stream so that match-stream and diff-stream share them. Their names are stable (listed inhdfe_stream.core).core.influence: influence-function variances from per-cluster sums (one-way and multi-way), the weighted mean difference, and the joint variance of estimators fitted on different tables.ClusterScoreAccumulatorbuilds the one-way clustered variance batch by batch, in memory that does not grow with the number of clusters: 0.8 GB, against 4.5 GB, for 2 million clusters and 20 estimators.core.mestimation: a fitted logit or probit first stage, and the correction of an influence function for estimating it.core.ipw: inverse-probability weights, and the IPW difference in means corrected for the estimated score.core.balance: a weighted two-group balance table (means, standardized mean differences, variance ratios, eCDF gaps) with MatchIt’s conventions. Covariates with zero variance are allowed: a standardized difference whose scale is 0 is 0, or ±inf when the means differ, and the variance ratio is inf when only the control group’s variance is 0, null when both are.
Less memory reading Parquet in batches.
core.store.iter_batchesanditer_groupsno longer use pyarrow’s pre-buffering, which held the selected columns of the whole file as it read: 4.7 GB extra for a 4.4 GB file, now 0.3 GB. Packages built on them gain most: logit-stream and dpd-stream fits peak 0.25-0.5 GB lower. Results are unchanged.Memory tests.
pytest -m resourcefits OLS and a logit on a 10-million-row panel in a child process under a 1.6 GB limit, which a fit holding the 0.5 GB panel in memory would exceed (2.6 GB on macOS and 2.0 GB on Windows, where the memory measured includes mapped files or untouched allocations). CI runs them on Linux, macOS and Windows; the defaultpytestrun skips them. Thetestextra now includesstream-limits[testing].
0.8.0¶
Fit resources (CPUs and memory) are constrained to your job’s limits automatically. On a cluster (PBS, Slurm, or a container with cgroup limits), importing
hdfe_streamcaps the threads of Polars, numba, BLAS and pyarrow at the job’s CPU allocation, and with Polars 2.x gives Polars a memory budget so its streaming operations spill to disk instead of growing. Caveats: the Polars budget is a target for its buffers, not a hard cap on the process, and Polars 1.x has no such option, so there only the threads are capped. The caps must be in place before Polars is imported: importhdfe_streamfirst, or callstream_limits.set_limits()at the top of the script. With no limit found nothing changes. See “Resource limits and profiling” in the documentation.profile=True: estimate a fit’s memory and disk before running it.feols_stream,fepois_stream,feglm_streamandleave_out_ksstakeprofile=Trueand return ahdfe_stream.Profileinstead of a result: one streaming scan of the data, the model’s arrays sized from what it finds, an expected size and an upper bound for each, the peak by phase, andrecommend()/recommend().pbsas a resource request. Nothing is fitted and no run directory is made. The shared code (Profile,Component,scan_source) is inhdfe_stream.core.profilefor logit-stream and dpd-stream, which take the same option. See “Resource limits and profiling” in the documentation.Depends on the new
stream-limitspackage (standard library only), which does the limiting for all three packages and works on its own; its documentation covers the thread, memory and scheduler details.max_memory_gbandmemory_reserve: choices follow the memory left.max_s_gb’s default (25% of physical memory) and the CRV3,bootclusterand IV-diagnostics guards (25%) used the node’s memory and a fixed share of it, which a correctly sized PBS job always hit. They now ask whether their exact allocation fits in the headroom: the limit (the job’s allocation, ormax_memory_gb), less a reserve (memory_reserve, default 0.15), less what the process holds. S is built if it fits, otherwisestream_cgstreams it; per-thread accumulators drop to fewer copies; pass 0’s sort buckets shrink in a small allocation; what cannot shrink raisesMemoryErrorup front with the numbers.Removed:
max_s_gb. It capped the explicit S and the per-thread accumulators separately from the rest of the memory. The headroom rule above subsumes it: lowermax_memory_gbto tighten the whole fit, or givesolver="stream_cg"to skip the explicit S. Passingmax_s_gbis now aTypeError.n_threads=is scoped to the fit. It used to callnumba.set_num_threadsin the constructor and never restore it; it now holds numba and BLAS to that many threads for the length offit()(and ofleave_out_kss) and restores them.diagnostics["peak_rss_gb"]: the peak resident memory of each fit, from the kernel’s high-water mark (no polling).New
hdfe_stream.core.resourcesandhdfe_stream.core.profile(stable names).
0.7.0¶
device="cuda"runs GLMs without fixed effects on the GPU. Poisson, logit and probit with no fixed effects (feglm_stream,fepois_stream) did nothing on the GPU before: its solver exists only with two or more fixed effects. Now the rows are uploaded once and every IRLS step (the family’s terms, the weighted cross-products) runs on the device, so later steps do not read the Parquet rows again. If the rows do not fit in the device’s free memory the fit warns and uploads them again at each step. Sums are formed in a different order, so estimates agree with the CPU’s to rounding. Linear models (OLS, IV) are not yet on the GPU.Benchmarks for OLS, IV and logit/probit with zero or one fixed effects (
benchmarks/ols_benchmark.py,iv_benchmark.py,binary_benchmark.py), against scikit-learn, polars-ols, polars-ds, statsmodels, linearmodels, glum, pyfixest and R, and the same models on a GPU (benchmarks/general_gpu_benchmark.py, against cuML and CuPy). Results and discussion:docs/benchmarks/regression.mdand the plain-regressions section ofdocs/benchmarks/gpu.md. Thebenchmarkextra now installs the comparison packages.
0.6.2¶
Works with
polars-runtime-64(#5). With that runtime installed, polars’ row indices are UInt64 rather than UInt32, whatever the size of the data, and the level codes androw_idbuilt from them failed in NumPy (bincount) and numba. They are now Int64. No estimate changes; therow_idcolumn in the residual file is 8 bytes a row instead of 4.
0.6.1¶
Fix a minor performance regression introduced in 0.6.0 based on a fixed cost to the first fit in every process. No estimate changes.
The blocked copy that stacks a chunk’s columns is used only where it pays. 0.6.0’s
_stackcarried the columns to its numba kernel in anumba.typed.List, whose internals numba compiles in each process (the compiled code is not cached): about 0.2 s, on the first fit with a chunk of 65,536 elements or more, whatever the width of the design. It bought nothing on AKM fits with few covariates: the copy saves time only with many columns. The blocked copy is now used once the time it would have saved adds up to the compile (a width-dependent estimate per element), so a narrow design, as the AKM regression’s three columns, never pays for it, and a wide one does within its first chunks. Narrow fits in a new process are about 0.2 s faster; wide ones are unchanged.
0.6.0¶
A supported API for packages built on hdfe_stream.core (logit-stream is
the first), and a row store for them. Nothing changes for code that imports
from hdfe_stream itself, and no estimate changes.
IV diagnostics on 2SLS results (
HDFEResult.iv_diag, and insummary()), under the model’s vcov, with ivreg2’s conventions: Kleibergen-Paap rk LM underidentification and rk Wald weak-identification F (Anderson’s LM and Cragg-Donald’s F under iid errors), Sanderson-Windmeijer conditional F statistics, first-stage partial and Shea partial R^2, Montiel Olea and Pflueger’s effective F with its critical value (one endogenous regressor), the Anderson-Rubin test and (one endogenous regressor) confidence set, the endogeneity C statistic (ivreg2’sendog()), and Hansen’s J (Sargan’s statistic under iid errors). The robust and clustered ones need the instruments’ and first stages’ scores, which pass 2 now also accumulates for IV models; the rest come from the cross-products. The algebra ishdfe_stream.core.ivtests, from sums, for any estimator built on the core.Log-likelihoods and information criteria. Results have
aicandbic(the coefficients plus the fixed effects’ degrees of freedom, as fixest counts them), OLS results the normalloglik(with analytic weights, sum(log w) / 2 added, as statsmodels’ WLS), GLM resultsloglik_null(constant only), and GLMs with fixed effectsloglik_fe_nullandpseudo_r2_within(fixest’s within pseudo R2: what the covariates add beyond the fixed effects). With one fixed effect and no offset the fixed-effects-only model is the groups’ means, computed in the first row pass; otherwise it is a fit of its own, made withwithin_pseudo_r2=True.Incidental-parameter bias correction for logit and probit with one or two fixed effects (
bias_correction=True, or{"time": ..., "lags": L}for predetermined regressors): the analytic correction of Fernández-Val and Weidner (2016), as R’s alpaca computes it (biasCorr), matching it to 1e-7 with the same standard errors; the fixed effects are then re-estimated with the corrected coefficients held (from the first fit’s, or from zero if that fails, as it can when the correction is large, in very short panels). Checks the family, the number of fixed effects, and with lags one row per unit and period and an orderable period; warns for very short panels, gaps and units no longer than the window. Not for Poisson (no such bias with one or two fixed effects), nor three-way models.GLMs rescale analytic weights to average 1 over the estimation sample (Stata’s convention for maximum likelihood): before, the iid vcov and the log-likelihood depended on the weights’ scale (weights x 10: iid standard errors / sqrt(10)). Coefficients and robust/clustered vcovs are unchanged;
fepoisiid standard errors with analytic weights now differ from pyfixest’s, which uses the weights as given.Stable names in
hdfe_stream.core, listed in its docstring and pinned by a test: they change only in a minor release, with a changelog entry. Nine helpers lose their leading underscore on the way:core.formula’scompile_design,categorical_vars,numeric_exprandpyfixest_formula_api;core.feterms.parse_fe;core.report.warn;core.utils.as_lazy;core.workspace.Run; andcore.results_base.vcov_key. The type aliases move fromcore._typestocore.typing. The old names are gone (they were internal).hdfe_stream.core.store(new): a block store of rows (BlockStore) for estimators that read every row in each iteration, with what pass 0 needs to fill it – the narrow copy of the sample (write_sample,iter_batches), level tables (factorize), frames of whole groups, sorted in buckets when the groups are not consecutive (iter_groups), and Polars queries on the CPU or the GPU engine with fallback (PolarsEngine). hdfe-stream’s own estimators do not use it, but it is available for other estimators.BlockStore(binary=mask)stores the design’s 0/1 columns as one byte each and puts X back together, float64, as each block is read (iterate(raw=True)yields them apart, for a consumer that puts X together elsewhere, as on a GPU).iter_groupssorts within groups bysort_byon its in-order path too (a file whose groups are consecutive but whose rows within a group are not insort_byorder), as its docstring said.Results record each vcov’s small-sample factor (
diagnostics["vcov_factors"], by vcov key), for a caller that converts to other conventions (logit-stream’s multinomial logit with several fixed effects, fitted byfepois_stream).Faster row reads. Stacking a chunk’s columns into the row-major design (
_stack, every pass of every model) is a blocked parallel copy: 0.04 s instead of 0.47 s for 2 million rows of 39 columns.GLMs (IRLS): BLAS on one thread, smaller chunks. OpenBLAS’s threads and numba’s contended in the row passes, the more the smaller the chunks; up to 128 columns the passes now hold BLAS to one thread (
core.utils.single_blas, new dependency threadpoolctl), which is faster at every chunk size. GLMs then default to chunks of about 64 MB of the design (batch_rows=None, between 100,000 and 2,000,000 rows; linear models keep 2,000,000). Estimates are unchanged to rounding.GLMs without fixed effects: a fused, parallel row pass. Their IRLS row pass was NumPy on one thread, so it gained nothing from more cores; it is now one numba sweep like the fixed-effects path’s (
core.kernels_glm._nb_glm_rows_plain, sharing that kernel’s per-row family code), each block of rows forming its own cross-products up to 128 columns. An ACS logit of 3 million rows and 39 coefficients: 9.5 s -> 6.0 s on 8 threads, each IRLS step 1.1 s -> 0.6 s. Estimates are unchanged to rounding, and do not depend on the number of threads.Buckets sized by the rows’ width. Pass 0 sorts each bucket in memory;
rows_per_bucketnow defaults to about 384 MB of rows at their width (500,000 to 20,000,000 rows) instead of 20,000,000 rows. An ACS logit of 3 million rows and 41 columns with PUMA fixed effects: peak 3.3 GB -> about 1.7 GB, slightly faster. The sort itself is unchanged.Linear models without fixed effects also default to 64 MB chunks: on 3 million rows of 40 columns, peak memory 3.9 GB -> 2.1 GB at the same time.
0.5.1¶
Internal restructuring. Nothing changes for code that imports from
hdfe_stream itself, the documented hdfe_stream.simulate and
hdfe_stream.leaveout paths included, and no estimate changes.
hdfe_stream.core: the machinery the estimators share now lives in its own subpackage, for other estimators built on the same streaming passes to import without the leave-out (KSS) estimators. It holds the passes, the solve, inference, the numba kernels, formula parsing, results and reporting. Its names are internal, not a supported API.StreamingHDFEis the core driver (core/estimator.py) with the leave-out mixins added.StreamingGLM’s weighted least-squares steps, which do not depend on the GLM family, are incore/irls.py. Per-group kernels that do not depend on the model have moved fromkernels_inverse.pytocore/kernels_groups.py.HDFEResultandHDFEMultiderive from new base classes (core.results_base.RegressionResultandRegressionMulti). These hold what follows from a vector of estimates and its vcov alone:tidy,confint,wald_test, the summaries, the pyfixest view behindetable, and the multiple-testing corrections. Output is unchanged.repr()of a result lists its fields in a new order, the base class’s first.The modules that moved were undocumented, and their old paths no longer import:
hdfe_stream.results,reporting,connected,multcomp,workspace,families,utils,gpu,wildboot,formula,feterms,passes,solve,inference,report,_columns,_typesand thekernels_*modules other thankernels_inverseandkernels_se. Import public names fromhdfe_stream(hdfe_stream.HDFEResult,hdfe_stream.connected_components,hdfe_stream.cleanup, …).The numba kernels are cached under their new paths, so the first fit after upgrading compiles them once more.
0.5.0¶
Experimental GPU options.
device="cuda"runs the solve on an NVIDIA GPU through CuPy, andpolars_engine="gpu"runs the fit’s Polars queries on the cudf-polars GPU engine, with any query it cannot run run on the CPU and listed indiagnostics["polars_gpu_fallbacks"]. Neither changes the estimates beyond the solver tolerance. On an NVIDIA H100 they gained about 10% at 5 million workers and nothing consistent below; see the new “CPU and GPU” benchmark, which also measures pyfixest’s and xhdfe’s GPU paths.The regression and many-covariates benchmarks also compare with R’s fixest and Julia’s FixedEffectModels.jl. The AKM figures no longer draw
solver="within", whose results stay inakm.csv.The choice of Polars engine is now always explicitly specified in the codebase. This fixes an issue where the in-memory engine would be used in Polars 1.x.x despite the streaming engine being used in Polars 2.x.x.
0.4.0¶
New features.
HDFEResult.predict()predicts on new data (a DataFrame, a LazyFrame, or a Parquet path or glob) or on the fit’s source, lazily, so the data can be larger than memory. It returns the data with a prediction column: the linear predictor, or withtype="response"a GLM’s mean. Rows with a fixed-effect level the fit did not estimate get null. It supportsi()covariates, interacted fixed effects, varying slopes, and IV models.HDFEResult.confint(): confidence intervals, pointwise or, withjoint=True, simultaneous over the selected coefficients, as pyfixest’s.HDFEResult.wald_test(): Wald tests of R beta = q, or that the coefficients selected bykeep/dropare zero, under the current vcov, with F or chi-squared p-values. F is reported by default for any OLS hypothesis (chi-squared for GLMs), withdf_tdenominator degrees of freedom, so a one-coefficient test hastidy()’s p-value.bonferroni()andholm(): multiple-testing corrections of one or more coefficients’ p-values across models (results,HDFEMulti, or lists of them). Holm’s step-down adjustment controls the familywise error rate as Bonferroni’s does, and never rejects less often.The wild cluster bootstrap:
bootcluster=,HDFEResult.wildboottest(),rwolf()andwyoung(). Withbootcluster=, the fit keeps, for each cluster, the sums the bootstrap needs (about G x k^2 numbers, collected in the residual pass it makes anyway; nothing without the option). After the fit,wildboottest()runs the restricted or unrestricted wild cluster bootstrap of any coefficient from those sums, without reading the data, andrwolf()andwyoung()give Romano-Wolf and Westfall-Young adjusted p-values across models on the same draws. One-way, OLS only, and every fixed effect must be nested within the clusters (a fixed effect with few levels, such as year, can go in as covariates instead).
Fixes.
cluster="firm_id", a single string, was read as a list of characters; it now means one clustering, as documented.
Performance.
Cells are collapsed from sorted rows, without a hash aggregation. Pass 0 now sorts each worker’s rows by the other fixed effects’ levels too, so that every cell (one combination of levels) is a run of consecutive rows, and pass 1 collapses the runs as it reads the sorted rows, in a multithreaded kernel. This replaces Polars’ group_by over each slice of rows, and the cell table it wrote to disk and read back. Where nearly every row is a cell of its own (e.g., worker, firm and year effects on a worker-year panel), pass 0 sorts by the streamed dimension alone. The new
collapse_cellsoption ("auto", the default; True; False) overrides that choice, anddiagnostics["cells_collapsed"]reports it. Together with the faster iterations below, this reduced compute time by 5-31% on large AKM configurations, and peak disk by up to 40%, with the same or lower memory.Faster conjugate-gradient iterations. The vector work of each iteration (dot products, norms, and the updates of the solution, residual and search direction) runs as fused, multithreaded kernels instead of single-threaded numpy operations.
Faster IRLS steps for Poisson, logit and probit. Each step’s read of the rows (every row’s linear predictor, the family’s mean, weight and working response, the deviance and log-likelihood, and the sums per cell) runs as one fused, multithreaded kernel, instead of a dozen single-threaded numpy operations over each chunk. On large regression benchmarks, compute time declined by 11-32%.
Pass 1 builds the Jacobi diagonal and step 2’s right-hand side chunk by chunk while it has the cells in memory, instead of reading the identifying cells back for each, when the variables are solved in one block (up to
rhs_blockof them). Each of those reads is a pass over data as large as the cell table, which matters most where the scratch disk is slow.A memory budget for per-thread accumulators.
stream_cgand the leave-out passes give each thread its own level-sized accumulator, which with many threads and many levels could take more memory than the rest of the fit (64 threads, 30 million firm-years and 8 columns: about 120 GB, allocated afresh every iteration). They now get one copy per thread only while all of them fit in half ofmax_s_gb, with fewer threads on those passes when that binds, andstream_cgallocates its copies once per solve. Loweringmax_s_gbtightens it.
0.3.0¶
New features.
connected_componentsfinds the connected components of the graph of two fixed-effect dimensions (either may be an interaction,firm_id^year) by union-find over the rows as they stream, holding level-sized arrays only. It returns a table per dimension giving each level its component, numbered by size so that component 0 is the largest (ties go to the component with the smallest level of the first dimension), and a table of component sizes.largest()filters the data to the largest connected set andlabel()adds each row’s component, both lazily (on the data the components were found in, or on other data passed to them).min_degreeremoves levels with fewer distinct partners in the other dimension, repeating until none is left, before the components are found:(2, 1)keeps only movers,2the 2-core.leave_one_out=Trueprunes to the leave-one-out connected set of KSS estimation instead.rank_bysays whether “largest” counts rows (the default) or the levels of one dimension.connected=,min_degree=andconnected_fe=infeols_stream,fepois_stream,feglm_streamandStreamingHDFErestrict the fit to a pair of fixed effects (connected_fe, by default the first two listed), among the rows with no missing values and before singletons are dropped:min_degreeprunes levels with too few distinct partners, thenconnected="largest"keeps the largest connected set of what is left, orconnected="leave_one_out"the leave-one-out connected set, asconnected_componentsdoes.sample()reports the rows they drop as"min_degree","disconnected"and"leave_one_out", anddiagnostics["connected"]and the summary count them.Python 3.15 is supported and tested in CI. pyfixest, which the
formulaextra needs, has no 3.15 wheels yet (0.60.0), and building it from source needs Rust andPYO3_USE_ABI3_FORWARD_COMPATIBILITY=1; the rest of the package installs from wheels.
Changes that can affect existing code.
leave_one_out_connectedandLeaveOutSetare removed. Useconnected_components(data, "worker_id + firm_id", leave_one_out=True), whose.largest()is the pruned panel, orconnected="leave_one_out"in a fit. The set is the same: on simulated panels with many components, workers observed once and several rounds of cut workers, the workers and firms kept are identical. It is found 5-6 times faster (38s against 218s on 150 million rows), and a null worker or firm id no longer makes it fail.leave_out_kssprunes in the fit, withconnected="leave_one_out", so the leave-one-out connected set is that of the rows the model can use: before, rows with a missing outcome or covariate were part of the network being pruned.lo.pruningis now a dict of the pruning’s counts (the fit’sdiagnostics["connected"]["leave_one_out"]), and the rows it dropped are thoselo.fit.sample()labels"leave_one_out".The
componentcolumn offixef()is numbered by size, so component 0 is the largest (by rows in the estimation sample), as inconnected_components. Ties go to the component with the smallest level of that dimension. It was numbered by each component’s smallest level.Removed
hdfe_stream.iter_group_chunksandStreamingHDFE.from_formula. The first read only the fit’s internal row files, sorted by its internal group code, and stays internal; the second duplicatedfeols_stream.
Fixes.
The leave-out operator’s null space is right with several connected components.
apply_inversebuilt one null vector for every number up to the largest component label, which with several components left gaps, and each gap added a spurious vector. Leave-out estimation runs on a connected set and was not affected.
Documentation.
A documentation site, at leetucker.github.io/hdfe-stream, built with Sphinx from
docs/and published by a new GitHub Actions workflow. It has a page for each example, a section on leave-out variance components (bringing togetherdocs/kss.md, the methodological differences and a derivation of the correction), a page for each benchmark, a function reference built from the docstrings, and this changelog.docs/kss.md,docs/glm.mdanddocs/kss_methodological_differences.mdmoved into it, and the README is shorter, pointing to it. The public docstrings are now numpydoc, documenting every option, includingtol,maxiter,row_group_sizeandlog_levelofStreamingHDFE, and the attributes ofHDFEResultand the other result classes.pip install "hdfe-stream[docs]"installs what building it needs.New example,
connected_sets.py, and additions to the others:sample()and joining the residuals back onrow_id,fe_dof, and CRV3 (formulas.py);summary_json(quickstart.py);keep=and a decomposition by group (akm_variance.py); andStreamingGLM(glm.py).
0.2.2¶
Polars 2.0 support.
fit.sample()returns the source’s rows in the source’s order again. Polars 2.0 collects with the streaming engine by default, whose joins do not keep row order unless asked, so the rows came back shuffled. Under Polars 2.0, repeated fits of the same model can differ in the last digit or so (around 1e-16 relative): its streaming engine adds floating-point sums in an order that depends on thread scheduling. Under Polars 1.x they are identical bit for bit.Dropping singletons no longer inflates memory with a wide design. The dropped levels were anti-joined after the design was evaluated, so the streaming join buffered every design column. The rows are now dropped from the source columns before the design is evaluated.
Finding singletons takes fewer scans. The search used to stop only after a full round over the fixed effects found nothing. It now stops once every fixed effect has been checked since the last drop, since a dimension’s own drop cannot leave a singleton in it: four scans instead of six for a typical three-way model, about 40% less time spent on singletons, and the same memory. The rows dropped are the same.
Sorting the buckets and building the cell table takes less memory under Polars 2.0. Each bucket is sorted with Polars’ in-memory engine and then written, rather than sunk through the streaming engine, whose sort peaked about 1.5x higher. Similarly, Pass 1 grouped each bucket with a streaming
group_by, which under Polars 2.0 gives every thread its own hash table: with as many cells as rows, as in an AKM panel, the fit’s peak more than doubled. The rows are sorted by fe[0] group, so each bucket is now grouped a slice of whole groups at a time and the cells appended in order. This reduces memory use in AKM specifications and leaves wide designs unchanged or a little better.The explicit solver builds its matrix faster and in less memory. The reduced matrix S is now written directly in compressed form, one row at a time, instead of being assembled from chunks of coordinate triples that were merged with scipy. Each row’s size is counted first, so S is allocated once and nothing larger than S is held while it is built;
max_s_gbis checked before S is allocated rather than partway through. Estimates are unchanged up to rounding.Removed
triple_budgetanddense_max_levelsfromStreamingHDFE. They tuned the old way of building S and have no counterpart in the new one.Importing hdfe_stream costs a little less memory. p-values, critical values and the weak-identification interval use
scipy.special’s distribution functions instead ofscipy.stats, which is no longer imported. The values are the same.Empty run directories no longer pile up on NFS. A file deleted while still open or memory-mapped becomes a hidden .nfs file on NFS, so its run directory could not be removed and was left empty once the process exited. A failed removal is now retried after collecting garbage on every platform (it was Windows only); the leave-out functions release their memory maps as soon as they are done (
reload_intermediates()maps them back in); and empty run directories more than a minute old are removed by every new fit in the same working directory and byhdfe_stream.cleanup().Slightly less verbose default logging. CG iteration messages are now logged at DEBUG level and therefore not printed by default. Lower your log level to obtain this information.
0.2.1¶
fe_dof="exact"no longer depends on the order of the fixed effects. With three or more fixed effects it counted the connected components of the streamed dimension and whichever came next in the formula, so reordering the formula could change the standard errors. It now counts the components of every pair of dimensions and uses the pair with the most, which is never more than the true number of redundant levels. With two fixed effects nothing changes, except in the clustered case below.Clustered standard errors with fixed effects nested in the clusters. Under
fe_dof="exact", the components of a pair of fixed effects that are both nested within the clusters were subtracted from K, although those fixed effects’ levels are already dropped from it. K could then fall below the number of covariates and the standard errors were too small. Such a pair is no longer used, and with no other pair K is pyfixest’s.fit.sample()labels every singleton. With three or more fixed effects that each had singleton levels, rows dropped only for the third or a later dimension came back within_sample=True, so the counts disagreed withn_obsand the summary’s singleton count. The fit itself was right. GLM"separation"labels had the same fault.A NaN in a fixed-effect or cluster column is missing, as a null is, rather than a level of its own. For fixed effects this matches pyfixest; for clusters, where pyfixest raises an error, the row is dropped as it is for a null cluster.
sample()reports these rows as"missing".Polars 1.41 is excluded from the supported versions. Its streaming join panics (
called Option::unwrap() on a None value) once a frame has about 130 columns, which a model with more than about 120 covariates reaches in pass 0. Polars 1.40 and earlier, and 1.42 and later, are unaffected.A panic inside Polars is reported as a
RuntimeErrorthat names the Polars version, says it is a Polars bug, and suggests a fix, instead of a barePanicException.
0.2.0¶
Changes to defaults, so results can differ from 0.1.0 without any change to your code.
Default
vcovis now"iid", with or without fixed effects, matching pyfixest 0.60. Before, a model with fixed effects defaulted to CRV1 clustered on the first fixed effect. Passvcov={"CRV1": "worker_id"}for the old behavior.Singleton observations are dropped by default (
fixef_rm="singleton"), as in pyfixest, repeating until none is left.fixef_rm="none"keeps them.leave_out_kssfits withfixef_rm="none", since its pruning defines the sample.
New features.
row_idinresid(): each row carries its position in the source before any row was dropped, so residuals join back onto the source (row_id=renames the column).fit.sample()returns the source, lazily, withrow_id,in_sampleanddropped_because("missing","singleton"or"separation").multi.sample()returns{formula: frame}.Polars
DataFrameinputs are accepted wherever a Parquet path orLazyFramewas.Reserved column prefix
__hdfe_. All of the estimator’s internal columns now use it, and a source with a column starting with it is refused. This fixes fits failing when a user column was namedw(with weights),v0,c1,gcodeand similar.
0.1.0¶
First release.
feols_stream: out-of-core OLS with several high-dimensional fixed effects, varying slopes, weights, IV, and CRV1/CRV3 and other variance estimators.fepois_streamandfeglm_stream: Poisson, logit and probit by iteratively reweighted least squares over the same passes.AKM variance decomposition and leave-out (KSS) bias correction with standard errors and weak-identification diagnostics.
Reporting through pyfixest (
to_pyfixest(),etable).summary_json()andsummary_dict(): the model-level information ofsummary()as JSON or a dict, for saving to disk.