Paper: Shi Bo, Debarghya Mukherjee, and AmirEmad Ghassami, MediEncoder: Nonlinear Representation Learning for High-Dimensional Causal Mediation Analysis.
Representation learning and cross-fitted estimation for causal mediation analysis. This research implementation separates the estimator from simulated truth and uses observation-level cross-fitted scores for dataset-specific uncertainty estimates.
src/mediencoder/
estimation.py # Shared cross-fitting and influence-score estimation
training.py # Coupled encoders, training losses, and tuning
models.py # Autoencoders, VAEs, and nuisance regressions
nn_utils.py # Neural-network construction and device selection
simulation/ # Fixed cubic mechanism; main and ablation experiments
comparison/ # Separate polynomial experiment and comparison methods
real_data/ # Observed-data loading, validation, and effect estimation
scripts/ # Command-line entry points
tests/ # Statistical, data-boundary, and execution regression tests
docs/ # Methods, corrections, migration, and workflow notes
requirements/ # Validated environment snapshot
Generated results and real datasets stay outside version control. The earlier
mediencoder_exmaple_code/ layout is retired; see migration.
Use Python 3.11 or later in a virtual environment. Install the PyTorch build appropriate for your hardware, then install this package:
python -m pip install -e ".[test]"
python -m pytest -qThe development environment used Python 3.12 and PyTorch 2.8.0 with CUDA 12.6.
Its exact snapshot is in
requirements/validated-windows-cu126.txt.
That file describes the validated Windows environment; its CUDA-specific torch
wheel requires the corresponding PyTorch wheel index. CPU installations can use
the ordinary package dependencies. Other version combinations are not certified.
For unattended runs on BU SCC, see the background experiment guide. It covers CPU/GPU throughput comparisons, scheduler resources, immutable source snapshots, independent replication arrays, validation gates, and same-seed resume.
New main runs use fixed additive polynomial measurement maps of degree 3:
phi_k(f) = sum_j sum_{r=1}^3 C[k,j,r-1] * f[j]^r, with independent Gaussian
coefficients of variance coef_scale^2 / 3. X and M use separate loading streams.
Current main defaults use p=q=500, five true factors per block, and ten learned
coordinates per block. --latent-p and --latent-q set the positive learned
dimensions for X and M for all five methods; both default to 10 and are recorded
as tilde_p and tilde_q in the scientific manifest. These switches do not change
the true factors in the data-generating mechanism. The separate --factor-dim
option sets both true dimensions, bar_p=bar_q, to an integer from 1 through 5
(default 5); it does not alter either learned representation dimension. The
existing population-theta10 quadrature supports these dimensions. A changed
true dimension draws a different mechanism and target; it is not a controlled
perturbation holding the old structural coefficients or population target fixed.
Treatment coefficients are fixed draws from Uniform(0,1);
delta_0 and delta_1 are independent fixed draws with entries Uniform(0.9,1.1).
Gaussian mediator innovations, outcome equations, and noise SDs X=2, M=1, Y=1
are retained. This creates a new mechanism and does not resume historical results.
The existing Gaussian noise SDs can be specified with --sigma-eps-x-sd (default
2), --sigma-eps-m-sd (default 1), and --sigma-y-sd (default 1). These are
finite nonnegative standard deviations, with zero permitted. They map to
dgp.sigma_eps_X, dgp.sigma_eps_M, and dgp.sigma_y in the manifest, separate
from the covariance-eigenvalue scale --sigma-u-scale. All methods receive the
same resulting DGP. The noise and factor-dimension fields already existed in
the mechanism schema, so explicit default values preserve the previous canonical
configuration and RNG behavior. Noise-only changes leave the latent mechanism's
population theta10 unchanged but change the observed-data distribution. Changing
any of these settings requires a new run directory and a matching mechanism;
full DGP comparison rejects importing an old mechanism with different factor
dimensions or noise SDs. These CLI options support future prespecified studies
and do not change any frozen experiment, loss, weights or network architecture.
The treatment assignment defaults to --treatment-link linear, using
e(f_X) = expit(sum_j alpha_j * f_Xj). The exploratory
--treatment-link quadratic_centered instead uses
e(f_X) = expit(sum_j alpha_j * (f_Xj^2 - (mu^2 + 1/3))), centered by the
population second moment of each Uniform(mu-1,mu+1) covariate factor.
--sigma-u-scale controls the scale of the mediator-innovation covariance
matrix Sigma_U: its eigenvalues are fixed Uniform[1,2] draws multiplied by
this positive scale (default 0.05). It is a covariance scale, not a mediator
standard deviation. Both settings apply to the same data-generating mechanism
for every method and are recorded inside the manifest's dgp configuration;
the default linear link is omitted from serialization to preserve the default
canonical configuration. The causal outcome equations and analytic truth
formula remain unchanged. These are exploratory settings requiring a separate
run and source snapshot; existing runs retain their frozen settings and code.
For mixed/Haar measurement maps, changing the assignment or mediator covariance
also changes the independent mediator-pilot distribution used for calibration;
the loading seeds remain fixed, and every method uses the same resulting map.
MediEncoder defaults to fixed weights (.45,.45,.10), with ablation weights (.5,.5,0). Explicit --lambda-mode grid retains the former 36/9 candidate searches. The alignment term compares each mediator code and predicted code after dividing each row by its own L2 norm, with epsilon 1e-8. Alignment gradients update both encoders and the cross-factor predictor; neither code is detached. X/M reconstruction uses raw MSE; inference still uses the original encoder outputs. All nuisance networks have two hidden layers of width 300.
Use --loading-family haar explicitly for a new run with the retained Haar
generator or when importing an old Haar mechanism. Schema-1 saved mechanisms
retain their original content hashes and loadings; a default polynomial run
rejects an incompatible Haar import. Existing run manifests retain their source
fingerprints and must be resumed with their original code snapshot.
Exploratory --loading-family mixed_tanh and --loading-family deep_tanh
replace the measurement maps with injective mixtures using t + c*tanh(w*t);
--loading-strength sets c and --loading-frequency sets positive w. A fixed independent latent pilot matches each
signal coordinate's mean and variance to the polynomial reference. The causal
equations, measurement-noise SDs, and population target remain unchanged.
These opt-in settings are exploratory and do not replace the polynomial default.
--preprocessing standardize applies the existing representation-input
standardization to every method, fitting means and SDs only on that method's
representation-training rows. It preserves the loss formula and weights but
changes its input units, so it defines a separate scientific setting. The default
is --preprocessing none.
The separate opt-in --nuisance-standardize switch standardizes the input
features of every shared nuisance model for all five methods. Each nuisance fit
estimates its feature means and SDs only from that model's training subset,
including any treatment restriction; it stores those statistics as model buffers
and reuses them unchanged for validation and prediction. It uses population SD;
coordinates with training SD at most 1e-8 are centered with scale one to avoid
amplifying effectively constant features. Y remains in its original
units. This is distinct from --preprocessing, which transforms observed X/M
inputs for representation learning. Nuisance standardization is disabled by
default; when enabled, the manifest records nuisance_standardize: true and
training.nn_cfg.standardize_inputs: true. It changes neither representation
configuration (ae_cfg/me_cfg) nor the alignment loss or its weights. Treat
either switch or a changed latent dimension as a separate scientific run and use
a new output directory.
Start with a small execution check:
python -m mediencoder.simulation.runner --output-dir results/pilot --n 100 --reps 1 --pilot-epochs 2 --workers 1 --device cpuFor the full experiment:
python -m mediencoder.simulation.runner --output-dir results/formal --workers 1 --device cudaTo compute the first 50 replications now and extend the same run later, reserve 200 from the outset and change only the execution target:
python -m mediencoder.simulation.runner --output-dir results/formal --reps 200 --target-reps 50 --workers 1 --device cuda
python -m mediencoder.simulation.runner --output-dir results/formal --reps 200 --target-reps 100 --workers 1 --device cuda
python -m mediencoder.simulation.runner --output-dir results/formal --reps 200 --target-reps 200 --workers 1 --device cudaEach phase includes every selected sample size and arm. Completed fits retain
their original seeds, scores, and scientific fingerprint. The manifest records
the reserved 200; summaries and status show the current target (50, 100, or 200).
Changing --reps itself changes the reserved scientific configuration and is
rejected when resuming. Omit --target-reps to compute the full reservation.
For parallel execution on standard GitHub-hosted CPU runners, see the manual cloud simulation workflow. It prepares one shared mechanism, computes the first 50 replications across 50 shards, and validates the saved scores before assembling either table.
All current training defaults use weight decay 0, including representation, auxiliary, and final nuisance networks. The separate retained-mechanism workflow also uses weight decay 0 for 100 paired replications of MediEncoder and its zero-alignment arm. It explicitly imports the historical Haar mechanism; the main simulation runner defaults to cubic polynomial loadings.
Defaults are six sample sizes (100, 300, 800, 1200, 2000, 3000), 200 replications, and five arms: Projection, Autoencoder, VAE, fixed-lambda MediEncoder, and MediEncoder with zero alignment weight. This is 6,000 fits, each potentially containing many neural-network training runs. Both tables share the same MediEncoder fits. One worker is the conservative default. Workers are recycled between fits to release allocations; increase concurrency only after checking resources.
The same command resumes completed checkpoints only when scientific settings,
source hashes, the saved mechanism, and runtime identity match. Small-epoch pilot
results are marked and cannot be merged with the formal experiment.
Failures retain their seeds and traces; --retry-failed archives the previous
attempt before rerunning the same task. It does not replace difficult datasets.
Outputs include a configuration manifest, task JSON records, per-person score NPZ
files, summary.csv, main_table.tex, ablation_table.tex, and status.json.
Requested, valid, failed, and pending counts are explicit. Partial summaries are
not final manuscript results. For durable logs and a refreshing local HTML report:
python -m mediencoder.simulation.monitor --output-dir results/formal --reps 200 --target-reps 50 --workers 1 --device cudaThe monitor launches the runner; use it instead of launching a second runner against the same output directory. It forwards other runner options and displays the saved configuration and current phase. Raise its target to 100 or 200 to extend the same run after the previous phase has stopped. Interrupting the monitor stops its owned runner and worker processes; completed checkpoints are retained, and an interrupted fit is rerun with the same seed.
- Real-data workflow and input contract
- Polynomial comparison experiment and external baselines
- Scientific corrections and remaining limitations
- Validation performed for this release
All supported MediEncoder workflows call the shared estimator. External baseline adaptations are identified explicitly; unavailable standard errors are not replaced by Monte Carlo error SDs. Real-data inputs, identifiers, private paths, and third-party source repositories are not distributed here.
Confidence intervals use each dataset's own cross-fitted score variability. They remain asymptotic intervals and depend on identification, overlap, representation, and nuisance-estimation assumptions. Passing software tests does not establish these assumptions or guarantee nominal coverage.
Alignment uses row-L2 normalization and propagates through both encoders; checkpoint selection still uses reconstruction loss. Finite gradient training is not asserted to attain a global scalar-objective minimum. These changes do not revise or certify any manuscript proof. Historical tables must be recomputed; this code release does not validate their reported numbers.