Changelog¶
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.