Frontier: neural SDEs, latent SDEs and path signatures
Learn stochastic dynamics from data using neural and latent SDEs, variational and adversarial path models, stochastic adjoints, neural controlled differential equations and path signatures.
After this lesson you can
- Implement and train a neural SDE to reproduce OU and stochastic-volatility path laws.
- Derive a latent SDE ELBO with Girsanov and train on irregular series using local GPU.
- Compare backpropagation through the solver with stochastic adjoints in memory and accuracy.
- Calculate truncated signatures and signature kernels for path classification or comparison.
- Position these methods relative to diffusion models and classical statistics and propose a research question.
Before you start
- 26Stochastic differential equationGirsanov theoremKL divergence between diffusion path measuresEuler-Maruyama schemeStrong and weak convergenceStratonovich integralQuadratic variation
- 03Neural ordinary differential equationAdjoint sensitivity method
- 19Variational autoencoderGAN minimax gameGAN training recipes
- 15Micro framework to PyTorch correspondence
- 00Canonical training and evaluation loopDevice placement and CPU-GPU transfers
Learn one path or a law of paths?
Two models can reproduce the distribution of an observation at each time yet generate paths with very different persistence or barrier crossings. To generate market scenarios, describe a noisy physical system or analyze an irregularly observed history, ask which joint law you want to reproduce and what information the sample actually provides.
A neural stochastic differential equation uses parameterized functions for drift and, where appropriate, diffusion:
Choose the Itô or Stratonovich interpretation and retain it in simulation, gradients and interpretation. Strong existence and uniqueness on a finite horizon follow, for example, from global Lipschitz and linear-growth conditions in state, together with a square-integrable initial condition. An arbitrary network does not automatically satisfy these assumptions. Bounding diffusion helps prevent numerical explosions but does not replace assumptions on drift and regularity. Strictly positive diagonal diffusion also simplifies the ratio in change of measure; if singular, the drift difference must belong to its image.
When discretizing with Euler-Maruyama, paths, loss and gradients depend on step size. Reducing it alone does not correct incorrect statistical specification. Finite-grid observations do not necessarily identify the complete continuous law: without further assumptions, different dynamics can be compatible with the same observed transitions. Quadratic variation distinguishes diffusion under ideal continuous observation, but estimating it from discrete data and measurement noise is another problem.
The following short training run uses a synthetic double well and this lesson’s lab. Observations have the same scale in generator and model, but improved ELBO and forecast fans do not prove drift or diffusion is identified.
Synthetic drift is not globally Lipschitz and explicit Euler can be unstable for extreme states. The example’s neural prior is bounded and cannot match that drift on the entire line: field comparison is limited to the plotted interval. If increasing step size or duration, watch for nonfinite paths and consider a scheme appropriate for nonlinear drift; do not interpret the short run as a general stability proof.
A latent SDE as a probabilistic model
In a latent SDE the hidden path explains noisy observations, which may arrive at irregular times. Let the prior be under and the variational posterior under :
For the next identity assume square invertible diffusion, also shared by prior and posterior. With singular diffusion, the drift difference must be in its image and the minimum-norm control must be used: adding to a component of the kernel of does not change the law of , but changes its energy. Control can depend on an encoder of available observations to infer the complete path. That does not permit future information in a causal forecasting task: real-time filtering requires the encoder to use only the past.
Under suitable integrability and change-of-measure conditions, for example a sufficient Novikov condition, Girsanov gives:
The identity requires direction and expectation under . If diffusions change freely between the two laws, their quadratic variations can distinguish them and this formula does not apply directly. The variational bound for conditionally independent observations at times is
The bound comes from applying Jensen to the joint model-to-posterior ratio. An improving bound does not prove generated paths are correct: compare increment distributions, autocorrelations, persistence in regions and path statistics relevant to the application. Tzen and Raginsky develop latent Gaussian models in the diffusion limit.
To see where the sign comes from, take the logarithm of the path density of relative to . Under the stochastic term has zero expectation and positive energy remains, alongside the initial ratio. Thus maximizing the bound subtracts both initial divergence and shift energy. In Euler, if both steps have variance and means differ by , their conditional KL is exactly in the scalar case. Summing over steps gives a bound for the discretized model; its difference from the continuous SDE still requires study.
In the figure, the ELBO curve is evaluated on held-out paths with a fixed realization of inference noise to facilitate comparison across epochs. That Monte Carlo estimate has variability. Fans are marginal quantiles at each time, not simultaneous bands for a complete path; two laws can share them while differing in temporal dependence.
Gradients and reproducible noise
Direct backpropagation retains the solver-step graph. The stochastic adjoint poses another backward equation to calculate sensitivities. Comparison is valid when both methods use the same Brownian realization, objective, discretization and precision; comparing gradients on independent noise mixes numerical error with sampling variability.
A Brownian tree queries compatible increments on different intervals without storing an entire discretized path. The method of Li and colleagues analyzes noise reconstruction and scalable gradients. Total memory includes solver, model and tree implementation: do not extrapolate one component’s cost to the complete program. In addition, the gradient of a discretized continuous adjoint equation can differ from the exact gradient of the fixed-step discrete program; a resolution study helps separate the quantities.
The next experiment must synchronize the GPU before and after measurement, reset peak-memory counters for each method and use the same tree for both. Also check a derivative by finite differences with fixed noise: matching paths does not guarantee the backward computation is correct. Times and peaks are properties of this implementation and shared machine, not architecture constants.
Generate, discriminate and control
In a path GAN, the generator can be a neural SDE and the discriminator a controlled equation receiving the entire path. They are fitted in an adversarial game to bring laws closer, not to pair one generated path with each observation. Kidger and colleagues develop this infinite-dimensional GAN perspective. Architecture and finite experimental samples still limit what the discriminator can detect.
If ranges over a class of path functions, an idealized objective compares and . Wasserstein interpretation requires controlling the class and regularity of ; a particular network and finite iterations only approximate that supremum. A small adversarial loss for that discriminator does not rule out differences detectable by another statistic or on another time scale.
A neural controlled differential equation evolves according to a control path :
For irregular data, construct a continuous control by interpolation, including time and, where appropriate, observation indicators. Interpolation type determines control behavior between measurements. An interpolation using future points can be valid for classifying a complete path, but leaks information if used unmodified for online prediction. The Neural CDE paper studies irregularly observed series.
For example, two identical observations separated by a minute and by a year produce the same value path if the clock is removed. Adding time allows to respond differently to elapsed intervals. A mask distinguishes a missing measurement from a real zero. For a polygonal control, each segment drives an ordinary equation with constant derivative; limits of rough signals require specifying the lift and notion of integral.
Signatures: retaining order in iterated integrals
The signature of a continuous path of bounded variation collects its iterated integrals. For , level is
The first level is the increment; the second retains order information. In two dimensions, is the algebraic area enclosed when the path is closed by a chord. Oppositely signed loops can cancel, so zero area does not imply absence of motion.
For a segment with increment , the signature is the truncated tensor exponential: . If concatenating paths with signatures and , Chen’s identity says , where the tensor product is understood by levels. In particular, for increments and :
The proof divides domain into three regions: both times in the first path, one in each path and both in the second. The cross rectangle contributes , in that order. In the cell, increments and produce first level and area : swapping order changes area while retaining total increment.
The spatial signature does not change under continuous increasing reparameterization. Reversing the path changes signs of increment and area, while higher levels obey index-order reversal with the corresponding sign. Adding time as a channel retains speed information and changes this invariance. A full signature identifies paths only under appropriate assumptions and equivalences; a truncated signature loses information. In dimension the number of coordinates through level is , a real memory constraint.
A path traversing a segment and returning over it has a trivial signature: outward and return displacements cancel at all levels. This is an example of tree-like equivalence. Universality is therefore formulated on suitable path spaces, often after time augmentation, and does not mean a fixed truncation distinguishes every pair. Lead-lag augmentation converts a discrete sequence into a two-dimensional path whose area encodes a sum of squared increments, according to traversal convention. The signature of that polygonal interpolation must not automatically be confused with an Itô or Stratonovich integral of the continuous limit.
The signature kernel compares paths via inner products of their representations. With finite truncation it is an inner product of signature vectors and hence positive semidefinite. The full kernel can be calculated through a Goursat equation under the conditions in Salvi and colleagues. See also the Chevyrev-Kormilitzin primer for assumptions on universality and path equivalence.
Reproducible labs
Locally, install PyTorch, NumPy, pandas and optionally torchsde==0.2.6. The code separately trains an OU, a double well and the OT channel of ETTh1. Irregular masks are artificially generated on a regular grid: they are not attributed to the original dataset. In ETTh1 the split is temporal and scale is fitted on the earlier segment; windows can overlap, so they are not independent samples. The short run checks the program, while full configuration increases data and training steps. The posterior uses a GRU observing the entire path and serves smoothing, not online prediction. Prior and posterior share diffusion; the calculated ELBO corresponds to discretization.
"""EDE latente con ELBO discretizado sobre datos sintéticos y ETTh1.
Requiere numpy, pandas y torch; torchsde es opcional para contrastar Euler.
ORYON_SHORT=1 activa una verificación pequeña; ORYON_DATA_DIR y ORYON_OUTPUT_DIR
permiten elegir las carpetas. La EDE real es un modelo, no una ley identificada.
"""
import gc
import hashlib
import json
import math
import os
import urllib.request
from pathlib import Path
import numpy as np
import pandas as pd
import torch
from torch import nn
torch.set_num_threads(1)
torch.manual_seed(313100)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
short=os.environ.get('ORYON_SHORT')=='1'
steps=32 if short else 64
T=2.0
dt=T/steps
epochs=4 if short else 60
batches_per_epoch=8 if short else 12
batch_size=16 if short else 64
train_size=96 if short else 512
test_size=48 if short else 256
obs_sd=0.2
data_dir=Path(os.environ.get('ORYON_DATA_DIR','data'))
output_dir=Path(os.environ.get('ORYON_OUTPUT_DIR','neural-sde-output'))
data_dir.mkdir(parents=True,exist_ok=True)
output_dir.mkdir(parents=True,exist_ok=True)
print('Dispositivo:',device,'pasos:',steps,'épocas:',epochs,'lotes/época:',batches_per_epoch,flush=True)
def synthetic(name, n, seed):
rng=np.random.default_rng(seed)
latent=np.empty((n,steps+1),dtype=np.float32)
latent[:,0]=rng.normal(size=n)
for k in range(steps):
x=latent[:,k]
drift=-.8*x if name=='OU' else x-x**3
latent[:,k+1]=x+drift*dt+.7*np.sqrt(dt)*rng.normal(size=n)
observed=latent+obs_sd*rng.normal(size=latent.shape)
mask=rng.random(latent.shape)<.3
mask[:,0]=True; mask[:,-1]=True
return latent.astype(np.float32),observed.astype(np.float32),mask.astype(np.float32)
def real_data():
path=data_dir/'ETTh1.csv'
if not path.exists():
url='https://raw.githubusercontent.com/zhouhaoyi/ETDataset/main/ETT-small/ETTh1.csv'
urllib.request.urlretrieve(url,path)
digest=hashlib.sha256(path.read_bytes()).hexdigest()
expected='f18de3ad269cef59bb07b5438d79bb3042d3be49bdeecf01c1cd6d29695ee066'
if digest!=expected:
raise ValueError('ETTh1 no coincide con la versión de referencia')
values=pd.read_csv(path)['OT'].to_numpy(dtype=np.float64)
split=3000
mean,std=values[:split].mean(),values[:split].std()
if not np.isfinite(values).all() or std<=0:
raise ValueError('Serie o escala no válidas')
values=(values-mean)/std
rng=np.random.default_rng(313104)
train_starts=rng.integers(0,split-steps,size=train_size)
test_starts=rng.integers(split,split+500,size=test_size)
def build(starts):
x=np.stack([values[s:s+steps+1] for s in starts]).astype(np.float32)
mask=(rng.random(x.shape)<.3).astype(np.float32)
mask[:,0]=1; mask[:,-1]=1
return x,x.copy(),mask
print('ETTh1 OT, hash:',digest,'corte temporal:',split,
'escala ajustada solo antes del corte; máscara irregular artificial',flush=True)
return build(train_starts),build(test_starts)
class LatentSDE(nn.Module):
"""La posterior y el prior usan la misma difusión escalar positiva."""
def __init__(self):
super().__init__()
width=16 if short else 32
self.encoder=nn.GRU(3,width,batch_first=True)
self.initial=nn.Linear(width,2)
self.drift=nn.Sequential(nn.Linear(1,width),nn.Tanh(),nn.Linear(width,1),nn.Tanh())
self.control=nn.Sequential(nn.Linear(width+2,width),nn.Tanh(),nn.Linear(width,1),nn.Tanh())
self.raw_sigma=nn.Parameter(torch.tensor(0.))
def sigma(self):
return .15+.85*torch.sigmoid(self.raw_sigma)
def prior(self,z):
return 2*self.drift(z)
def posterior_control(self,z,t,context):
time=torch.full_like(z,t/T)
return 2*self.control(torch.cat([z,time,context],dim=1))
def neg_elbo(self,y,mask,generator=None):
time=torch.linspace(0,1,steps+1,device=y.device).expand(len(y),-1)
encoder_input=torch.stack([y*mask,mask,time],dim=-1)
_,hidden=self.encoder(encoder_input)
context=hidden[-1]
initial=self.initial(context)
mean=initial[:,:1]
log_std=initial[:,1:2].clamp(-3.,1.)
sigma=self.sigma()
z=mean+log_std.exp()*torch.randn(mean.shape,device=y.device,generator=generator)
kl0=.5*(mean.square()+torch.exp(2*log_std)-1-2*log_std).squeeze(1)
klpath=torch.zeros(len(y),device=y.device)
likelihood=torch.distributions.Normal(z.squeeze(1),obs_sd).log_prob(y[:,0])*mask[:,0]
for k in range(steps):
u=self.posterior_control(z,k*dt,context)
noise=torch.randn(z.shape,device=y.device,generator=generator)
z=z+(self.prior(z)+sigma*u)*dt+sigma*math.sqrt(dt)*noise
klpath=klpath+.5*u.squeeze(1).square()*dt
likelihood=likelihood+torch.distributions.Normal(z.squeeze(1),obs_sd).log_prob(y[:,k+1])*mask[:,k+1]
return -(likelihood-kl0-klpath).mean(),likelihood.mean(),kl0.mean(),klpath.mean()
@torch.no_grad()
def prior_paths(self,count,seed):
generator=torch.Generator(device=device).manual_seed(seed)
z=torch.randn((count,1),device=device,generator=generator)
paths=[z.squeeze(1)]
for _ in range(steps):
z=z+self.prior(z)*dt+self.sigma()*math.sqrt(dt)*torch.randn(z.shape,device=device,generator=generator)
paths.append(z.squeeze(1))
return torch.stack(paths,dim=1).cpu().numpy()
def compare_torchsde(model):
try:
import torchsde
except ImportError:
print('torchsde no instalado: comparación omitida',flush=True)
return None
class FixedBrownian:
levy_area_approximation='none'
def __init__(self,dw):
self.dw=dw; self.shape=dw.shape[1:]; self.dtype=dw.dtype; self.device=dw.device
def __call__(self,ta,tb=None,return_U=False,return_A=False):
if tb is None or return_U or return_A:
raise ValueError('Solo incrementos de la malla')
i,j=round(float(ta)/dt),round(float(tb)/dt)
if j!=i+1 or not 0<=i<steps:
raise ValueError('Consulta fuera de la malla')
return self.dw[i]
class PriorWrapper(nn.Module):
noise_type='diagonal'
sde_type='ito'
def __init__(self,latent):
super().__init__(); self.latent=latent
def f(self,t,z):
return self.latent.prior(z)
def g(self,t,z):
return torch.ones_like(z)*self.latent.sigma()
generator=torch.Generator(device=device).manual_seed(313190)
z0=torch.randn((8,1),device=device,generator=generator)
dw=math.sqrt(dt)*torch.randn((steps,8,1),device=device,generator=generator)
with torch.no_grad():
z=z0.clone()
for k in range(steps):
z=z+model.prior(z)*dt+model.sigma()*dw[k]
ts=torch.tensor([0.,T],device=device)
library=torchsde.sdeint(PriorWrapper(model),z0,ts,bm=FixedBrownian(dw),method='euler',dt=dt,adaptive=False)[-1]
difference=float(torch.max(torch.abs(z-library)).cpu())
assert difference<1e-5
print('Mismo ruido: diferencia máxima Euler propio/torchsde:',difference,flush=True)
return difference
real_train,real_test=real_data()
datasets=[('OU',synthetic('OU',train_size,313101),synthetic('OU',test_size,313102)),
('doble_pozo',synthetic('doble_pozo',train_size,313105),synthetic('doble_pozo',test_size,313106)),
('ETTh1_OT',real_train,real_test)]
summary={}
for model_index,(name,train,test) in enumerate(datasets):
train_y=torch.as_tensor(train[1],device=device)
train_mask=torch.as_tensor(train[2],device=device)
test_y=torch.as_tensor(test[1],device=device)
test_mask=torch.as_tensor(test[2],device=device)
model=LatentSDE().to(device)
optimizer=torch.optim.Adam(model.parameters(),lr=.003)
batch_rng=np.random.default_rng(313200+model_index)
grids=np.linspace(-2,2,41,dtype=np.float32)
snapshots=[]
for epoch in range(epochs+1):
if epoch:
model.train()
for _ in range(batches_per_epoch):
indices=batch_rng.integers(0,len(train_y),size=batch_size)
optimizer.zero_grad(set_to_none=True)
loss,_,_,_=model.neg_elbo(train_y[indices],train_mask[indices])
if not torch.isfinite(loss): raise ValueError('ELBO no finito')
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(),5.)
optimizer.step()
if epoch in set(np.linspace(0,epochs,5,dtype=int)):
model.eval()
with torch.no_grad():
gen=torch.Generator(device=device).manual_seed(313300+model_index)
loss,likelihood,kl0,klpath=model.neg_elbo(test_y,test_mask,gen)
drift=model.prior(torch.tensor(grids[:,None],device=device)).squeeze(1).cpu().numpy()
generated=model.prior_paths(128 if short else 512,313400+model_index)
fan=np.quantile(generated,[.1,.5,.9],axis=0)
target=np.quantile(test[0],[.1,.5,.9],axis=0)
snapshots.append({'epoch':int(epoch),'heldout_neg_elbo':float(loss.cpu()),
'heldout_loglik':float(likelihood.cpu()),'kl0':float(kl0.cpu()),
'klpath':float(klpath.cpu()),'sigma':float(model.sigma().cpu()),
'drift':drift.tolist(),'fan':fan.tolist(),'target_fan':target.tolist()})
print(name,'época:',epoch,'ELBO negativo reservado:',float(loss.cpu()),
'sigma:',float(model.sigma().cpu()),flush=True)
comparison=compare_torchsde(model)
summary[name]={'grid':grids.tolist(),'times':np.linspace(0,T,steps+1).tolist(),
'observations':obs_sd,'snapshots':snapshots,'torchsde_maxdiff':comparison}
del model,optimizer,train_y,train_mask,test_y,test_mask
gc.collect()
if device.type=='cuda': torch.cuda.empty_cache()
out={'run':'short' if short else 'full','device':str(device),'steps':steps,'epochs':epochs,
'batch_size':batch_size,'batches_per_epoch':batches_per_epoch,'train_size':train_size,
'test_size':test_size,'seed':313100,'results':summary,
'limits':'Máscaras sintéticas en malla; ELBO de Euler y comparación de abanicos no identifican la dinámica.'}
destination=output_dir/'latent_sde_results.json'
destination.write_text(json.dumps(out,ensure_ascii=False,indent=2),encoding='utf-8')
print('Resultados generados:',destination,flush=True)npm run lab and open the connection link.Learning latent volatility
Now observed returns are Gaussian conditional on latent log-volatility following OU dynamics. The prior combines trainable OU parameters with a bounded neural drift correction; the posterior uses a bidirectional GRU and shares reference drift and diffusion. Discrete KL penalizes drift shift divided by diffusion. We separate independent training and test paths and also compare unconditional prior samples: smoothing observed paths well is insufficient to generate their law correctly.
In the short check, generated terminal log-volatility deviation falls below the held-out value. This discrepancy is an experimental result and shows the reduced fit has not fully reproduced the law; also compare returns and their dependence. The true state is accessible here because this is a simulation, not because it is observable in a real market. ELBO and smoother reconstruction are not a predictive likelihood.
Squared-return correlation pools adjacent pairs from all paths and times. Because the state starts at zero and its distribution changes over time, it is not a stationary autocorrelation or necessarily the correlation at each time. The short run compares 64 held-out paths with 2048 generated by each prior; statistics have sampling uncertainty and different sample sizes.
"""Inferencia variacional didáctica de volatilidad latente OU.
Sin pesos previos ni datos externos. La posterior usa toda la serie observada
para suavizar h, no constituye un pronóstico causal. El modelo y el ELBO son
de tiempo discretizado con Euler, y comparten la difusión entre prior y posterior.
"""
import json
import math
import os
from pathlib import Path
import numpy as np
import torch
from torch import nn
torch.set_num_threads(1)
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
STEPS, T = 32, 1.0
DT = T / STEPS
KAPPA, THETA, SIGMA = 1.0, -0.5, 1.2
DATA_SEED, TEST_SEED, TRAIN_SEED, EVAL_SEED = 263110, 263111, 263112, 263113
def simulate(count, seed):
rng = np.random.default_rng(seed)
hidden = np.zeros((count, STEPS + 1), dtype=np.float32)
returns = np.zeros((count, STEPS), dtype=np.float32)
for i in range(STEPS):
returns[:, i] = np.exp(hidden[:, i] / 2) * np.sqrt(DT) * rng.normal(size=count)
hidden[:, i+1] = (hidden[:, i] + KAPPA * (THETA - hidden[:, i]) * DT
+ SIGMA * np.sqrt(DT) * rng.normal(size=count))
return torch.tensor(returns, device=DEVICE), torch.tensor(hidden, device=DEVICE)
class Posterior(nn.Module):
def __init__(self):
super().__init__()
self.encoder = nn.GRU(1, 16, batch_first=True, bidirectional=True)
self.control = nn.Sequential(nn.Linear(33, 32), nn.Tanh(), nn.Linear(32, 1), nn.Tanh())
# Inicialización deliberadamente distinta de los parámetros generadores.
self.raw_kappa = nn.Parameter(torch.tensor(math.log(math.expm1(.55))))
self.theta = nn.Parameter(torch.tensor(.1))
self.raw_sigma = nn.Parameter(torch.tensor(math.log(.5 / 1.9)))
self.prior_network = nn.Sequential(nn.Linear(1, 16), nn.Tanh(), nn.Linear(16, 1))
nn.init.zeros_(self.prior_network[-1].weight)
nn.init.zeros_(self.prior_network[-1].bias)
def coefficients(self):
kappa = .05 + torch.nn.functional.softplus(self.raw_kappa)
sigma = .1 + 2.4 * torch.sigmoid(self.raw_sigma)
return kappa, self.theta, sigma
def prior_correction(self, state):
return .3 * torch.tanh(self.prior_network(state[..., None]).squeeze(-1))
def simulate(self, observations, noise):
# El contexto bidireccional usa toda la serie: esto es suavizado.
features, _ = self.encoder((observations / math.sqrt(DT)).unsqueeze(-1))
kappa, theta, sigma = self.coefficients()
z = torch.zeros(len(observations), device=observations.device)
states, controls = [z], []
for i in range(STEPS):
u = 2.0 * self.control(torch.cat((z[:, None], features[:, i]), dim=-1)).squeeze(-1)
z = z + (kappa * (theta-z) + self.prior_correction(z) + u) * DT + sigma * math.sqrt(DT) * noise[:, i]
states.append(z)
controls.append(u)
return torch.stack(states, dim=1), torch.stack(controls, dim=1)
def prior(noise, kappa, theta, sigma, correction=None):
z = torch.zeros(len(noise), device=noise.device)
states = [z]
for i in range(STEPS):
extra = correction(z) if correction is not None else 0.
z = z + (kappa * (theta-z) + extra) * DT + sigma * math.sqrt(DT) * noise[:, i]
states.append(z)
return torch.stack(states, dim=1)
def reconstruction_nll(observations, states):
log_variance = states[:, :-1] + math.log(DT)
return .5 * (math.log(2*math.pi) + log_variance + observations.square() * torch.exp(-log_variance)).sum(dim=1)
def main():
short = os.environ.get('ORYON_SHORT') == '1'
iterations = 250 if short else 1600
train_n, test_n, batch, mc = (256, 64, 32, 32) if short else (2048, 256, 64, 128)
torch.manual_seed(TRAIN_SEED)
if DEVICE.type == 'cuda': torch.cuda.manual_seed_all(TRAIN_SEED)
train_y, _ = simulate(train_n, DATA_SEED)
test_y, test_h = simulate(test_n, TEST_SEED)
model = Posterior().to(DEVICE)
opt = torch.optim.Adam(model.parameters(), lr=.002)
progress = []
for step in range(iterations):
model.train()
idx = torch.randint(train_n, (batch,), device=DEVICE)
y = train_y[idx]
noise = torch.randn(batch, STEPS, device=DEVICE)
states, u = model.simulate(y, noise)
_, _, sigma = model.coefficients()
nll = reconstruction_nll(y, states)
kl = .5 * (u / sigma).square().sum(dim=1) * DT
loss = (nll + kl).mean()
if not torch.isfinite(loss): raise RuntimeError('ELBO no finito')
opt.zero_grad(set_to_none=True)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 5.0)
opt.step()
if step in (0, iterations - 1) or (step + 1) % 50 == 0:
row = {'iteration':step+1, 'negative_elbo':float(loss.detach()),
'nll':float(nll.mean().detach()), 'kl':float(kl.mean().detach())}
progress.append(row)
print('entrenamiento', row, flush=True)
model.eval()
torch.manual_seed(EVAL_SEED)
if DEVICE.type == 'cuda': torch.cuda.manual_seed_all(EVAL_SEED)
with torch.no_grad():
kappa, theta, sigma = model.coefficients()
y = test_y.repeat_interleave(mc, dim=0)
noise = torch.randn(test_n * mc, STEPS, device=DEVICE)
posterior, u = model.simulate(y, noise)
reference = prior(noise, kappa, theta, sigma, model.prior_correction)
posterior_nll = reconstruction_nll(y, posterior).reshape(test_n, mc)
prior_nll = reconstruction_nll(y, reference).reshape(test_n, mc)
kl = (.5 * (u / sigma).square().sum(dim=1) * DT).reshape(test_n, mc)
posterior_mean = posterior.reshape(test_n, mc, STEPS+1).mean(dim=1)
# La corrección neuronal impide una media cerrada; estimamos una única
# media incondicional común a las series con test_n*mc caminos del prior.
prior_mean = reference.mean(dim=0, keepdim=True).expand(test_n, -1)
posterior_rmse = (posterior_mean - test_h).square().mean().sqrt()
prior_rmse = (prior_mean - test_h).square().mean().sqrt()
result = {'posterior_latent_rmse':float(posterior_rmse), 'prior_latent_rmse':float(prior_rmse),
'posterior_negative_elbo_per_series':float((posterior_nll + kl).mean()),
'prior_negative_elbo_per_series':float(prior_nll.mean()),
'posterior_reconstruction_nll_per_series':float(posterior_nll.mean()),
'posterior_path_kl_per_series':float(kl.mean()),
'test_series':test_n, 'mc_paths_per_series':mc}
# Ley generada sin condicionar en observaciones: misma cantidad de
# realizaciones para el prior ajustado y el punto inicial sin entrenar.
law_size = test_n * mc
innovations = torch.randn(law_size, STEPS, device=DEVICE)
observation_noise = torch.randn(law_size, STEPS, device=DEVICE)
learned_h = prior(innovations, kappa, theta, sigma, model.prior_correction)
initial_h = prior(innovations, .6, .1, .6)
learned_y = torch.exp(learned_h[:, :-1] / 2) * math.sqrt(DT) * observation_noise
initial_y = torch.exp(initial_h[:, :-1] / 2) * math.sqrt(DT) * observation_noise
def moments(y, h):
squared = y.square()
left, right = squared[:, :-1].reshape(-1), squared[:, 1:].reshape(-1)
left, right = left-left.mean(), right-right.mean()
corr = (left * right).mean() / torch.sqrt(left.square().mean() * right.square().mean())
return {'h_terminal_mean':float(h[:, -1].mean()), 'h_terminal_std':float(h[:, -1].std(unbiased=True)),
'return_mean':float(y.mean()), 'return_std':float(y.std(unbiased=True)),
'squared_return_lag1_correlation':float(corr)}
laws = {'heldout_truth':moments(test_y, test_h), 'learned_prior':moments(learned_y, learned_h),
'initial_prior':moments(initial_y, initial_h),
'generated_trajectories':law_size}
examples = {'returns':test_y[:3].cpu().tolist(), 'hidden':test_h[:3].cpu().tolist(),
'posterior_mean':posterior_mean[:3].cpu().tolist(), 'prior_mean':prior_mean[:3].cpu().tolist()}
output = {'model':'Euler con prior OU más deriva neuronal acotada y retornos normales condicionales',
'interpretation':'Suavizado con toda la serie; NLL de reconstrucción y ELBO no son log-verosimilitud predictiva.',
'dt':DT, 'steps':STEPS, 'kappa':KAPPA, 'theta':THETA, 'sigma':SIGMA,
'training_series':train_n, 'data_seed':DATA_SEED, 'test_seed':TEST_SEED,
'train_seed':TRAIN_SEED, 'eval_seed':EVAL_SEED, 'device':str(DEVICE),
'torch':torch.__version__, 'iterations':iterations, 'training':progress,
'prior_learned':{'kappa':float(kappa.detach()), 'theta':float(theta.detach()), 'sigma':float(sigma.detach()),
'correction_at_minus2_minus1_0_1_2':model.prior_correction(torch.tensor([-2.,-1.,0.,1.,2.],device=DEVICE)).detach().cpu().tolist()},
'prior_initial':{'kappa':.6, 'theta':.1, 'sigma':.6},
'heldout':result, 'laws':laws, 'examples':examples}
directory = Path(os.environ.get('ORYON_OUTPUT_DIR', '.'))
directory.mkdir(parents=True, exist_ok=True)
path = directory / 'latent_volatility.json'
path.write_text(json.dumps(output, ensure_ascii=False, indent=2), encoding='utf-8')
print('evaluación reservada:', result, flush=True)
print('parámetros aprendidos:', output['prior_learned'], flush=True)
print('leyes: h solo se conoce en este simulador; muestra reservada:', test_n,
'trayectorias generadas por cada prior:', law_size, flush=True)
print('momentos de prueba, prior aprendido y prior inicial:', laws, flush=True)
print('guardado:', path, flush=True)
del model, opt
if DEVICE.type == 'cuda': torch.cuda.empty_cache()
if __name__ == '__main__':
main()npm run lab and open the connection link.Measuring gradients with common noise
The next experiment uses the same reconstructible Brownian tree for both methods. It compares forward output and gradients of parameters and initial state. It measures additional peak CUDA memory after loading each model, with synchronization and warm-up; on CPU it leaves memory missing. The direct gradient is that of the Euler program, while the adjoint discretizes another equation: fixed-step discrepancy does not prove an implementation error.
"""Gradientes de Euler y adjunto estocástico con browniano reconstruible.
Instala torch y torchsde==0.2.6; activa CUDA si está disponible.
La diferencia frente al gradiente discreto es error de discretización, no una
medida de la calidad estadística del modelo ni garantía de igualdad exacta.
"""
import gc
import json
import os
import platform
import time
from pathlib import Path
import torch
import torchsde
torch.set_num_threads(1)
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
WIDTH, BATCH, DIM, SEED, ENTROPY = 48, 96, 8, 2631, 6317
class Model(torch.nn.Module):
sde_type = 'ito'
noise_type = 'diagonal'
def __init__(self):
super().__init__()
self.drift = torch.nn.Sequential(torch.nn.Linear(DIM, WIDTH), torch.nn.Tanh(),
torch.nn.Linear(WIDTH, DIM), torch.nn.Tanh())
self.volatility = torch.nn.Sequential(torch.nn.Linear(DIM, WIDTH), torch.nn.Tanh(),
torch.nn.Linear(WIDTH, DIM))
def f(self, t, y):
return self.drift(y) - .4 * y
def g(self, t, y):
return .1 + .3 * torch.sigmoid(self.volatility(y))
def brownian():
# Árbol por puntos medios para que los intervalos consultados durante
# la ida y la vuelta correspondan a la misma realización, aun con distinto orden.
return torchsde.BrownianInterval(t0=0., t1=1., size=(BATCH, DIM), device=DEVICE,
entropy=ENTROPY, halfway_tree=True, tol=1e-9)
def sync():
if DEVICE.type == 'cuda':
torch.cuda.synchronize()
def run(method, steps, initial, weights):
model = Model().to(DEVICE)
model.load_state_dict(weights)
model.zero_grad(set_to_none=True)
y0 = initial.clone().detach().requires_grad_(True)
ts = torch.tensor([0., 1.], device=DEVICE)
bm = brownian()
gc.collect()
if DEVICE.type == 'cuda':
torch.cuda.empty_cache()
sync()
baseline = torch.cuda.memory_allocated()
torch.cuda.reset_peak_memory_stats()
else:
baseline = None
sync()
start = time.perf_counter()
solver = torchsde.sdeint if method == 'directo' else torchsde.sdeint_adjoint
kwargs = dict(bm=bm, method='euler', dt=1. / steps, adaptive=False)
if method == 'adjunto':
kwargs['adjoint_method'] = 'euler'
result = solver(model, y0, ts, **kwargs)
objective = result[-1].square().mean()
objective.backward()
sync()
seconds = time.perf_counter() - start
peak = (torch.cuda.max_memory_allocated() - baseline) / 2**20 if baseline is not None else None
gradient = torch.cat([p.grad.detach().reshape(-1) for p in model.parameters()]).cpu()
initial_gradient = y0.grad.detach().cpu()
final = result[-1].detach().cpu()
value = float(objective.detach().cpu())
del result, objective, model, y0, bm
gc.collect()
if DEVICE.type == 'cuda': torch.cuda.empty_cache()
return {'seconds': seconds, 'peak_extra_mib': peak, 'gradient': gradient,
'initial_gradient': initial_gradient, 'final': final, 'loss': value}
def check_finite_difference(initial, weights):
# Elige el mayor gradiente del primer peso para evitar división por un valor
# casi nulo. Se usa exactamente el mismo browniano en ambas perturbaciones.
steps, epsilon = 32, 1e-3
direct = run('directo', steps, initial, weights)
size = DIM * WIDTH
index = int(torch.argmax(torch.abs(direct['gradient'][:size])))
grad = float(direct['gradient'][index])
losses = []
for sign in (-1, 1):
model = Model().to(DEVICE)
model.load_state_dict(weights)
with torch.no_grad():
model.drift[0].weight.view(-1)[index] += sign * epsilon
t = torch.tensor([0., 1.], device=DEVICE)
result = torchsde.sdeint(model, initial, t, bm=brownian(), method='euler',
dt=1./steps, adaptive=False)
losses.append(float(result[-1].square().mean().cpu()))
del model, result
central = (losses[1] - losses[0]) / (2 * epsilon)
relative = abs(central - grad) / max(abs(grad), 1e-12)
assert relative < .01
return {'steps':steps, 'parameter':'drift.0.weight', 'flat_index':index,
'epsilon':epsilon, 'direct_gradient':grad, 'central_difference':central,
'relative_error':relative}
def main():
short = os.environ.get('ORYON_SHORT') == '1'
steps_list = [16, 32, 64, 128] if short else [32, 64, 128, 256, 512]
repeats = 2 if short else 3
torch.manual_seed(SEED)
model = Model().to(DEVICE)
weights = {k: v.detach().clone() for k, v in model.state_dict().items()}
initial = torch.linspace(-1, 1, BATCH * DIM, device=DEVICE).reshape(BATCH, DIM)
del model
# Calentamiento de ambos métodos fuera de la medición.
for method in ('directo', 'adjunto'):
run(method, 8, initial, weights)
rows = []
for steps in steps_list:
for rep in range(repeats):
direct = run('directo', steps, initial, weights)
adjoint = run('adjunto', steps, initial, weights)
forward_error = float(torch.max(torch.abs(direct['final'] - adjoint['final'])))
assert forward_error < 1e-6
denom = float(torch.linalg.vector_norm(direct['gradient']))
assert denom > 1e-12
relative = float(torch.linalg.vector_norm(direct['gradient'] - adjoint['gradient'])) / denom
y0_denom = float(torch.linalg.vector_norm(direct['initial_gradient']))
y0_error = float(torch.linalg.vector_norm(direct['initial_gradient'] - adjoint['initial_gradient'])) / y0_denom
row = {'steps': steps, 'rep': rep, 'dt': 1 / steps, 'loss_direct': direct['loss'],
'loss_adjoint': adjoint['loss'], 'max_forward_error': forward_error,
'relative_gradient_error': relative, 'relative_y0_gradient_error': y0_error,
'direct_seconds': direct['seconds'], 'adjoint_seconds': adjoint['seconds'],
'direct_peak_extra_mib': direct['peak_extra_mib'],
'adjoint_peak_extra_mib': adjoint['peak_extra_mib']}
rows.append(row)
print(json.dumps(row, ensure_ascii=False), flush=True)
finite_difference = check_finite_difference(initial, weights)
print('Diferencia finita emparejada:', finite_difference, flush=True)
output = {'description': 'Itô diagonal, Euler directo y adjunto Euler; browniano reconstruible compartido por entropía',
'torch': torch.__version__, 'torchsde': torchsde.__version__, 'python': platform.python_version(),
'device': str(DEVICE), 'gpu': torch.cuda.get_device_name(0) if DEVICE.type == 'cuda' else None,
'seed': SEED, 'brownian_entropy': ENTROPY, 'batch': BATCH, 'state_dimension': DIM,
'hidden_width': WIDTH, 'time_horizon': 1., 'output_times': [0., 1.],
'short': short, 'finite_difference': finite_difference, 'rows': rows}
directory = Path(os.environ.get('ORYON_OUTPUT_DIR', '.'))
directory.mkdir(parents=True, exist_ok=True)
output_path = directory / 'adjoint_comparison.json'
output_path.write_text(json.dumps(output, ensure_ascii=False, indent=2), encoding='utf-8')
print('Guardado:', output_path, flush=True)
if __name__ == '__main__':
main()npm run lab and open the connection link.The following cells calculate polygonal signatures without signature libraries. They generate independent paths before splitting training and test and distinguish Brownian from fractional Brownian motion with the stated parameters. Normalization uses the complete path and is valid for classifying an already observed path, not forecasting its future. The obtained accuracy belongs to this particular simulation; compare it with classical statistical features and do not interpret it as a universal guarantee.
The test contains a fixed number of paths per class. Printed Wilson intervals describe overall accuracy conditional on the trained classifier; they are approximate and do not offer exact binomial coverage if accuracy differs across classes. Since methods share test paths, their differences must be analyzed in pairs.
import numpy as np
def signature3(paths):
"""Firma poligonal por Chen. Entrada: (trayectorias, nodos, dimensiones)."""
paths = np.asarray(paths, dtype=float)
if paths.ndim != 3 or paths.shape[1] < 2 or not np.isfinite(paths).all():
raise ValueError('Se requiere un lote finito con al menos dos nodos')
m, _, d = paths.shape
s1 = np.zeros((m, d))
s2 = np.zeros((m, d, d))
s3 = np.zeros((m, d, d, d))
for dx in np.diff(paths, axis=1).transpose(1, 0, 2):
dx2 = np.einsum('bi,bj->bij', dx, dx)
dx3 = np.einsum('bi,bj,bk->bijk', dx, dx, dx)
s3 = s3 + np.einsum('bij,bk->bijk', s2, dx) + .5*np.einsum('bi,bjk->bijk', s1, dx2) + dx3/6
s2 = s2 + np.einsum('bi,bj->bij', s1, dx) + dx2/2
s1 = s1 + dx
return s1, s2, s3
# La concatenación de dos tramos a y b incluye el término temporal a tensor b.
a, b = np.array([2., -1.]), np.array([1., 3.])
path = np.array([[[0., 0.], a, a+b]])
s1, s2, s3 = signature3(path)
theory = np.outer(a,a)/2 + np.outer(a,b) + np.outer(b,b)/2
assert np.allclose(s1[0], a+b) and np.allclose(s2[0], theory)
reverse = signature3(path[:, ::-1])
assert np.allclose(reverse[0], -s1) and np.allclose(reverse[1], s2.transpose(0,2,1))
# Insertar una parada y puntos interiores de cada segmento no altera la firma.
fine = np.array([[[0.,0.], a/2, a, a, a+b/3, a+b]])
for coarse_level, fine_level in zip((s1,s2,s3),signature3(fine)):
assert np.allclose(coarse_level, fine_level)
area = (s2[0,0,1] - s2[0,1,0])/2
print('Chen: nivel 1, nivel 2 y área:', s1[0], s2[0], area)
print('Dimensión para d=2 hasta nivel 3, incluido nivel cero:', 1+2+4+8)def fractional_increments(hurst, count, steps, rng):
"""Incrementos de fBm en [0,1] por factorización exacta de su covarianza."""
if not 0 < hurst < 1:
raise ValueError('H debe pertenecer a (0,1)')
k = np.arange(steps, dtype=float)
covariance = .5*((k+1)**(2*hurst) - 2*k**(2*hurst) + np.abs(k-1)**(2*hurst)) / steps**(2*hurst)
matrix = covariance[np.abs(np.arange(steps)[:,None]-np.arange(steps)[None,:])]
factor = np.linalg.cholesky(matrix)
return rng.normal(size=(count,steps)) @ factor.T
def augment_lead_lag(increments):
"""Tiempo y copia adelantada/retrasada; el tiempo avanza con la copia adelantada."""
increments = np.asarray(increments, dtype=float)
count, steps = increments.shape
x = np.column_stack([np.zeros(count), np.cumsum(increments, axis=1)])
path = np.zeros((count, 2*steps+1, 3))
path[:,1::2,0] = np.arange(1,steps+1)/steps
path[:,2::2,0] = np.arange(1,steps+1)/steps
path[:,1::2,1], path[:,1::2,2] = x[:,1:], x[:,:-1]
path[:,2::2,1], path[:,2::2,2] = x[:,1:], x[:,1:]
return path
# Cada trayectoria se normaliza por su propia norma de incrementos. La clase ya
# no puede adivinarse comparando solo variación cuadrática o amplitud global.
rng = np.random.default_rng(3131)
steps, per_class = 48, 96
brownian = fractional_increments(.5, per_class, steps, rng)
rough = fractional_increments(.25, per_class, steps, rng)
increments = np.concatenate([brownian, rough])
increments /= np.sqrt(np.mean(increments**2, axis=1, keepdims=True))
labels = np.r_[np.zeros(per_class,dtype=int), np.ones(per_class,dtype=int)]
paths = augment_lead_lag(increments)
level1, level2, level3 = signature3(paths)
features = np.column_stack([level1, level2.reshape(len(paths),-1), level3.reshape(len(paths),-1)])
assert features.shape == (2*per_class, 3+9+27) and np.isfinite(features).all()
# El área en el plano adelantado/retrasado es la mitad de la suma de cuadrados.
lead_lag_area = (level2[:,1,2] - level2[:,2,1])/2
assert np.allclose(lead_lag_area, np.sum(increments**2,axis=1)/2)
print('Trayectorias y dimensiones de firmas:', len(paths), features.shape[1])
print('Área lead-lag (primera) y semisuma de incrementos al cuadrado:', lead_lag_area[0], np.sum(increments[0]**2)/2)def lag_correlation(increments, lag):
left, right = increments[:,:-lag], increments[:,lag:]
denom = np.sqrt(np.sum(left**2,axis=1)*np.sum(right**2,axis=1))
return np.sum(left*right,axis=1)/denom
# Los mismos caminos se usan por pareja de métodos y cada test queda íntegramente fuera.
classic = np.column_stack([lag_correlation(increments,1), lag_correlation(increments,2),
np.mean(np.abs(increments),axis=1),
np.ptp(np.column_stack([np.zeros(len(increments)),np.cumsum(increments,axis=1)]),axis=1)])
train = np.r_[np.arange(64), per_class+np.arange(64)]
test = np.r_[np.arange(64,per_class), per_class+np.arange(64,per_class)]
assert not np.intersect1d(train,test).size
def ridge_classifier(x, y, train, test, penalty=1.):
# Centrado y escala se estiman exclusivamente en entrenamiento.
mean = x[train].mean(axis=0)
scale = x[train].std(axis=0)
scale = np.where(scale > 1e-10, scale, 1.)
z = (x-mean)/scale
design = np.column_stack([np.ones(len(z)),z])
reg = penalty*np.eye(design.shape[1]); reg[0,0] = 0
weights = np.linalg.solve(design[train].T@design[train]+reg, design[train].T@(2*y[train]-1))
prediction = (design[test]@weights >= 0).astype(int)
return prediction, z
def wilson(successes,n):
p=successes/n; z=1.959963984540054
center=(p+z*z/(2*n))/(1+z*z/n)
half=z*np.sqrt(p*(1-p)/n+z*z/(4*n*n))/(1+z*z/n)
return float(center-half),float(center+half)
for name,x in [('firmas hasta nivel 3',features),('estadísticos de incrementos',classic)]:
predicted,z = ridge_classifier(x,labels,train,test)
correct=int(np.sum(predicted==labels[test]))
print(name,'aciertos:',correct,'/',len(test),'exactitud:',correct/len(test),
'intervalo Wilson 95 %:',wilson(correct,len(test)))
# El producto interno de firmas finitas define un núcleo semidefinido positivo.
z=(features-features[train].mean(axis=0))/np.where(features[train].std(axis=0)>1e-10,features[train].std(axis=0),1.)
gram=z[train[:8]]@z[train[:8]].T
minimum=np.linalg.eigvalsh(gram).min()
assert minimum > -1e-8
print('Mínimo autovalor del Gram de 8 firmas:',minimum)
print('El intervalo es condicional al clasificador y al reparto de entrenamiento; los dos métodos comparten test.')Connections and open questions
Generative diffusion SDEs learn dynamics related to diffusion SDEs, but training objectives and time direction depend on the particular construction. In finance, rough volatility motivates processes with temporal dependence that a low-dimensional Markov SDE may not capture without state augmentation.
Research question: with equal budget and temporal out-of-sample data, how much does a memory representation improve over a Markov SDE in reproducing volatility autocorrelation and scenario coverage? Fix test data, uncertainty and metrics in advance; identify which aspect of the law remains unchecked.
Exercises
Step 1 of 3. What follows from applying Jensen to the joint-law-to-Q ratio?
Step 1 of 3. What is the concatenation's first level?
import numpy as np
def signature_level2(path):
pass