Large data: a million rows within a memory limit

examples/large_data.py simulates a million rows in pieces of 250,000, writes them to a Parquet file (so that they are never in memory at once), and fits a causal forest of 500 trees to the file. The true average effect is 0.35. Run it with python examples/large_data.py 10000000 for ten million rows.

What the fit will need

profile=True returns the memory and disk a fit is expected to need, without fitting:

import forest_stream as fs

fml = "y ~ w | x1 + x2 + x3 + x4 + x5"
print(fs.causal_forest(fml, path, num_trees=500, profile=True))
Profile: causal forest y ~ w | x1 + x2 + x3 + x4 + x5
  1,000,000 rows kept of 1,000,000 (scan 0.0s); 8 threads
  memory     1.24 GB expected      1.52 GB upper bound   (this process holds 0.44 GB now)
  disk       1.73 GB expected      3.33 GB upper bound
  by phase: bin 0.49, grow 1.24
  request: ncpus=8  mem=2gb  disk=3gb   (select=1:ncpus=8:mem=2gb)
  components (GB expected / upper):
    trees                                          1.600 /    3.200  disk   all
    splitting samples of a batch of 64 trees       0.528 /    0.607  ram    grow
    nodes of a batch's trees                       0.205 /    0.410  ram    grow
    outcome, effects and fitted values (files)     0.096 /    0.096  disk   all
    streaming chunk                                0.049 /    0.049  ram    bin,grow
    binned copy of the data                        0.029 /    0.029  disk   all
    out-of-bag predictions of a round              0.016 /    0.016  ram    grow
    sample for the bin edges                       0.008 /    0.012  ram    bin

The estimate is a model of the fit, not a measurement. Its request line is what to ask a scheduler for. The forest is much larger on disk than the data: the trees take 1.6 GB, the binned copy of the data 0.03 GB. Trees are the part that grows with the number of trees and rows, and workdir= says where they go.

The fit, within 2 GB

fit = fs.causal_forest(fml, path, num_trees=500, max_memory_gb=2.0, seed=1)
print(fit.average_treatment_effect().summary_text())
obs: 1,000,000
│ ATE         ┆ 0.349027 ┆ 0.002143   ┆ 162.906567 ┆ 0.0      │

The forest grew its trees in batches sized to the 2 GB, 11 passes over the data in all (fit.n_passes); the estimate is within a standard error of the true 0.35. With less memory there are more passes, which costs little until a batch holds fewer trees than there are threads: Memory, disk and threads explains.

Predictions to a file

out = fit.predict(path, variance=True, output="predictions.parquet",
                  keep=["true_effect"], batch_rows=250_000)

predict reads the file in batches of batch_rows, predicts each, and appends it to predictions.parquet, so that neither the features nor the predictions are ever in memory whole. keep= carries columns through (here, the true effect, to compare). The path is returned. See Predicting and plotting.