# This document requires two prepared environments and fails loudly if either is# missing:# - Python: `uv sync` (creates ../.venv)# - R: `renv::restore()` inside docs/ (installs the pinned packages)# Params files live in docs/: fast_params.yml for quick renders and# prd_params.yml for the full run, e.g.:# quarto render docs --execute-params docs/fast_params.yml# quarto render docs --execute-params docs/prd_params.yml# Override single values with -P, e.g. -P n_sim_confounded:1000000# The renv project and the Python environment live one level above this# benchmark directory, i.e. at the docs root and the repository root.benchmark_dir <-dirname(knitr::current_input(dir =TRUE))docs_dir <-normalizePath(file.path(benchmark_dir, ".."))# Force all libraries to be loaded from the renv environment.options(renv.config.synchronized.check =FALSE)renv::load(project = docs_dir, quiet =TRUE)# Point reticulate at the Python environment one level above docs/.library(reticulate)venv <-file.path(docs_dir, "..", ".venv")use_virtualenv(normalizePath(venv), required =TRUE)# Report when every chunk tagged with `#| time_it: true` starts and how long it# took to the console during compilation (not into the rendered document).knitr::knit_hooks$set(time_it =local({ start <-NULLfunction(before, options) {if (before) { start <<-Sys.time()message(sprintf("[%s] start %s", options$label, format(start, "%H:%M:%S"))) } else { elapsed <-as.numeric(difftime(Sys.time(), start, units ="secs"))message(sprintf("[%s] time taken %.2fs", options$label, elapsed))invisible(NULL) } }}))
Show code (R loading the qte package)
library(qte)
Show code (R configuring single-threaded BLAS/OpenMP)
# The qte parallel bootstrap forks worker processes; forking while BLAS/OpenMP is# multithreaded can deadlock. Pin both to a single thread globally so every run# uses the same single-threaded BLAS baseline.library(RhpcBLASctl)blas_set_num_threads(1L)omp_set_num_threads(1L)pbapply::pboptions(type ="none")
QS <-c(0.25, 0.5, 0.75)QS_SIMPLE <-c(0.25, 0.5, 0.75, 0.9)X_R <-~ age +I(age^2) + education + black + hispanic + married + nodegreeX_PY <-"age + I(age**2) + education + black + hispanic + married + nodegree"
Show code (Python importing libraries and loading the data)
import timeimport polars as plfrom great_tables import GT, loc, md, px, stylefrom qte.bootstrap import BootstrapConfigfrom qte.unconfounded import estimate_aipw_effects, estimate_unadjusted_effectsfrom qte.datasets import load_lalondeDATA = load_lalonde(controls_source="psid")qs = [float(q) for q in r.QS]qs_simple = [float(q) for q in r.QS_SIMPLE]
Show code (Python defining the comparison-table helpers)
def make_source_note(n_obs: int, n_iter: int, n_workers: int) ->str:return (f"N = {int(n_obs):,}; {int(n_iter):,} bootstrap iterations; "f"{int(n_workers)} workers for parallel computations." )def make_timing_table(ds: pl.DataFrame, estimation: str, source_note: str) -> GT:return ( GT(ds.select("package", "computation", "seconds")) .cols_label(package="Package", computation="Computation", seconds="Seconds") .fmt_number(columns=["seconds"], decimals=1, use_seps=True) .tab_header(title=md("**Speed Comparison**"), subtitle=estimation) .tab_source_note(source_note) )def make_comparison_data(qs, series) -> pl.DataFrame:"""Tidy estimate/SE data for a package-vs-package comparison. ``series`` maps a ``(package, computation)`` label to an ``(effects, ses)`` pair, each ordered as ``[QTE(q) for q in qs] + [ATT]``. """ n_qte =len(qs) records = []for (package, computation), (effects, ses) in series.items():for i, q inenumerate(qs): # quantiles records.append( {"effect": "QTE","quantile": f"{q:.2f}","package": package,"computation": computation,"estimate": float(effects[i]),"se": float(ses[i]), } ) records.append( {"effect": "ATT","quantile": "","package": package,"computation": computation,"estimate": float(effects[n_qte]),"se": float(ses[n_qte]), } )return pl.DataFrame(records)def make_estimate_comparison_table(data: pl.DataFrame, estimation: str, source_note: str) -> GT:"""Render tidy comparison data (see ``make_comparison_data``). Rows are grouped under ``QTE``/``ATT``; package names become the top-level column spanners with the computation nested underneath. Estimate and standard-error columns get distinct backgrounds, and packages are separated by a vertical rule. """ pairs = data.select("package", "computation").unique(maintain_order=True).rows() packages =list(dict.fromkeys(package for package, _ in pairs)) computations =list(dict.fromkeys(computation for _, computation in pairs))def series(package, computation):# filter preserves the QTE...ATT order produced by make_comparison_datareturn data.filter((pl.col("package") == package) & (pl.col("computation") == computation)) base = series(*pairs[0]) frame = {"effect": base["effect"].to_list(), "quantile": base["quantile"].to_list()} leaf_labels = {}for package, computation in pairs: prefix =f"{package}.{computation}" sub = series(package, computation) frame[f"{prefix}.est"] = sub["estimate"].to_list() frame[f"{prefix}.se"] = sub["se"].to_list() leaf_labels[f"{prefix}.est"] ="Estimate" leaf_labels[f"{prefix}.se"] = md("Standard<br>Error") table = pl.DataFrame(frame) est_cols = [c for c in table.columns if c.endswith(".est")] se_cols = [c for c in table.columns if c.endswith(".se")] gt = ( GT(table, groupname_col="effect") .row_group_order(["QTE", "ATT"]) .cols_label(quantile="Quantile", **leaf_labels) .fmt_number(columns=est_cols + se_cols, decimals=1, use_seps=True) .tab_header(title=md("**Results Comparison**"), subtitle=estimation) .tab_source_note(source_note) .tab_style(style=style.fill(color="#E8F1FA"), locations=loc.body(columns=est_cols)) .tab_style(style=style.fill(color="#FBF0E1"), locations=loc.body(columns=se_cols)) .tab_style(style=style.fill(color="#D3E4F5"), locations=loc.column_labels(columns=est_cols)) .tab_style(style=style.fill(color="#F6E0C4"), locations=loc.column_labels(columns=se_cols)) )for package in packages:# narrower spanners first so the package spanner sits on top package_columns = []for computation in computations: est_col, se_col =f"{package}.{computation}.est", f"{package}.{computation}.se"if est_col notin frame:continue gt = gt.tab_spanner( computation, columns=[est_col, se_col], id=f"{package}|{computation}" ) package_columns += [est_col, se_col] gt = gt.tab_spanner(package, columns=package_columns, id=f"{package}|pkg")iflen(packages) >1: divider ="#8A8A8A" second_package = packages[1] first_computation =next( computation for package, computation in pairs if package == second_package ) first_of_second =f"{second_package}.{first_computation}.est" gt = gt.tab_style( style=style.borders(sides="left", color=divider, style="solid", weight=px(2)), locations=[ loc.body(columns=first_of_second), loc.column_labels(columns=first_of_second), loc.spanner_labels(ids=[f"{second_package}|pkg"]), loc.spanner_labels(ids=[f"{second_package}|{first_computation}"]), ], )return gt
Summary
Here, we compare the performance of the py-qte and the qte package. We use a medium-sized machine (see the Environment section for details). The comparisons are based on the relatively small Lalonde dataset that comes with the qte package and on a medium-sized simulated dataset inspired by this section from the documentation of the DoubleML package.
In particular, estimators that involve an outcome model are relatively computationally intensive since they involve fitting a quantile regression model on a grid of quantiles in each bootstrap run. So speed matters here.
Even for the small Lalonde dataset (2,675 observations), we find sizeable differences between the qte and the py-qte packages in sequential computations. These can be closely tied to different implementation approaches of the respective estimators. Parallelized approaches benefit qte relatively more (in this setting). See Table 2. For estimation with confounders, the same holds true, but even after parallelization the gap remains sizeable, and the qte package takes about 3 times as long as the py-qte package (see Table 4).
For a larger simulated dataset (2,000 observations), we find that without confounderspy-qte is orders of magnitude as fast even after parallelization. See Table 6. For the AIPW estimator we find that the parallelized py-qte version on a medium-sized dataset (2,000 observations and 5 covariates) with a reasonable number of bootstrap iterations is more than 20 times faster than the qte version. See Table 9.
Lastly, the py-qte version can provide results for 400 observations and 3 bootstrap iterations in about 260 seconds. This is about half the time the parallelized qte version took for a dataset that has only 20% of the rows. Interestingly, the parallelized py-qte version with 4 workers is about 10 times faster than the sequential version, which suggests that the chosen parallelization strategy based on threads is close to optimal for larger datasets. See Table 11.
Overall, these results stress the importance of algorithmic choices and parallelization strategies for the bootstrap iterations.
Unconfounded Data
We compare unconfounded estimators on the Lalonde dataset. The Lalonde dataset is a relatively small dataset with only 2,675 observations.
Estimation under Unconfoundedness
Show code (R estimate of the unconditional QTE)
# Unconditional QTE with no covariates == R's IPW branch with x = NULL.run_r_simple <-function(cl) {set.seed(SEED) t0 <-Sys.time() res <-unc_qte(yname ="re78", dname ="treat", data = lalonde.psid, xformla =NULL,probs = QS_SIMPLE, est_method ="ipw", target ="qtt",cl = cl, biters = N_ITER_SIMPLE )list(seconds =as.numeric(Sys.time() - t0, units ="secs"),vals =list(qte =as.numeric(res$qte), se =as.numeric(res$qte.se),ate =as.numeric(res$ate), ate_se =as.numeric(res$ate.se) ) )}r_simple_seq <-run_r_simple(1)r_simple_par <-run_r_simple(N_WORKERS)r_simple_seq_seconds <- r_simple_seq$secondsr_simple_par_seconds <- r_simple_par$secondsr_simple_seq_vals <- r_simple_seq$valsr_simple_par_vals <- r_simple_par$vals
Show code (Python estimate of the unconditional QTE)
Show code (Python building the simple comparison tables)
simple_order = [f"QTE({q:.2f})"for q in qs_simple] + ["ATE"]def py_simple_cols(res): rows = {f"QTE({row['q']:.2f})": (row["effect"], row["se"]) for row in res.qtt.iter_rows(named=True) } rows["ATE"] = (res.att["effect"][0], res.att["se"][0])return [rows[k][0] for k in simple_order], [rows[k][1] for k in simple_order]def r_simple_cols(vals): eff = [float(x) for x in vals["qte"]] + [float(vals["ate"])] err = [float(x) for x in vals["se"]] + [float(vals["ate_se"])]return eff, errsimple_source_note = make_source_note(DATA.height, int(r.N_ITER_SIMPLE), int(r.N_WORKERS))simple_table_html = make_estimate_comparison_table( make_comparison_data( qs_simple, { ("py-qte", "Sequential"): py_simple_cols(res_py_simple_seq), ("py-qte", "Parallel"): py_simple_cols(res_py_simple_par), ("qte", "Sequential"): r_simple_cols(r.r_simple_seq_vals), ("qte", "Parallel"): r_simple_cols(r.r_simple_par_vals), }, ),"Estimation under Unconfoundedness", simple_source_note,).as_raw_html()data = pl.DataFrame( {"language": ["Python", "Python", "R", "R"],"package": ["py-qte", "py-qte", "qte", "qte"],"computation": ["Sequential", "Parallel", "Sequential", "Parallel"],"workers": [1, int(r.N_WORKERS), 1, int(r.N_WORKERS)],"iterations": [int(r.N_ITER_SIMPLE)] *4,"seconds": [ py_simple_seq_seconds, py_simple_par_seconds,float(r.r_simple_seq_seconds),float(r.r_simple_par_seconds), ], })simple_timing_html = make_timing_table( data, "Estimation under Unconfoundedness", simple_source_note).as_raw_html()
Table 1: Unconditional QTE Estimates on the Lalonde Data.
Results Comparison
Estimation under Unconfoundedness
py-qte
qte
Quantile
Sequential
Parallel
Sequential
Parallel
Estimate
Standard Error
Estimate
Standard Error
Estimate
Standard Error
Estimate
Standard Error
QTE
0.25
−11,041.0
594.1
−11,041.0
594.1
−11,041.0
602.1
−11,041.0
597.0
0.50
−16,455.9
733.2
−16,455.9
733.2
−16,455.9
717.7
−16,455.9
756.3
0.75
−19,911.5
784.6
−19,911.5
784.6
−19,911.5
794.5
−19,911.5
824.0
0.90
−23,867.8
1,902.8
−23,867.8
1,902.8
−23,839.0
1,918.4
−23,839.0
1,954.2
ATT
−15,204.8
672.0
−15,204.8
672.0
−15,204.8
643.8
−15,204.8
672.6
N = 2,675; 1,000 bootstrap iterations; 4 workers for parallel computations.
Table 2: Unconditional QTE Runtimes on the Lalonde Data.
Speed Comparison
Estimation under Unconfoundedness
Package
Computation
Seconds
py-qte
Sequential
1.3
py-qte
Parallel
0.9
qte
Sequential
8.1
qte
Parallel
3.6
N = 2,675; 1,000 bootstrap iterations; 4 workers for parallel computations.
Notice first that py-qte replicates the point estimates of the qte package and produces similar standard errors. Notice that py-qte produces consistent standard error estimates across the sequential and the parallelized runs, as it should.
We see that py-qte is in a sequential scenario much faster than qte. This is probably mostly because np.quantile provides an efficient implementation of computing weighted quantiles whereas the qte package runs a solver for each quantile. The speed-up from parallelization is very large for qte and sizeable but relatively low for py-qte.
Show code (Python building the AIPW comparison tables)
order = [f"QTE({q:.2f})"for q in qs] + ["ATE"]def py_cols(res): rows = {f"QTE({row['q']:.2f})": (row["effect"], row["se"]) for row in res.qtt.iter_rows(named=True) } rows["ATE"] = (res.att["effect"][0], res.att["se"][0])return [rows[k][0] for k in order], [rows[k][1] for k in order]def r_cols(vals): eff = [float(x) for x in vals["qte"]] + [float(vals["ate"])] err = [float(x) for x in vals["se"]] + [float(vals["ate_se"])]return eff, errpy_seq_e, py_seq_s = py_cols(res_py_seq)py_par_e, py_par_s = py_cols(res_py_par)r_seq_e, r_seq_s = r_cols(r.r_seq_vals)r_par_e, r_par_s = r_cols(r.r_par_vals)aipw_data = make_comparison_data( qs, { ("py-qte", "Sequential"): (py_seq_e, py_seq_s), ("py-qte", "Parallel"): (py_par_e, py_par_s), ("qte", "Sequential"): (r_seq_e, r_seq_s), ("qte", "Parallel"): (r_par_e, r_par_s), },)aipw_source_note = make_source_note(DATA.height, int(r.N_ITER), int(r.N_WORKERS))table_html = make_estimate_comparison_table( aipw_data, "Estimation via AIPW", aipw_source_note).as_raw_html()timing = pl.DataFrame( {"language": ["Python", "Python", "R", "R"],"package": ["py-qte", "py-qte", "qte", "qte"],"computation": ["Sequential", "Parallel", "Sequential", "Parallel"],"workers": [1, int(r.N_WORKERS), 1, int(r.N_WORKERS)],"iterations": [int(r.N_ITER)] *4,"seconds": [py_seq_seconds, py_par_seconds, float(r.r_seq_seconds), float(r.r_par_seconds)], })timing_html = make_timing_table(timing, "Estimation via AIPW", aipw_source_note).as_raw_html()
Table 3: AIPW Comparison of py-qte and qte.
Results Comparison
Estimation via AIPW
py-qte
qte
Quantile
Sequential
Parallel
Sequential
Parallel
Estimate
Standard Error
Estimate
Standard Error
Estimate
Standard Error
Estimate
Standard Error
QTE
0.25
−7,647.3
2,650.8
−7,647.3
2,650.8
−7,646.7
2,459.8
−7,646.7
2,299.6
0.50
−12,682.7
3,535.6
−12,682.7
3,535.6
−12,684.5
2,659.2
−12,684.5
2,543.1
0.75
−16,522.6
1,106.3
−16,522.6
1,106.3
−16,522.7
1,173.9
−16,522.7
1,734.7
ATT
−12,535.5
1,498.6
−12,535.5
1,498.6
−13,194.8
1,629.5
−13,194.8
1,498.0
N = 2,675; 10 bootstrap iterations; 4 workers for parallel computations.
In terms of results, we see in Table 3 that the point estimates are close between py-qte and qte. The standard errors are once more consistent across the sequential and parallelized runs.
Table 4: AIPW Runtimes Comparison of py-qte and qte.
Speed Comparison
Estimation via AIPW
Package
Computation
Seconds
py-qte
Sequential
4.9
py-qte
Parallel
2.4
qte
Sequential
26.2
qte
Parallel
11.7
N = 2,675; 10 bootstrap iterations; 4 workers for parallel computations.
We further see in Table 4 that the sequential version of py-qte is much faster than the qte version. This is probably largely due to the fact that py-qte computes \(F_{AIPW}(y)\) on the y-grid in a single (vectorized) pass whereas the qte version computes each point on the y-grid separately in a loop. The parallelized version of py-qte retains a sizeable advantage over the qte version although the gap is considerably narrower than in the sequential case.
Simulated Data
The sections above use the Lalonde dataset, which has only a few thousand observations. To see how well the py-qte and the qte package do on large dataset we resort to simulated data.
Show code (Python simulating the datasets)
from qte.unconfounded import simulate_covariate_data, simulate_simple_datadef add_correct_features(ds):return ds.with_columns( ind1=(pl.col("x1") >0.1).cast(pl.Float64), ind2=((pl.col("x0") * pl.col("x2")) >0).cast(pl.Float64), sq=(2.5+0.3* pl.col("x1")).sqrt(), )EFFECT_SCALE =1000.0sim_simple = simulate_simple_data(int(r.N_SIM_UNCONFOUNDED), treatment_effect=EFFECT_SCALE, error_var=EFFECT_SCALE**2, # keep the residual sd on the same scale as the effect seed=int(r.SEED),)sim_cov = add_correct_features( simulate_covariate_data(int(r.N_SIM_CONFOUNDED), effect_scale=EFFECT_SCALE, seed=int(r.SEED) +1 ))# Plain dicts so reticulate hands R a data.frame (polars objects are not converted).SIM_SIMPLE_R = sim_simple.to_dict(as_series=False)SIM_COV_R = sim_cov.to_dict(as_series=False)
Table 5: QTE Estimates on the Simulated Unconfounded Data.
Results Comparison
Simulated data without covariates
py-qte
qte
Quantile
Sequential
Parallel
Estimate
Standard Error
Estimate
Standard Error
Estimate
Standard Error
QTE
0.25
980.6
53.1
980.6
53.1
980.2
92.9
0.50
999.9
50.8
999.9
50.8
1,000.2
62.7
0.75
982.3
41.1
982.3
41.1
983.6
30.4
ATT
1,001.2
34.2
1,001.2
34.2
1,001.2
43.3
N = 2,000; 3 bootstrap iterations; 4 workers for parallel computations.
Table 6: QTE Runtimes on the Simulated Unconfounded Data.
Speed Comparison
Simulated data without covariates
Package
Computation
Seconds
py-qte
Sequential
0.0
py-qte
Parallel
0.0
qte
Parallel
0.1
N = 2,000; 3 bootstrap iterations; 4 workers for parallel computations.
As in the Lalonde comparison, the two packages agree on the point estimates and standard errors. We omit the sequential qte run here because it is very slow on larger data; even against the parallel qte run py-qte is faster. Because the simulated design is randomized, the treatment effect is identified by the unadjusted comparison; simulate_simple_data generates it with the treatment effect set by EFFECT_SCALE.
AIPW Estimator
The simulated dataset has five covariates: the outcome model uses five transformed features of them, whereas the propensity score uses three of the raw covariates. Note that qte::unc_qte takes a single xformla used for both the propensity score and the outcome regression, so the R run below fits both models on the same five features while the py-qte run uses separate formulas. The population (“true”) effects of this design are reported in Table 7. They are obtained by generating a large dataset at the true parameter values and subsequently computing the quantities of interest from that dataset.
Show code (Python true effects of the confounded simulation)
import gcimport numpy as npN_TRUE =int(10e6)true_ds = simulate_covariate_data(N_TRUE, effect_scale=EFFECT_SCALE, seed=int(r.SEED))true_y0 = true_ds["y_0"].to_numpy()true_y1 = true_ds["y_1"].to_numpy()true_ate =float(np.mean(true_y1 - true_y0))true_qte = np.quantile(true_y1, qs) - np.quantile(true_y0, qs)# Drop the large simulated population before the later runs.del true_ds, true_y0, true_y1_ = gc.collect()true_rows = pl.concat( [ pl.DataFrame({"Quantity": ["ATE"], "Estimate": [true_ate]}), pl.DataFrame({"Quantity": [f"QTE({q:.2f})"for q in qs], "Estimate": true_qte}), ])true_table_html = ( GT(true_rows) .fmt_number(columns=["Estimate"], decimals=1, use_seps=True) .tab_header( title=md("**True Effects**"), subtitle="Confounded simulation (population QTE)", ) .tab_source_note(f"True values from a simulation with N = {N_TRUE:,} units.") .as_raw_html())
Table 7: True Mean and Quantile Treatment Effects of the Confounded Simulation.
True Effects
Confounded simulation (population QTE)
Quantity
Estimate
ATE
500.3
QTE(0.25)
−498.0
QTE(0.50)
499.9
QTE(0.75)
1,499.0
True values from a simulation with N = 10,000,000 units.
Table 8: AIPW QTE Estimates on the Simulated Confounded Data.
Results Comparison
Simulated data with covariates
py-qte
qte
Quantile
Sequential
Parallel
Estimate
Standard Error
Estimate
Standard Error
Estimate
Standard Error
QTE
0.25
−501.1
41.6
−501.1
41.6
−499.9
61.3
0.50
503.3
22.3
503.3
22.3
503.2
133.4
0.75
1,495.1
29.1
1,495.1
29.1
1,495.0
75.9
ATT
497.9
23.0
497.9
23.0
494.6
61.5
N = 2,000; 3 bootstrap iterations; 4 workers for parallel computations.
Table 9: AIPW QTE Runtimes on the Simulated Confounded Data.
Speed Comparison
Simulated data with covariates
Package
Computation
Seconds
py-qte
Sequential
1.2
py-qte
Parallel
0.6
qte
Parallel
8.2
N = 2,000; 3 bootstrap iterations; 4 workers for parallel computations.