riesznet trains the Riesz representer α(x) with a PyTorch model, in the spirit of Chernozhukov et al. (2021), RieszNet and ForestRiesz. It fits the Riesz representer only — outcome regression is handled separately.
The backend implements Backend.fit_augmented and groups the augmented rows by original row: for each original row z_i,
where the (c_j, p_j) pairs are the evaluation points of m at z_i and the model produces α via a Bregman link. These points come from the augmented dataset the orchestrator builds with estimand.augment, so the built-in estimands need no per-row Python work. Each minibatch evaluates the network only at its own rows’ points. The training loop minimizes the mean of L_i with autograd.
Two surfaces
RieszNet: convenience class with a default MLP. Surfaces hidden_sizes, activation, dropout, learning_rate, weight_decay, epochs, batch_size, device, dtype, standardize, n_jobs.
TorchBackend: power-user surface. Pass any nn.Module factory and any optimizer factory. Compose with rieszreg.RieszEstimator for full control.
RieszNet(early_stopping_rounds=30, epochs=400,
estimand=<rieszreg.estimands.base.ATE object at 0x15f26f750>,
learning_rate=0.005, validation_fraction=0.2)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
RieszNet(early_stopping_rounds=30, epochs=400,
estimand=<rieszreg.estimands.base.ATE object at 0x15f26f750>,
learning_rate=0.005, validation_fraction=0.2)
alpha_hat = rn.predict(df)true_alpha = a / pi - (1- a) / (1- pi)print(f"corr(α̂, α₀) = {np.corrcoef(alpha_hat, true_alpha)[0, 1]:.3f}")
RieszNet(early_stopping_rounds=30, epochs=400,
estimand=<rieszreg.estimands.base.TSM object at 0x163727450>,
learning_rate=0.005,
loss=<rieszreg.losses.kl.KLLoss object at 0x16372ed50>,
validation_fraction=0.2)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
RieszNet(early_stopping_rounds=30, epochs=400,
estimand=<rieszreg.estimands.base.TSM object at 0x163727450>,
learning_rate=0.005,
loss=<rieszreg.losses.kl.KLLoss object at 0x16372ed50>,
validation_fraction=0.2)
alpha_hat = rn.predict(df)true_alpha = (a ==1).astype(float) / piprint(f"min α̂ = {alpha_hat.min():.4f} (positive by construction)")
KLLoss and BernoulliLoss can’t represent ATE / ATT / shift-style estimands, because their α takes negative values; fit warns, and α̂ is pinned at 0 wherever α is negative. BoundedSquaredLoss(lo, hi) with lo < 0 accepts them and clips α̂ into the interval.
Custom architectures
The convenience class RieszNet covers MLPs. For an arbitrary nn.Module, instantiate TorchBackend directly and compose with rieszreg.RieszEstimator:
RieszEstimator(backend=TorchBackend(batch_size=256, early_stopping_rounds=30,
epochs=300, grad_clip_norm=1.0,
module_factory=<function my_factory at 0x16370d1c0>,
optimizer_factory=functools.partial(<class 'torch.optim.adamw.AdamW'>, lr=0.0003, weight_decay=0.001),
validation_fraction=0.2),
estimand=<rieszreg.estimands.base.ATE object at 0x163727fd0>)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
RieszEstimator(backend=TorchBackend(batch_size=256, early_stopping_rounds=30,
epochs=300, grad_clip_norm=1.0,
module_factory=<function my_factory at 0x16370d1c0>,
optimizer_factory=functools.partial(<class 'torch.optim.adamw.AdamW'>, lr=0.0003, weight_decay=0.001),
validation_fraction=0.2),
estimand=<rieszreg.estimands.base.ATE object at 0x163727fd0>)
module_factory and optimizer_factory must be top-level callables (functools.partial over a top-level function is fine). Closures and lambdas fit and predict, but raise on save() because they cannot be reconstructed by qualname.
Hyperparameters
RieszNet constructor:
Knob
Default
Notes
hidden_sizes
(64, 64)
MLP layer widths. Empty tuple gives a linear model.
activation
"relu"
One of relu, tanh, gelu, elu, silu, leaky_relu.
dropout
0.0
Dropout probability after each activation.
learning_rate
1e-3
Adam learning rate.
weight_decay
0.0
Adam weight decay.
epochs
200
Max epochs. Combine with early_stopping_rounds for adaptive stopping.
batch_size
64
Original rows per minibatch. None is full-batch GD.
device
"cpu"
Also "cuda", "mps", "auto". "auto" skips MPS when dtype="float64".
dtype
"float32"
Also "float64" (slower, more precise).
grad_clip_norm
None
Global L2 clip on the gradient.
standardize
True
Center and scale each input column by its mean and standard deviation over the observed training rows, so covariates on any scale train well. The counterfactual rows get the same transformation.
loss
SquaredLoss()
Any of the four built-in Bregman losses.
init
None
α-space initialization. Default is m̄ = E[m(Z, 1)] projected into the loss’s domain (the loss-minimizing constant); pass a float to override.
validation_fraction
0.1
Held-out fraction for early stopping. Used only when early_stopping_rounds is set and no eval_set is passed.
early_stopping_rounds
None
Patience (in epochs) for validation Riesz loss. The best-validation weights are restored at the end. With None, all epochs run and the final weights are kept.
snapshot_epochs
None
Epochs at which to store the weights for predict_path. None gives about 20 ticks; [] stores none.
n_jobs
None
torch threads during fit and predict. None keeps torch’s setting (all cores unless changed); -1 uses all cores. Set 1 when running many fits in parallel processes.
random_state
0
Seeds the fit. The global torch random state is restored afterward.
TorchBackend constructor (power-user surface):
Knob
Default
Notes
module_factory
placeholder
Callable[[int], nn.Module] returning a model with scalar output. The default placeholder raises at fit, so set it when you build TorchBackend yourself. RieszNet fills in an MLP (riesznet.modules.build_mlp).
optimizer_factory
placeholder
Callable[[Iterable[Parameter]], Optimizer]. The default placeholder raises at fit. RieszNet fills in Adam (riesznet.modules.build_adam).
scheduler_factory
None
Optional Callable[[Optimizer], LRScheduler]. Stepped per epoch.
epochs
200
batch_size
None
Original-row batch size. None is full-batch.
device
"cpu"
dtype
"float32"
grad_clip_norm
None
early_stopping_rounds
None
Patience in epochs; restores the best-validation weights.
validation_fraction
0.1
Held-out fraction for early stopping when no eval_set is passed. Rows are held out only when early_stopping_rounds is set.
snapshot_epochs
()
Epochs at which to store the weights for predict_eta_path.
Save writes state_dict.pt (PyTorch weights, on CPU) plus predictor.json (carries the factory’s module + qualname, the input dim, and the Bregman-loss spec). Load re-imports the factory by qualname, rebuilds the module, and calls load_state_dict. A model saved on a GPU loads and predicts on a machine without one; it runs on the CPU.
For built-in estimands the metadata round-trips automatically. For a custom Estimand, pass estimand= to load.
Sklearn integration
RieszNet is a BaseEstimator, so it composes with clone, GridSearchCV, cross_val_predict, Pipeline. See Tuning and cross-fitting.
Loss support
Loss
Supported
Link
Notes
SquaredLoss
✅
identity
Default. Works on every estimand.
KLLoss
✅
exp
Density-ratio targets only (TSM, IPSI). Requires non-negative m-coefficients.
BernoulliLoss
✅
sigmoid
Forces α̂ ∈ (0, 1), so the true Riesz representer must lie in (0, 1). Among the built-in estimands, only OutcomeRegNormSq with a binary outcome satisfies this. Otherwise use it for custom estimands whose representer does.
BoundedSquaredLoss(lo, hi)
✅
scaled-sigmoid
Forces α̂ ∈ (lo, hi). Works on every estimand.
The autograd implementation matches the analytic gradient in the loss spec exactly — verified per loss in the test suite.
Device, dtype, reproducibility
Each fit seeds torch from random_state and restores the global torch random state afterward, so single-device fits are reproducible run-to-run on the same hardware and do not change random draws elsewhere in your code. torch’s random state is shared by the whole process (and, on some torch builds, so is its thread count), so fits started in parallel threads of one process run one at a time; to fit in parallel, use processes (joblib’s default backend). Bitwise reproducibility on CUDA across machines is not promised; torch.use_deterministic_algorithms is not enabled by default because it slows training significantly.
device="auto" picks cuda → mps → cpu in that order. dtype="float64" runs end-to-end in double precision, useful for tightly-coupled gradient checks but slower.