Module contents
Lesson 28 of 28Research 120 min

Frontier: deep causal learning, proximal inference and causality in LLMs

Explore neural treatment-effect estimators, proximal inference with proxies, causal representations, and language-model causal reasoning. Assess assumptions, benchmark mechanisms, and limitations.

After this lesson you can

  • Implement TARNet, CFR, and Dragonnet and compare with DR-learner on semisynthetic data.
  • Explain proximal completeness and bridge equations and estimate effects with negative controls.
  • State a causal-representation identification result and its assumptions.
  • Design an exploratory local language-model causal-reasoning evaluation.
  • Critically assess a causal-learning paper’s assumptions, benchmark, and limitations.

Before you start

Four distinct questions

A network can predict an outcome from thousands of variables, but factual prediction does not observe what would have happened under the other intervention. A proxy can contain information about an invisible confounder without being equivalent to observing it. A language model can answer a familiar causal question without proving it applies the same reasoning to another mechanism.

This lesson examines four research programs: estimating effects with networks, identifying effects through proxies, recovering representations with causal meaning, and evaluating causal reasoning in language models. Each changes available tools; none by itself turns association into intervention.

Networks for potential outcomes

For binary treatment and prior covariates XX, write μt(x)=E[Y(t)∣X=x]\mu_t(x)=E[Y(t)\mid X=x] and τ(x)=μ1(x)−μ0(x)\tau(x)=\mu_1(x)-\mu_0(x). Under consistency, conditional exchangeability, and overlap, μt\mu_t is identified with the observed outcome mean in arm tt. Identification is a claim about distribution and assumptions, not network size.

TARNet learns a shared representation Φ(X)\Phi(X) and two heads μ^0,μ^1\widehat\mu_0,\widehat\mu_1. In factual loss each observation updates the head corresponding to its treatment; their prediction difference estimates CATE. Sharing the representation transfers information, but a head must still extrapolate where its arm is scarce.

CFR adds a discrepancy penalty between distributions of Φ(X)\Phi(X) for treated and control units. For a function family G\mathcal G, an integral probability metric is

IPM⁡G(P,Q)=sup⁡g∈G∣EP[g]−EQ[g]∣.\operatorname{IPM}_{\mathcal G}(P,Q) =\sup_{g\in\mathcal G}|E_P[g]-E_Q[g]|.

MMD uses the unit ball of a kernel Hilbert space as its class. For kernel kk its population square is E[k(R,R′)]+E[k(S,S′)]−2E[k(R,S)]E[k(R,R')]+E[k(S,S')]-2E[k(R,S)], with independent copies within each term. Pairwise sums approximate it and allow gradients, but kernel and scale choice matter.

The bound of Shalit, Johansson and Sontag, theorem 1, assumes an injective representation with inverse, squared loss, and scaled loss functions belonging to the IPM-defining class. Under strong ignorability and regularity,

ϵPEHE≤2(ϵFt=0+ϵFt=1+BΦIPM⁡G(PΦt=1,PΦt=0)−2σY2).\epsilon_{\mathrm{PEHE}} \leq 2\left(\epsilon_F^{t=0}+\epsilon_F^{t=1} +B_\Phi\operatorname{IPM}_{\mathcal G}(P_\Phi^{t=1},P_\Phi^{t=0}) -2\sigma_Y^2\right).

Here ϵFt\epsilon_F^{t} is conditional factual error in arm tt and σY2\sigma_Y^2 is the irreducible variance term defined in the paper. The proof first bounds PEHE through factual and counterfactual errors, then bounds the latter using factual errors and IPM. Lower empirical discrepancy alone is insufficient: a constant representation perfectly mixes arms while potentially discarding predictive information. A practical dimension-reducing network does not automatically satisfy the bound’s injectivity assumption.

InteractiveBalance representations

Compare learned representation with individual-effect error on an independent synthetic test. Each point represents an observation; axes have the same scale across states so contraction stays visible.

−5.95.9Representation 1Representation 2
  • Control
  • Treated

Root PEHE versus λ at step 2000. The orange bar is the selected state.

00.010.11101001.730

The synthetic model generates X with two standard normal components, T with logistic probability of 2X₀, and Y=0.3X₀+0.8X₁+T(1+1.3X₀)+ε with normal noise of standard deviation 0.4. A 2D linear representation and two linear heads are trained with factual error, balance penalty and L2 regularization. Six fits share data and initialization; Adam uses 2,000 steps and seed 272801.

The penalty is linear-kernel MMD², the squared distance between mean representations of both arms. The first 160 test observations are shown; root PEHE, factual error and MMD² use all 400 test observations, independent of the 400 training observations. Root PEHE is the root mean squared CATE error; individual truth is known only in simulation.

This linear network demonstrates balance inspired by CFR; it does not reproduce its architecture or a published benchmark. A small linear MMD does not establish equal distributions or absence of confounding; shrinking the representation can lose useful information. See Shalit and colleagues.

0
Training step
λ0
Test root PEHE0.0853
Test linear MMD²1.8566
Factual squared error0.1742
Compare actual training runs of a synthetic model with different balance penalties.

Dragonnet adds a head for e^(x)=P(T=1∣X=x)\widehat e(x)=P(T=1\mid X=x) and targeted regularization. If Q^(T,X)\widehat Q(T,X) is factual prediction, a perturbation used by Shi, Blei and Veitch has the form

Q^⋆(T,X)=Q^(T,X)+ε(Te^(X)−1−T1−e^(X)).\widehat Q^\star(T,X)=\widehat Q(T,X) +\varepsilon\left(\frac{T}{\widehat e(X)} -\frac{1-T}{1-\widehat e(X)}\right).

Loss combines factual fit, treatment cross-entropy, and squared error of perturbed prediction, with weights for each term. Propensity must stay away from zero and one to control denominators. Targeted regularization links learning to estimating equations but alone guarantees neither identification, finite-sample double robustness, nor interval coverage for an arbitrary network.

What a semisynthetic benchmark teaches

In IHDP, covariates come from a real study and potential outcomes are simulated. This provides truth for estimator comparison, but truth depends on the chosen mechanism. The version described in the CFR paper, section 5.1 has 747 units, 139 treated, and 25 covariates. Its results average 1,000 realizations with 63%, 27%, and 10% training, validation, and test splits. A short single-realization check does not reproduce that experiment.

With reference effects τi\tau_i and predictions τ^i\widehat\tau_i, distinguish

PEHE⁡=1n∑i(τ^i−τi)2,ϵATE=∣1n∑i(τ^i−τi)∣.\operatorname{PEHE}=\frac1n\sum_i(\widehat\tau_i-\tau_i)^2,\qquad \epsilon_{\mathrm{ATE}}=\left|\frac1n\sum_i(\widehat\tau_i-\tau_i)\right|.

Some papers show the square root of PEHE: state which quantity is calculated. Accurate ATE can conceal individual errors that cancel. IHDP or ACIC compare methods under particular mechanisms, but good performance does not verify exchangeability, support, or absence of measurement error in a real application.

Two proxies and an invisible variable

Proximal causal inference treats adjustment with unmeasured confounding as an inverse problem. Let UU be a latent confounder, ZZ a treatment-associated proxy, and WW an outcome-associated proxy. Negative-control interpretation requires substantive exclusions: schematically, once UU and prior covariates XX are fixed, WW does not respond to TT or ZZ, and ZZ does not directly affect YY beyond TT. Conditional exchangeability given U,XU,X, support, and regularity are also needed.

An outcome bridge function hh satisfies the observable equation

E[Y∣T=t,Z=z,X=x]=E[h(W,t,x)∣T=t,Z=z,X=x].E[Y\mid T=t,Z=z,X=x] =E[h(W,t,x)\mid T=t,Z=z,X=x].

If an appropriate bridge exists and proximal exclusion and completeness conditions hold, the intervened mean is identified as E[Y(t)]=E[h(W,t,X)]E[Y(t)]=E[h(W,t,X)]. One way to understand completeness is that the conditional operator associated with ZZ does not hide a relevant nonzero function of UU: if E[g(U)∣T,Z,X]=0E[g(U)\mid T,Z,X]=0 almost surely, then g(U)=0g(U)=0 almost surely in the considered class. This concerns latent distributions, not a high correlation testable from observations alone. Bridge existence and exact completeness versions depend on the theorem; see Tchetgen Tchetgen and colleagues.

In the linear case consider centered variables and independent innovations:

T=aU+ηT,Z=bU+ηZ,W=cU+ηW,Y=θT+dU+ηY.T=aU+\eta_T,\quad Z=bU+\eta_Z,\quad W=cU+\eta_W,\quad Y=\theta T+dU+\eta_Y.

If c≠0c\ne0, bridge h(W,T)=θT+(d/c)Wh(W,T)=\theta T+(d/c)W has residual ηY−(d/c)ηW\eta_Y-(d/c)\eta_W with zero conditional expectation given T,ZT,Z. The rank condition identifying its two coefficients using instruments (T,Z)(T,Z) is Cov⁡(Z,W∣T)≠0\operatorname{Cov}(Z,W\mid T)\ne0. In this Gaussian model with positive variances, proxies must transmit relevant information; estimation becomes unstable as that covariance approaches zero. The linear rank condition does not generally replace nonparametric completeness.

The first stage projects WW onto an intercept, TT and ZZ; the second regresses YY on an intercept, TT and projected WW. Standard errors need IV or GMM formulas accounting for both stages: ordinary second-stage regression errors are insufficient. Direct adjustment for WW and ZZ may reduce confounding and remain biased.

InteractiveTwo proxies for an invisible confounder

Population model: U, εA, εZ, εW and εY are independent standard normals; A = 0.8U + εA, Z = aU + εZ, W = bU + εW and Y = 1.2A + U + εY. The effect of increasing A by one unit via intervention is 1.2. Signals a and b change how much the two proxies reveal about U; their noise variances remain one.

  • Causal effect
  • OLS with W
  • OLS with W and Z
  • Bridge, if a unique solution exists
1.21.41.61.80.00.51.01.52.0Z signal: a

Adjusting for noisy proxies leaves residual confounding. In this population OLS without proxies is 1.688; the two lines show A’s coefficient including W or both proxies. The curve varies a with b fixed and the vertical line marks the selected value.

Cov(Z, W | A)
0.6098
Cov(Z, Y | A)
0.6098
Coefficient of Z in W ~ A + Z
0.3788
Coefficient of W in bridge
1.000

The linear bridge h(W, A) = θA + γW satisfies E[Y − h(W, A) | A, Z] = 0. Its moments give γ = Cov(Z, Y | A) / Cov(Z, W | A), then θ = 1.2. Here Cov(Z, W | A) = ab / 1.64. If a = 0, the condition leaves the bridge indeterminate; if b = 0 and a > 0, the ratio has zero denominator and positive numerator, so this linear bridge does not exist. The point disappears in both cases. A small nonzero denominator retains the exact population solution but may produce unstable estimates in finite samples. Covariance depends on units and is not a universal measure of strength.

In this model Z does not directly affect Y and W is not affected by A, given U and the other equations. These assumptions and rank permit the shown construction; linear rank alone does not prove general proximal-identification conditions.

1.00
1.00
Causal effect1.200
OLS: A y W1.503
OLS: A, W y Z1.420
Proximal bridge1.200
Change proxy quality and compare population limits of the fits.

Causal representations and what can be identified

Causal representation learning seeks latent variables whose mechanisms answer intervention questions. Without extra restrictions, an invertible latent transformation can produce the same observed distribution with a different factor interpretation: observations alone do not necessarily select a causal representation. Schölkopf and colleagues present the program and difficulties.

Positive results therefore specify extra information sources and an equivalence class. For example, theorem 3.2 of von Kügelgen and colleagues studies two latent variables, a known observational environment, and one stochastic perfect intervention per node, though their node correspondence is unknown. Assumptions include differentiable full-support densities, an observational mixture invertible on its image, and difference and genericity conditions between original and intervened mechanisms. Under all theorem conditions it identifies variables up to permutation and differentiable invertible componentwise transformation, and the graph up to isomorphism. It does not claim arbitrary images or imperfect interventions identify any graph. Other results exploit temporal structure and different assumptions. Before transferring a conclusion check observations, environment changes, and remaining ambiguities.

A temporal example is CITRIS. Its model assumes stationary first-order Markov latent dynamics, no instantaneous effects, and independent noise across factors. Observations are generated by a bijective transformation of factors and noise; which factors receive intervention at each step is known, though intervened values need not be. In that framework theorem 3.3 characterizes recovery of each factor’s intervention-dependent part under its variation and global-optimization conditions. It does not guarantee separation of factors always intervened on together or recovery of all information: the intervention-invariant part may remain in another latent block.

Causal reasoning in language models

Associational, interventional, and counterfactual questions require different information. The CLadder benchmark builds questions from graphs and symbolic queries, with answers calculated by a causal engine; its abstract describes 10,000 examples and three query types. In table 2 of version 1.5 of the paper, GPT-4 obtains 62.03% overall and 70.40% with CausalCoT under that protocol. These are published results of that experiment, not measurements of the local model you will run.

Kıcıman and colleagues investigate language-model uses in causal tasks, while Zečević and colleagues caution against attributing a causal model from linguistic answers. To investigate the difference, fix a structural model and generate question pairs with semantic and arbitrary names, keeping equations, distribution, and answer fixed. A drop when names change indicates formulation sensitivity; it alone proves neither memorization nor absence of reasoning. A counterfactual requires specifying shared exogenous variables between factual and intervened worlds: a graph alone usually does not suffice.

InteractiveOne mechanism, two ways to ask

Choose a mechanism and a rung. Both wordings contain the same model and change the labels; both have the same exact answer.

UXY
Meaningful version

In this fictional world, U=1 is vulnerability, X=1 is receiving treatment and Y=1 is improvement. U, Nₓ and Nᵧ are independent binary variables with P(U=1)=0.4, P(Nₓ=1)=0.2 and P(Nᵧ=1)=0.1. Equations: X=U⊕Nₓ; Y=(X·U)⊕Nᵧ. ⊕ is XOR. Changing X retains the same exogenous values.

Among those treated, what is the probability they improved?

Abstract version

In this fictional world, U, X and Y are labels without further meaning. U, Nₓ and Nᵧ are independent binary variables with P(U=1)=0.4, P(Nₓ=1)=0.2 and P(Nᵧ=1)=0.1. Equations: X=U⊕Nₓ; Y=(X·U)⊕Nᵧ. ⊕ is XOR. Changing X retains the same exogenous values.

Among cases with X=1, what is the probability that Y=1?

The direct graph removes U→Y; the other includes confounding and changes the effect of X by U. An observational distribution alone is insufficient for the counterfactual: structural equations and all exogenous distributions are also given here.

The two questions can be sent to a local model outside this figure. Different answers reveal wording sensitivity, but alone do not prove memory or training contamination. This example contains no LLM responses. See CLadder.

Graph and mechanism
Rung
0.4
Formal questionP(Y=1 | X=1)
ProbabilityHidden
Generate queries at all three rungs and compare formulations with the model’s exact answer.

Open questions

With interference, one unit’s outcome may depend on others’ treatments; define intervention and network exposure before estimation. In time series declare information available before each decision and keep later variables out of controls. In adaptive experiments assignment probability changes with history and must enter design and evaluation. In each case predictive gain does not replace assumptions linking data to a causal estimand.

When reading a paper separate four claims: which parameter is identified and under which assumptions; what the algorithm actually estimates; which mechanisms generate benchmark truth; and what experimental variation or uncertainty is reported. Then ask whether its conditions and distribution resemble your problem.

Lab: negative controls and a linear bridge

In this simulation UU and all errors are independent standard normals. Treatment is continuous; interventions fix T=tT=t. We use a=0,8a=0{,}8, b=c=d=1b=c=d=1 and θ=1,2\theta=1{,}2. Truth follows from equations, not estimation: intervening on TT gives causal coefficient θ\theta. Observed treatment shares UU with outcome and adjustment for noisy proxies does not remove all confounding.

[ ]Generate confounder proxiesBrowser
import numpy as np

def mundo_proximal(n, semilla, b=1.0, c=1.0):
    rng = np.random.default_rng(semilla)
    u, ruido_t, ruido_z, ruido_w, ruido_y = rng.normal(size=(5, n))
    t = .8*u + ruido_t
    z = b*u + ruido_z
    w = c*u + ruido_w
    y = 1.2*t + u + ruido_y
    return t, z, w, y

t, z, w, y = mundo_proximal(12000, 272801)
print('Observaciones:', len(y), '| efecto causal fijado en el modelo:', 1.2)

Compare direct fits with instrumental variables. In 2SLS regressors are D=(1,T,W)D=(1,T,W) and instruments Z∗=(1,T,Z)Z_\ast=(1,T,Z). The first stage calculates D^=PZ∗D\widehat D=P_{Z_\ast}D; the second solves D^TD β^=D^TY\widehat D^\mathsf TD\,\widehat\beta=\widehat D^\mathsf TY. lstsq is used for projection and the identifying matrix is checked for full rank.

[ ]OLS and 2SLS bridgeBrowser
def ajustar_directo(t, z, w, y, usar_z):
    columnas = [np.ones(len(t)), t, w]
    if usar_z:
        columnas.append(z)
    return np.linalg.lstsq(np.column_stack(columnas), y, rcond=None)[0][1]

def puente_2sls(t, z, w, y):
    D = np.column_stack([np.ones(len(t)), t, w])
    Z = np.column_stack([np.ones(len(t)), t, z])
    proyeccion = Z @ np.linalg.lstsq(Z, D, rcond=None)[0]
    matriz = proyeccion.T @ D / len(t)
    if np.linalg.matrix_rank(matriz) < D.shape[1]:
        raise ValueError('Instrumentos sin rango para identificar el puente')
    coef = np.linalg.solve(matriz, proyeccion.T @ y / len(t))
    return coef

print('OLS con W:', round(float(ajustar_directo(t,z,w,y,False)), 4))
print('OLS con W y Z:', round(float(ajustar_directo(t,z,w,y,True)), 4))
print('Puente 2SLS, coeficientes constante, T, W:',
      np.round(puente_2sls(t,z,w,y), 4))

In this mechanism population limits of both direct adjustments can be calculated. They are not general guarantees for different proxies: they depend on declared variances and exclusions.

[ ]Check model limitsBrowser
a = .8
theta = 1.2
ols_w_poblacion = theta + a/(1 + 1 + a*a)
ols_wz_poblacion = theta + a/(1 + 1 + 1 + a*a)
cov_zw_dado_t = 1/(1 + a*a)
print('OLS con W, límite poblacional:', round(ols_w_poblacion, 5))
print('OLS con W y Z, límite poblacional:', round(ols_wz_poblacion, 5))
print('Covarianza parcial Z,W dado T:', round(cov_zw_dado_t, 5))
print('Puente poblacional: h(w,t)=', theta, '*t + w')

For an overidentified version add Z2Z^2 as an instrument. Here it is valid because the bridge residual is independent of (T,Z)(T,Z) by construction. The following GMM first uses identity weighting and then the inverse empirical residual-moment matrix. Adding an instrument does not make it valid in a real study; the function warns if that matrix or the identification matrix lacks rank.

[ ]Two-step GMM bridgeBrowser
def puente_gmm(t, z, w, y):
    n = len(y)
    D = np.column_stack([np.ones(n), t, w])
    instrumentos = np.column_stack([np.ones(n), t, z, z*z])
    A = instrumentos.T @ D / n
    b = instrumentos.T @ y / n

    def resolver(peso):
        matriz = A.T @ peso @ A
        if np.linalg.matrix_rank(matriz) < D.shape[1]:
            raise ValueError('Momentos sin rango para identificar el puente')
        return np.linalg.solve(matriz, A.T @ peso @ b)

    inicial = resolver(np.eye(instrumentos.shape[1]))
    residuos = y - D @ inicial
    momentos = instrumentos * residuos[:, None]
    omega = momentos.T @ momentos / n
    if np.linalg.matrix_rank(omega) < omega.shape[0]:
        raise ValueError('Matriz de momentos singular')
    return resolver(np.linalg.solve(omega, np.eye(omega.shape[0])))

print('GMM, coeficientes constante, T, W:', np.round(puente_gmm(t,z,w,y), 4))

Repeat on independent samples to see bias and spread. A weak proxy does not change structural truth, but can make the moment ratio highly variable. These repetitions belong to the simulation and do not validate negative controls in a real dataset.

[ ]Repeat with strong and weak proxiesBrowser
for calidad in (1.0, .25):
    resultados = []
    for replica in range(120):
        tr, zr, wr, yr = mundo_proximal(600, 272900+replica, b=calidad)
        resultados.append((ajustar_directo(tr,zr,wr,yr,False),
                           puente_2sls(tr,zr,wr,yr)[1]))
    resultados = np.asarray(resultados)
    print('Calidad de Z:', calidad,
          '| medias OLS, 2SLS:', np.round(resultados.mean(axis=0), 3),
          '| desviaciones:', np.round(resultados.std(axis=0, ddof=1), 3))
print('Una media de muestras finitas no es el límite poblacional.')

Lab: reproduce the balance interactive

The following model uses one representation and two linear heads. Six runs share initialization and data but change the linear MMD penalty. The test sample is independent and CATE known because it is simulated; root PEHE cannot be calculated this way in a real study. Figure points and values come from these cells, not an external benchmark. Small linear MMD only equalizes representation means, not full distributions.

[ ]Balance experiment dataBrowser
import numpy as np

# Datos independientes para ajustar y evaluar el mismo experimento de la figura.
bal_rng = np.random.default_rng(272801)
bal_alphas = (0., .01, .1, 1., 10., 100.)
bal_pasos = (0, 100, 500, 1000, 2000)
bal_reg = .02

def bal_muestra(n):
    X = bal_rng.normal(size=(n, 2))
    e = 1 / (1 + np.exp(-2 * X[:, 0]))
    T = (bal_rng.uniform(size=n) < e).astype(int)
    tau = 1 + 1.3 * X[:, 0]
    mu0 = .3 * X[:, 0] + .8 * X[:, 1]
    Y = mu0 + T * tau + bal_rng.normal(0, .4, size=n)
    return X, T, Y, tau

bal_x, bal_t, bal_y, _ = bal_muestra(400)
bal_x_test, bal_t_test, bal_y_test, bal_tau_test = bal_muestra(400)
bal_inicial = [np.eye(2), bal_rng.normal(0, .05, size=(2, 2)), np.zeros(2)]
bal_resultados = {}

def bal_gradiente(params, alpha):
    A, W, b = params
    Z = bal_x @ A
    residuo = (Z * W[bal_t]).sum(axis=1) + b[bal_t] - bal_y
    delta = bal_x[bal_t == 1].mean(0) - bal_x[bal_t == 0].mean(0)
    diferencia = delta @ A
    grad_A = 2 / len(bal_x) * bal_x.T @ (residuo[:, None] * W[bal_t])
    grad_A += 2 * alpha * np.outer(delta, diferencia) + 2 * bal_reg * A
    grad_W = np.zeros_like(W)
    for brazo in (0, 1):
        mask = bal_t == brazo
        grad_W[brazo] = 2 / len(bal_x) * (Z[mask].T @ residuo[mask]) + 2 * bal_reg * W[brazo]
    grad_b = np.bincount(bal_t, weights=2 * residuo / len(bal_x), minlength=2)
    return [grad_A, grad_W, grad_b]

def bal_foto(params):
    A, W, b = params
    representacion = bal_x_test @ A
    medias = representacion @ W.T + b
    cate = medias[:, 1] - medias[:, 0]
    factual = medias[np.arange(len(bal_t_test)), bal_t_test]
    diferencia = representacion[bal_t_test == 1].mean(0) - representacion[bal_t_test == 0].mean(0)
    return {'raiz_pehe': float(np.sqrt(np.mean((cate - bal_tau_test)**2))),
            'mmd2': float(diferencia @ diferencia),
            'factual': float(np.mean((factual - bal_y_test)**2)),
            'puntos': representacion[:160].copy()}

def bal_iniciar(alpha):
    params = [v.copy() for v in bal_inicial]
    return {'alpha': alpha, 'params': params, 'paso': 0,
            'm': [np.zeros_like(v) for v in params],
            'v': [np.zeros_like(v) for v in params],
            'fotos': {0: bal_foto(params)}}

def bal_avanzar(estado, hasta):
    # Permite dividir una ejecución en varias celdas sin reiniciar Adam.
    if not estado['paso'] <= hasta <= 2000:
        raise ValueError('El paso final debe estar entre el actual y 2000')
    while estado['paso'] < hasta:
        g = bal_gradiente(estado['params'], estado['alpha'])
        paso = estado['paso'] + 1
        for k, grad in enumerate(g):
            estado['m'][k] = .9 * estado['m'][k] + .1 * grad
            estado['v'][k] = .999 * estado['v'][k] + .001 * grad * grad
            m_hat = estado['m'][k] / (1 - .9**paso)
            v_hat = estado['v'][k] / (1 - .999**paso)
            estado['params'][k] -= .01 * m_hat / (np.sqrt(v_hat) + 1e-8)
        estado['paso'] = paso
        if paso in bal_pasos:
            estado['fotos'][paso] = bal_foto(estado['params'])

def bal_informe(alpha):
    foto = bal_resultados[alpha]['fotos'][2000]
    print(f"λ={alpha:g}: raíz de PEHE={foto['raiz_pehe']:.6f}, "
          f"MMD²={foto['mmd2']:.6f}, error factual={foto['factual']:.6f}")

print('Muestras independientes:', len(bal_x), 'para entrenamiento y', len(bal_x_test), 'para prueba.')
[ ]Gradients and first training runBrowser
bal_resultados[0.] = bal_iniciar(0.)
bal_avanzar(bal_resultados[0.], 2000)
bal_informe(0.)
[ ]Balance λ=0,01Browser
bal_resultados[.01] = bal_iniciar(.01)
bal_avanzar(bal_resultados[.01], 2000)
bal_informe(.01)
[ ]Balance λ=0,1Browser
bal_resultados[.1] = bal_iniciar(.1)
bal_avanzar(bal_resultados[.1], 2000)
bal_informe(.1)
[ ]Balance λ=1Browser
bal_resultados[1.] = bal_iniciar(1.)
bal_avanzar(bal_resultados[1.], 2000)
bal_informe(1.)
[ ]Balance λ=10Browser
bal_resultados[10.] = bal_iniciar(10.)
bal_avanzar(bal_resultados[10.], 2000)
bal_informe(10.)
[ ]Balance λ=100Browser
bal_resultados[100.] = bal_iniciar(100.)
bal_avanzar(bal_resultados[100.], 2000)
bal_informe(100.)
[ ]Explore steps and pointsBrowser
# Los puntos mostrados y todas las métricas están disponibles sin archivos externos.
for alpha in bal_alphas:
    estado = bal_resultados[alpha]
    assert set(estado['fotos']) == set(bal_pasos)
    for paso in bal_pasos:
        foto = estado['fotos'][paso]
        assert foto['puntos'].shape == (160, 2)
        assert np.isfinite([foto['raiz_pehe'], foto['mmd2'], foto['factual']]).all()
    bal_informe(alpha)

print('Tratamientos de los cinco primeros puntos de prueba:', bal_t_test[:5])
print('Primeros cinco puntos, λ=0 y paso 2000:')
print(np.round(bal_resultados[0.]['fotos'][2000]['puntos'][:5], 5))
print('Los puntos y las métricas de cada paso están en bal_resultados[λ]["fotos"][paso].')

Local lab: networks on IHDP

Install NumPy, scikit-learn, and PyTorch in a compatible local environment. The lab downloads original IHDP-100 files linked by the CFR repository and retains a local cache. It does not replace the benchmark with invented data. If download fails, check the source before retrying. Covariates are real and potential outcomes simulated.

The official test set remains separate. A stratified part of training is reserved for validation; scales are fitted only on the remainder and epochs chosen by validation factual error without looking at counterfactual effects. Code reports root PEHE and absolute ATE error on test data. DR-learner fits nuisances out of fold and reports propensity clipping. Networks are compact method-inspired implementations, not exact reproductions of architectures or hyperparameter searches.

Normal execution uses five replicates and up to 300 epochs per network. To check operation set ORYON_SHORT=1: it uses one replicate, three epochs, and eight trees, so it cannot compare method quality. Replicates and epochs can be changed with ORYON_REPLICAS and ORYON_EPOCAS. CUDA is used if available, otherwise CPU. Propensity clipping in Dragonnet and DR is a stability tradeoff, not an identification guarantee.

[ ]TARNet, CFR, Dragonnet, and DR on IHDPLocal GPU
"""IHDP-100 original: TARNet, CFR-MMD, Dragonnet y DR-learner.

Datos: https://github.com/clinicalml/cfrnet, ejemplos IHDP del autor.
Requiere numpy, scikit-learn y torch. ORYON_SHORT=1 reduce la prueba.
El código es autónomo y guarda la caché de datos fuera del repositorio.
"""
import copy
import os
import random
import tempfile
from pathlib import Path
from urllib.request import urlopen

import numpy as np
import torch
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from torch import nn
from torch.nn import functional as F

SOURCE = 'https://www.fredjo.com/files/ihdp_npci_1-100.{}.npz'
CACHE = Path.home() / '.cache' / 'oryon-learn' / 'ihdp'
SHORT = os.environ.get('ORYON_SHORT') == '1'
SEED = 2728


def download(split):
    CACHE.mkdir(parents=True, exist_ok=True)
    path = CACHE / f'ihdp_npci_1-100.{split}.npz'
    if not path.exists():
        tmp = None
        try:
            with urlopen(SOURCE.format(split), timeout=60) as response:
                with tempfile.NamedTemporaryFile(dir=CACHE, suffix='.part', delete=False) as target:
                    tmp = Path(target.name)
                    while True:
                        chunk = response.read(1024 * 1024)
                        if not chunk:
                            break
                        target.write(chunk)
            # El archivo se valida antes de moverlo a su nombre definitivo.
            with np.load(tmp, allow_pickle=False) as archive:
                validate_archive(archive, split)
            os.replace(tmp, path)
            tmp = None
        finally:
            if tmp is not None:
                tmp.unlink(missing_ok=True)
    return path


def validate_archive(archive, name):
    required = ('x', 't', 'yf', 'mu0', 'mu1')
    missing = [key for key in required if key not in archive]
    if missing:
        raise ValueError(f'{name}: faltan variables {missing}')
    x = archive['x']
    if x.ndim != 3 or x.shape[1] != 25:
        raise ValueError(f'{name}: se esperaba x con forma (n,25,réplicas), recibida {x.shape}')
    n, _, r = x.shape
    if n == 0 or r == 0:
        raise ValueError(f'{name}: archivo vacío')
    for key in required[1:]:
        if archive[key].shape != (n, r):
            raise ValueError(f'{name}: {key} tiene forma inesperada {archive[key].shape}')
    return n, r


def load_replica(archive, replica):
    data = {key: np.asarray(archive[key][:, :, replica] if key == 'x' else archive[key][:, replica],
                            dtype=np.float64)
            for key in ('x', 't', 'yf', 'mu0', 'mu1')}
    for key, value in data.items():
        if not np.isfinite(value).all():
            raise ValueError(f'{key}: valores no finitos en réplica {replica + 1}')
    if not np.isin(data['t'], (0, 1)).all() or len(np.unique(data['t'])) != 2:
        raise ValueError('El tratamiento debe ser binario y contener ambos grupos')
    return data


class Net(nn.Module):
    def __init__(self, n_features, dragon=False):
        super().__init__()
        self.rep = nn.Sequential(nn.Linear(n_features, 64), nn.ELU(),
                                 nn.Linear(64, 32), nn.ELU())
        self.out0 = nn.Sequential(nn.Linear(32, 32), nn.ELU(), nn.Linear(32, 1))
        self.out1 = nn.Sequential(nn.Linear(32, 32), nn.ELU(), nn.Linear(32, 1))
        self.dragon = dragon
        if dragon:
            self.propensity = nn.Linear(32, 1)
            self.epsilon = nn.Parameter(torch.zeros(()))

    def forward(self, x):
        z = self.rep(x)
        q0, q1 = self.out0(z).squeeze(-1), self.out1(z).squeeze(-1)
        logits = self.propensity(z).squeeze(-1) if self.dragon else None
        return z, q0, q1, logits


def mmd_biased(z, t):
    """MMD² empírica con núcleo gaussiano, incluyendo las diagonales."""
    z0, z1 = z[t == 0], z[t == 1]
    if not len(z0) or not len(z1):
        raise ValueError('MMD requiere ambos grupos')
    def kernel(x, y):
        return torch.exp(-torch.cdist(x, y).square() / (2 * 4.0 ** 2))
    return kernel(z0, z0).mean() + kernel(z1, z1).mean() - 2 * kernel(z0, z1).mean()


def factual_prediction(net, x, t):
    z, q0, q1, logits = net(x)
    prediction = (1 - t) * q0 + t * q1
    if net.dragon:
        propensity = torch.sigmoid(logits).clamp(0.05, 0.95)
        clever = t / propensity - (1 - t) / (1 - propensity)
        prediction = prediction + net.epsilon * clever
    return prediction


def fit_neural(kind, x, t, y, xval, tval, yval, xtest, seed, epochs, device):
    torch.manual_seed(seed)
    net = Net(x.shape[1], dragon=(kind == 'Dragonnet')).to(device)
    train_x, train_t, train_y = (torch.as_tensor(v, dtype=torch.float32, device=device) for v in (x, t, y))
    val_x, val_t, val_y = (torch.as_tensor(v, dtype=torch.float32, device=device) for v in (xval, tval, yval))
    test_x = torch.as_tensor(xtest, dtype=torch.float32, device=device)
    optimizer = torch.optim.Adam(net.parameters(), lr=0.001, weight_decay=0.0001)
    best, best_state, best_epoch, stale = float('inf'), None, 0, 0
    for epoch in range(epochs):
        net.train()
        optimizer.zero_grad(set_to_none=True)
        z, q0, q1, logits = net(train_x)
        factual = (1 - train_t) * q0 + train_t * q1
        loss = F.mse_loss(factual, train_y)
        if kind == 'CFR-MMD':
            loss = loss + 0.1 * mmd_biased(z, train_t)
        elif kind == 'Dragonnet':
            p = torch.sigmoid(logits).clamp(0.05, 0.95)
            clever = train_t / p - (1 - train_t) / (1 - p)
            targeted = factual + net.epsilon * clever
            loss = (loss + F.binary_cross_entropy_with_logits(logits, train_t)
                    + 0.1 * F.mse_loss(targeted, train_y))
        if not torch.isfinite(loss):
            raise FloatingPointError(f'{kind}: pérdida no finita')
        loss.backward()
        optimizer.step()
        net.eval()
        with torch.no_grad():
            val_loss = F.mse_loss(factual_prediction(net, val_x, val_t), val_y).item()
        if not np.isfinite(val_loss):
            raise FloatingPointError(f'{kind}: validación no finita')
        if val_loss < best - 1e-6:
            best, best_state, best_epoch, stale = val_loss, copy.deepcopy(net.state_dict()), epoch + 1, 0
        else:
            stale += 1
        if stale >= 40:
            break
    if best_state is None:
        raise RuntimeError(f'{kind}: no hay checkpoint válido')
    net.load_state_dict(best_state)
    net.eval()
    with torch.no_grad():
        _, q0, q1, logits = net(test_x)
        if kind == 'Dragonnet':
            p = torch.sigmoid(logits).clamp(0.05, 0.95)
            q0 = q0 - net.epsilon / (1 - p)
            q1 = q1 + net.epsilon / p
        tau = (q1 - q0).cpu().numpy().copy()
    del optimizer, net, best_state, train_x, train_t, train_y, val_x, val_t, val_y, test_x
    if device.type == 'cuda':
        torch.cuda.empty_cache()
    return tau, best_epoch, best


def fit_dr(x, t, y, xtest, seed, trees):
    """Nuisances fuera de pliegue y bosque final del pseudoresultado DR."""
    pseudo = np.empty(len(t), dtype=float)
    clipped, total = 0, 0
    folds = StratifiedKFold(n_splits=2, shuffle=True, random_state=seed)
    for fold, (fit, hold) in enumerate(folds.split(x, t)):
        prop = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000, random_state=seed + fold))
        prop.fit(x[fit], t[fit])
        raw = prop.predict_proba(x[hold])[:, 1]
        p = np.clip(raw, 0.05, 0.95)
        clipped += np.count_nonzero(raw != p)
        total += len(raw)
        predictions = []
        for arm in (0, 1):
            subset = fit[t[fit] == arm]
            outcome_model = RandomForestRegressor(n_estimators=trees, min_samples_leaf=5,
                                                  random_state=seed + fold * 2 + arm, n_jobs=1)
            outcome_model.fit(x[subset], y[subset])
            predictions.append(outcome_model.predict(x[hold]))
        q0, q1 = predictions
        pseudo[hold] = q1 - q0 + t[hold] * (y[hold] - q1) / p - (1 - t[hold]) * (y[hold] - q0) / (1 - p)
    final = RandomForestRegressor(n_estimators=trees, min_samples_leaf=5, random_state=seed + 99, n_jobs=1)
    final.fit(x, pseudo)
    return final.predict(xtest), clipped / total


def metrics(tau, mu0, mu1):
    true_effect = mu1 - mu0
    if not np.isfinite(tau).all():
        raise FloatingPointError('La predicción contiene valores no finitos')
    return float(np.sqrt(np.mean((tau - true_effect) ** 2))), float(abs(np.mean(tau) - np.mean(true_effect)))


def run():
    replicas = int(os.environ.get('ORYON_REPLICAS', 1 if SHORT else 5))
    epocas = int(os.environ.get('ORYON_EPOCAS', 3 if SHORT else 300))
    if replicas < 1 or epocas < 1:
        raise ValueError('Réplicas y épocas deben ser positivas')
    torch.set_num_threads(1)
    random.seed(SEED)
    np.random.seed(SEED)
    torch.manual_seed(SEED)
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    if device.type == 'cuda':
        torch.backends.cudnn.benchmark = False
        torch.backends.cudnn.deterministic = True
    trees = 8 if SHORT else 100
    print(f'Dispositivo: {device}; réplicas: {replicas}; máximo épocas: {epocas}; árboles: {trees}')
    train_path, test_path = download('train'), download('test')
    summary = {name: [] for name in ('TARNet', 'CFR-MMD', 'Dragonnet', 'DR-learner')}
    try:
        with np.load(train_path, allow_pickle=False) as tr, np.load(test_path, allow_pickle=False) as te:
            ntrain, rtrain = validate_archive(tr, 'train')
            ntest, rtest = validate_archive(te, 'test')
            if rtrain != rtest or replicas > rtrain:
                raise ValueError('Las réplicas solicitadas no corresponden a ambos archivos')
            print(f'Archivos oficiales: train={ntrain}, test={ntest}, réplicas disponibles={rtrain}')
            for replica in range(replicas):
                train, test = load_replica(tr, replica), load_replica(te, replica)
                indices = np.arange(ntrain)
                fit, val = train_test_split(indices, test_size=0.2, stratify=train['t'], random_state=SEED + replica)
                scaler = StandardScaler().fit(train['x'][fit])
                x = scaler.transform(train['x'][fit])
                xval = scaler.transform(train['x'][val])
                xtest = scaler.transform(test['x'])
                t, y = train['t'][fit], train['yf'][fit]
                tval, yval = train['t'][val], train['yf'][val]
                # Normalización de Y solo sobre el entrenamiento factual.
                ymean, yscale = float(y.mean()), float(y.std())
                if yscale <= 1e-12:
                    raise ValueError('La desviación de Y en entrenamiento es nula')
                print(f'\nRéplica {replica + 1}: ajuste={len(fit)}, validación={len(val)}, prueba={ntest}')
                for method in ('TARNet', 'CFR-MMD', 'Dragonnet'):
                    pred, best_epoch, val_mse = fit_neural(method, x, t, (y - ymean) / yscale,
                                                          xval, tval, (yval - ymean) / yscale,
                                                          xtest, SEED + replica, epocas, device)
                    # ymean se cancela al restar resultados potenciales.
                    pred *= yscale
                    pehe, ate = metrics(pred, test['mu0'], test['mu1'])
                    summary[method].append((pehe, ate))
                    print(f'{method:10s} raíz_PEHE={pehe:.6f} error_ATE={ate:.6f} '
                          f'época={best_epoch} ECM_factual_validación={val_mse * yscale ** 2:.6f}')
                pred, clipped = fit_dr(train['x'][fit], t, y, test['x'], SEED + replica, trees)
                pehe, ate = metrics(pred, test['mu0'], test['mu1'])
                summary['DR-learner'].append((pehe, ate))
                print(f'DR-learner raíz_PEHE={pehe:.6f} error_ATE={ate:.6f} '
                      f'propensiones_recortadas={clipped:.3f}')
        print('\nPromedios sobre réplicas seleccionadas; son descriptivos:')
        for method, rows in summary.items():
            scores = np.asarray(rows)
            print(f'{method:10s} raíz_PEHE={scores[:, 0].mean():.6f} error_ATE={scores[:, 1].mean():.6f}')
    finally:
        if device.type == 'cuda':
            torch.cuda.empty_cache()


if __name__ == '__main__':
    run()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Local lab: evaluate a language model

Now build an exploratory test with fully specified binary structural models. Code generates 40 mechanisms with a fixed seed; for each it asks an observational, an interventional, and a counterfactual query, each with abstract and everyday names. Both formulations retain exactly the same probabilities and equations. Enumerating exogenous states with rational arithmetic gives the correct answer; the counterfactual first conditions on the observed fact and retains the same exogenous variables after intervention.

PyTorch, Transformers compatible with Qwen2.5, and model Qwen/Qwen2.5-0.5B-Instruct in the local Hugging Face cache are needed. The cell uses the tokenizer chat template and deterministic generation without modifying weights. With ORYON_SHORT=1 it runs two mechanisms as a path check; without it all 40 are evaluated, totaling 240 queries. It uses CUDA if available and CPU otherwise. The model can be chosen with ORYON_MODEL_ID, and ORYON_DEVICE=cpu forces one CPU thread. Base models without a template can only be used diagnostically via ORYON_ALLOW_PLAIN_PROMPT=1: their results are not those of the instruction-tuned model.

The program retains each raw answer alongside the exact answer. Format violations count as incorrect; their number and accuracy among parseable responses are also shown. The two-form comparison is paired because each mechanism is reused. An accuracy difference shows sensitivity to formulation but alone cannot attribute it to memorization or prove causal understanding. This teaching experiment does not reproduce CLadder or evaluate all causal capabilities.

For each rung, output also compares both answers on the same mechanism: how often only the semantic version is correct, only the abstract version is correct, and mean accuracy difference. These describe generated mechanisms, not a confidence interval or universal performance estimate.

[ ]SCM and local causal-reasoning evaluationLocal GPU
"""Evaluación exploratoria local de Qwen con SCM binarios enumerables.

Requiere torch y transformers compatibles con Qwen2.5, y el modelo
Qwen/Qwen2.5-0.5B-Instruct ya descargado en la caché de Hugging Face.
ORYON_SHORT=1 reduce a dos modelos por peldaño y presentación.
No requiere datos externos ni archivos de Oryon Learn.
"""
import itertools
import json
import os
import random
import re
from collections import defaultdict
from fractions import Fraction

DEFAULT_MODEL_ID = 'Qwen/Qwen2.5-0.5B-Instruct'
MODEL_ID = os.environ.get('ORYON_MODEL_ID', DEFAULT_MODEL_ID)
SEED = 2728
SHORT = os.environ.get('ORYON_SHORT') == '1'
N_MODELS = 2 if SHORT else 40
RUNGS = ('observacional', 'intervencion', 'contrafactual')
FORMS = ('abstracta', 'semantica')
PROBS = tuple(map(Fraction, ('1/4', '1/3', '2/5', '1/2', '3/5', '2/3', '3/4')))


def generate_models(count):
    """Mismos modelos para los tres peldaños y sus dos presentaciones."""
    rng = random.Random(SEED)
    result, seen = [], set()
    while len(result) < count:
        pu, pv, pw = (rng.choice(PROBS) for _ in range(3))
        mask = rng.randrange(1, 255)
        # En cada valor de A hay al menos un resultado 0 y uno 1. Esto
        # garantiza que el hecho A=0,Y=1 tiene probabilidad positiva.
        if not (0 < (mask & 15) < 15 and 0 < (mask >> 4) < 15):
            continue
        key = (pu, pv, pw, mask)
        if key in seen:
            continue
        seen.add(key)
        result.append({'pu': pu, 'pv': pv, 'pw': pw, 'mask': mask})
    return result


def outcome(model, a, u, w):
    return (model['mask'] >> (4 * a + 2 * u + w)) & 1


def exogenous_states(model):
    for u, v, w in itertools.product((0, 1), repeat=3):
        weight = Fraction(1)
        for value, probability in zip((u, v, w), (model['pu'], model['pv'], model['pw'])):
            weight *= probability if value else 1 - probability
        yield u, v, w, weight


def exact_answer(model, rung):
    numerator = Fraction(0)
    denominator = Fraction(0)
    for u, v, w, weight in exogenous_states(model):
        a = u ^ v
        y = outcome(model, a, u, w)
        if rung == 'observacional':
            if a == 1:
                denominator += weight
                numerator += weight * y
        elif rung == 'intervencion':
            denominator += weight
            numerator += weight * outcome(model, 1, u, w)
        elif rung == 'contrafactual':
            if a == 0 and y == 1:
                denominator += weight
                # Abducción: conservar la misma terna exógena factual.
                # Acción: sustituir solo la ecuación de A por A=1.
                numerator += weight * outcome(model, 1, u, w)
        else:
            raise ValueError(f'Peldaño desconocido: {rung}')
    if not denominator:
        raise ValueError('El evento condicionado debe tener probabilidad positiva')
    return numerator / denominator


def prompt_for(model, rung, form):
    if form == 'abstracta':
        setting = 'U, V, W, A e Y son variables binarias abstractas.'
    elif form == 'semantica':
        setting = ('A es el estado de un interruptor e Y es el estado de una luz. U es un estado interno, '
                   'V es una perturbación de activación y W es una perturbación '
                   'de la luz. Todas estas variables son binarias: 1 indica '
                   'presencia o activación, 0 ausencia o desactivación.')
    else:
        raise ValueError(f'Presentación desconocida: {form}')
    lines = [
        setting,
        'Usa exclusivamente el siguiente modelo, sin añadir supuestos:',
        f"U, V y W son independientes; P(U=1)={model['pu']}, P(V=1)={model['pv']}, P(W=1)={model['pw']}.",
        'A=1 si U y V son distintos; A=0 si son iguales.',
        'La ecuación de Y es la siguiente tabla completa:',
        'A U W | Y',
    ]
    for a, u, w in itertools.product((0, 1), repeat=3):
        lines.append(f'{a} {u} {w} | {outcome(model, a, u, w)}')
    if rung == 'observacional':
        question = '¿Cuánto vale P(Y=1 | A=1), observando A sin intervenir?'
    elif rung == 'intervencion':
        question = ('¿Cuánto vale P(Y=1 | do(A=1))? La intervención sustituye '
                    'la ecuación de A por A=1 y conserva las distribuciones de U, V y W.')
    elif rung == 'contrafactual':
        question = ('En una unidad se observó A=0 e Y=1. ¿Cuál es la probabilidad '
                    'de que Y hubiera sido 1 si en esa misma unidad se hubiera '
                    'intervenido con A=1? Conserva sus mismos U, V y W posibles, '
                    'actualizados por el hecho observado, y cambia solo la ecuación de A.')
    else:
        raise ValueError(f'Peldaño desconocido: {rung}')
    lines += [question, 'Responde solo en una línea: RESPUESTA: seguida de una fracción o un decimal con al menos tres cifras decimales.']
    return '\n'.join(lines)


NUMBER = re.compile(r'^\s*RESPUESTA\s*:\s*([+-]?\d+(?:[.,]\d+)?(?:\s*/\s*\d+)?)\s*$', re.IGNORECASE)


def parse_answer(text):
    """Acepta solo la línea pedida; no extrae números de explicaciones."""
    match = NUMBER.fullmatch(text)
    if not match:
        return None
    try:
        return Fraction(match.group(1).replace(',', '.').replace(' ', ''))
    except (ValueError, ZeroDivisionError):
        return None


def encode_messages(tokenizer, messages):
    """Utiliza la plantilla del tokenizador o un modo explícito de diagnóstico."""
    if tokenizer.chat_template:
        text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
        # La plantilla ya añade los tokens especiales que necesita el modelo.
        return tokenizer(text, return_tensors='pt', add_special_tokens=False)
    if os.environ.get('ORYON_ALLOW_PLAIN_PROMPT') != '1':
        raise ValueError('El tokenizador no tiene plantilla de chat. Para una prueba de flujo con un modelo base, activa ORYON_ALLOW_PLAIN_PROMPT=1; no compares ese resultado con el instruct.')
    text = '\n\n'.join(message['content'] for message in messages) + '\n'
    return tokenizer(text, return_tensors='pt', add_special_tokens=True)


def run():
    # Importaciones aquí para que el generador y el oráculo no requieran GPU.
    import torch
    from transformers import AutoModelForCausalLM, AutoTokenizer

    torch.manual_seed(SEED)
    requested_device = os.environ.get('ORYON_DEVICE', 'auto')
    if requested_device not in ('auto', 'cpu', 'cuda'):
        raise ValueError('ORYON_DEVICE debe ser auto, cpu o cuda')
    if requested_device == 'cuda' and not torch.cuda.is_available():
        raise RuntimeError('Se solicitó CUDA, pero no está disponible')
    device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu') if requested_device == 'auto' else requested_device)
    if device.type == 'cpu':
        torch.set_num_threads(1)
    if os.environ.get('ORYON_CHECK_DEFAULT_TEMPLATE') == '1':
        default_tokenizer = AutoTokenizer.from_pretrained(DEFAULT_MODEL_ID, local_files_only=True)
        if not default_tokenizer.chat_template:
            raise ValueError('Qwen predeterminado no dispone de plantilla de chat')
        check = encode_messages(default_tokenizer, [{'role': 'system', 'content': 'Responde brevemente.'}, {'role': 'user', 'content': 'Di uno.'}])
        if check['input_ids'].shape[1] == 0:
            raise ValueError('Plantilla Qwen vacía')
        print(f"Plantilla Qwen comprobada: {check['input_ids'].shape[1]} tokens", flush=True)
        del check, default_tokenizer
    tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, local_files_only=True)
    if not tokenizer.chat_template and os.environ.get('ORYON_ALLOW_PLAIN_PROMPT') != '1':
        raise ValueError('El modelo elegido no tiene plantilla de chat; activa el modo de diagnóstico explícitamente si procede')
    print(f"Modelo: {MODEL_ID} | dispositivo: {device} | plantilla: {'chat' if tokenizer.chat_template else 'texto plano de diagnóstico'}", flush=True)
    model = AutoModelForCausalLM.from_pretrained(MODEL_ID, local_files_only=True)
    model = model.to(device).eval()
    observations = []
    try:
        for index, scm in enumerate(generate_models(N_MODELS), start=1):
            for rung in RUNGS:
                truth = exact_answer(scm, rung)
                for form in FORMS:
                    messages = [
                        {'role': 'system', 'content': 'Resuelve la pregunta usando el modelo dado y sigue exactamente el formato de respuesta.'},
                        {'role': 'user', 'content': prompt_for(scm, rung, form)},
                    ]
                    inputs = encode_messages(tokenizer, messages).to(device)
                    with torch.inference_mode():
                        generated = model.generate(**inputs, do_sample=False, max_new_tokens=64,
                                                   pad_token_id=tokenizer.eos_token_id)
                    raw = tokenizer.decode(generated[0, inputs['input_ids'].shape[1]:], skip_special_tokens=True).strip()
                    parsed = parse_answer(raw)
                    # Un decimal redondeado a tres lugares puede diferir en 0,0005.
                    correct = parsed is not None and abs(parsed - truth) <= Fraction(51, 100000)
                    record = {'id': index, 'peldaño': rung, 'forma': form,
                              'verdad_exacta': str(truth), 'salida': raw,
                              'analizable': parsed is not None, 'correcta': correct}
                    observations.append(record)
                    print(json.dumps(record, ensure_ascii=False), flush=True)
                    del inputs, generated
        groups = defaultdict(list)
        for row in observations:
            groups[(row['peldaño'], row['forma'])].append(row)
        print('\nResumen: errores de formato cuentan como incorrectos en la precisión total.')
        for rung in RUNGS:
            for form in FORMS:
                rows = groups[(rung, form)]
                n = len(rows)
                valid = sum(row['analizable'] for row in rows)
                correct = sum(row['correcta'] for row in rows)
                print(f'{rung:14s} {form:10s} n={n:2d} correctas={correct:2d} '
                      f'precisión={correct / n:.3f} no_analizables={n - valid:2d} '
                      f'precisión_analizables={correct / valid:.3f}' if valid else
                      f'{rung:14s} {form:10s} n={n:2d} correctas=0 precisión=0.000 '
                      f'no_analizables={n:2d} precisión_analizables=no_definida')
        print('\nComparación pareada: acierto semántico menos acierto abstracto.')
        for rung in RUNGS:
            pairs = {(row['id'], row['forma']): row['correcta']
                     for row in observations if row['peldaño'] == rung}
            diffs = [int(pairs[(i, 'semantica')]) - int(pairs[(i, 'abstracta')])
                     for i in range(1, N_MODELS + 1)]
            print(f'{rung:14s} solo_semántica={diffs.count(1)} '
                  f'solo_abstracta={diffs.count(-1)} diferencia={sum(diffs) / len(diffs):+.3f}')
    finally:
        del model
        if device.type == 'cuda':
            torch.cuda.empty_cache()


if __name__ == '__main__':
    run()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofFrom factual loss to effect error
Prove: Under the CFR bound assumptions above, explain its two steps without omitting counterfactual loss or the variance term. Let mt(x)m_t(x) denote the conditional potential-outcome mean.
The proof will appear here as you work.

Step 1 of 3. When effect error is written as a difference of two prediction errors, which inequality bounds its square?

ProofIdentify the bridge coefficient
Prove: In the lesson’s linear SCM with independent innovations, c≠0c\ne0 and Cov⁡(Z,W∣T)≠0\operatorname{Cov}(Z,W\mid T)\ne0, derive the bridge’s causal coefficient.
The proof will appear here as you work.

Step 1 of 3. What residual remains if h(W,T)=θT+(d/c)W?

CodeDragonnet targeted loss
Implement dragonnet_loss(y, t, y0_hat, y1_hat, e_hat, eps, beta=1.0) with finite, nonempty, equal-length one-dimensional NumPy vectors; t contains only 0 or 1 and all propensities are strictly between zero and one. Reject invalid inputs with ValueError. eps and beta are finite scalars and beta is nonnegative. Define q=(1-t)y0_hat+t y1_hat, h=t/e_hat-(1-t)/(1-e_hat), q_dir=q+eps h. Return mean (y-q)² plus binary cross-entropy of t and e_hat plus beta times mean (y-q_dir)². Do not silently clip e_hat. This explicit function permits finite-difference derivative checks; autograd training occurs in the local lab.
def dragonnet_loss(y, t, y0_hat, y1_hat, e_hat, eps, beta=1.0):
  raise NotImplementedError('Implementa la pérdida')
Shift+Enter to run

For the following exercise, a cell creates two lists of 40 correct or incorrect answers for a teaching example. These are artificial data for practicing the calculation, not results from an evaluated model.

[ ]Count example answersBrowser
import numpy as np
respuestas_con_nombres = np.array([1]*32 + [0]*8)
respuestas_anonimas = np.array([1]*25 + [0]*15)
print('Aciertos con nombres y anónimos:',
      respuestas_con_nombres.sum(), respuestas_anonimas.sum())
print('Precisión porcentual y caída en puntos:',
      100*respuestas_con_nombres.mean(), 100*respuestas_anonimas.mean(),
      100*(respuestas_con_nombres.mean()-respuestas_anonimas.mean()))
NumericCompare two formulations
A rung has 40 questions. Semantic names yield 32 correct answers and anonymous names yield 25. Calculate the accuracy drop in percentage points.
QuizRead the benchmark
A paper reports low IHDP PEHE and extrapolates to a population with unmeasured confounding. What conclusion is supported?