Browse documentation
aner.nn · Reference

Recurrent neural networks

Train RNN, LSTM and GRU models, carry explicit streaming state, mask padded sequences and use DeepAR, ConvLSTM, AWD LSTM and stabilized xLSTM profiles.

Implemented

Carry explicit state through time

LSTM: two state paths through time

At timestep t, the cell receives input x_t, previous hidden state h_(t−1) and previous cell memory c_(t−1). Forget and input gates update cell memory; the output gate exposes hidden state h_t. Both hidden and cell state pass to the next timestep. Reusing a cell shares parameters, not observations from another series.

LSTM: two state paths through timeAt timestep t, the cell receives input x_t, previous hidden state h_(t−1) and previous cell memory c_(t−1). Forget and input gates update cell memory; the output gate exposes hidden state h_t. Both hidden and cell state pass to the next timestep. Reusing a cell shares parameters, not observations from another series.Same learned cell at every timestepc_(t−1)forget ×+c_tinput × candidateoutput gateh_th_(t−1)x_t · current inputh_t and c_t continue to t+1.Reset at a new stream boundary.

Follow the arrows in the diagram. On a narrow screen, scroll inside the figure or read its caption.

A complete research workflow

1 / Separate the observations

Split chronologically and fit scaling on the training period. Build windows within each partition; preserve sequence identity.

2 / Fit an immutable snapshot

Keep the starting model. Declare optimizer, clip norm, weight decay and shuffle policy. A deliberate new phase uses reset_optimizer().

3 / Evaluate held out data

Inspect evaluate(...).loss(), samples() and observations(); classification also reports accuracy(). This detached result does not advance optimizer state.

Use probabilities() for classification and predict() for the configured task. Carry hidden/cell state only across chunks of the same stream. reset_optimizer() also clears retained recurrent memory; reset_state() changes that memory without starting a new optimizer phase.

Read the recurrent parameter reference for every model/configuration argument, its actual default, accepted shape/range, effect and persistence contract. Neural networks and the model directory connect the technique specific guides.

Implemented CPU APIs in Aner 0.0.4 or newer. Use the matching editor integration. The 0.0.4 research packages include native CPU APIs, and supported Mac packages include Metal/MPS. CUDA and MPI/NCCL source backends require separately prepared compatible runtimes; the current Linux and Windows release packages do not include CUDA or MPI/NCCL. Follow each device, precision and operation contract before choosing an accelerator.

Build a model, fit it and retain the returned snapshot:

aner
import aner.nn
import aner.tensor

let x = tensor.reshape(nn.random(8, 6, seed: 2026, scale: 0.5), List(8, 6, 1))
let y = nn.zeros(8, 1)
let model = nn.lstm(inputs: 1, hidden: 8, outputs: 1,
    layers: 1, bidirectional: false, seed: 42)
    .on(device: "cpu", precision: "Float32")
let fitted = model.fit(x, y, epochs: 3, batch: 4, rate: 0.001,
    seed: 91, optimizer: "adam", clip_norm: 1.0,
    weight_decay: 0.0, shuffle: true)
print(fitted.predict(x).rows())

This complete synthetic example prints 8; it demonstrates API mechanics, not forecasting quality.

Here x is a preprocessed Tensor [batch,time,1] and y is [batch,1]. See the complete runnable synthetic example. The same signatures work with nn.rnn and nn.gru. Each builder takes inputs, hidden, outputs: 1, layers: 1, bidirectional: false and seed: 42.

Choose the objective and layout

TaskInputTargetPrediction
regression (default)[B,T,F][B,O][B,O]
classification[B,T,F]class IDs [B,1] or one hot [B,O]class IDs [B,1]
sequence_regression[B,T,F][B,T,O][B,T,O]
sequence_classification[B,T,F]class IDs [B,T,1] or one hot [B,T,O]class IDs [B,T,1]

Select with .task("sequence_classification"). .logits(x) retains raw class scores; .predict(x) applies the declared inference contract. Sequence lengths are exact integers in 1..T, with right padding. Supply lengths: List(...) to fit, predict, logits or step; padded positions do not contribute to the loss or final state. Do not encode missing data as an unlabelled zero.

Use chronological train/validation/test splits for forecasting. Fit scalers and vocabulary on training data only, keep series identity explicit and avoid future information in covariates. The Tensor API does not infer temporal splits or attach protected Dataset roles to arbitrary tensors. Evaluate on held out time periods using the same transforms and inverse scale predictions before reporting errors.

Streaming and truncated training

aner
let state = model.initial_state(batch: 8)
let first = model.step(chunk_a, state)
let second = model.step(chunk_b, first.state())
let values = second.values()

step returns RecurrentOutput, with task shaped values and detached RecurrentState. Each call ends the gradient graph. States belong to the model geometry, placement, dtype and batch ordering. Reset when a stream ends; never carry one series into another. Bidirectional models require future context and cannot be used as causal streaming models.

aner
let fitted = model.fit_chunk(chunk_a, target_a, state, clip_norm: 1.0)
let continued = fitted.fit_chunk(chunk_b, target_b, fitted.state())

fit_chunk performs one update on one ordered batch and retains detached final state. This is an explicit truncated backpropagation boundary. Choose chunk lengths that fit the activation budget; it does not retain gradients into earlier chunks. See streaming example.

Advanced architectures

FactoryUseImplementation scope
nn.deepar(inputs, hidden, outputs: 1, layers: 1, seed: 42)Probabilistic autoregressive forecastsLSTM Gaussian location/positive-scale head; explicit causal target lags, observed indicators and known covariates; masked likelihood and trajectory sampling
nn.convlstm(channels, hidden, outputs: 1, kernel: 3, seed: 42)Spatial sequencesActual input/recurrent convolutions, channel shared peepholes and per pixel output head; [B,T,C,H,W]
nn.awd_lstm(vocabulary, embedding, hidden, layers: 3, seed: 42)Vocabulary sequence modellingTied embeddings/output weights, locked and embedding dropout, recurrent weight DropConnect; paper optimizer schedules are separate
nn.xlstm(inputs, hidden, outputs: 1, variant: "slstm", layers: 1, seed: 42)Stabilized recurrent memoryScalar slstm and matrix mlstm cells with exponential gate stabilization; one memory head, documented block profile

The implementation order is the standard cells, DeepAR, ConvLSTM, AWD LSTM, then xLSTM. These advanced profiles implement their declared mechanisms; they are not claims of matching published benchmark quality or reproducing a complete research training recipe.

DeepAR helpers construct causal features and masked targets:

aner
let inputs = nn.deepar_inputs(values, observed)
let targets = nn.deepar_targets(values, observed)
let model = nn.deepar(inputs: 2, hidden: 32)
let fitted = model.fit(inputs, targets, epochs: 10)
let draws = fitted.forecast(inputs, last_target, horizon: 12, samples: 100)

values and binary observed are [B,T,O]; unobserved values are zero filled by the packer. With known covariates [B,T,C], use nn.deepar_inputs(values, observed, covariates) and declare inputs: 2*O+C. The current target never enters its own feature row. last_target is [B,O]; forecast trajectories are [B,samples,horizon,O]. For known future covariates, pass their [B,horizon,C] Tensor in place of horizon. Each trajectory feeds its own sampled value into the next step. Negative Gaussian NLL values can be valid. See forecast example.

Performance and parallel execution

On CUDA, standard RNN/LSTM/GRU layers automatically use native CUDA cell kernels and cuBLAS through one autodiff operation per layer/direction. Input projections combine all timesteps; saved activations and layer gradients stay on the GPU. The recurrent state still advances sequentially through time. The user facing builders, fit, step, valid lengths and state layouts are unchanged.

CPU and Metal/MPS use the reference Tensor route. DeepAR's standard LSTM backbone also uses the CUDA layer; its probabilistic head and forecasting behavior are unchanged. The other advanced families keep their declared implementations. This is a native CUDA/cuBLAS path, without cuDNN or CUDA training graph capture.

.on("cpu", precision: "Float64"), .on("mps") and .on("cuda") select supported native backends. Metal/MPS uses Float32. CPU/CUDA support Float32 and Float64. Intel and AMD accelerator providers remain reserved, without a validated execution path; use CPU on those systems. Explicit unsupported placement or precision fails.

aner
import aner.parallel

let fast = model.performance(amp: "fp16").on("cuda")
let fitted = fast.fit(x, y, batch: 64, execution: parallel.local())

Strict CUDA supports Float32 and Float64. Mixed profiles require Float32 storage: amp: "fp16", amp: "bf16", or matmul: "tf32". FP32 master weights, optimizer moments, gradients and outputs retain FP32 storage; only eligible GEMM computation changes. FP16 requires supported Tensor Core hardware; BF16 and TF32 require Ampere or newer. .performance(matmul: "tf32") explicitly permits TF32. FP16 dynamic loss scaling skips the whole update on overflow; inspect .attempts(), .skipped_updates() and .loss_scale(). Small or sequential workloads can be slower under AMP; measure the actual workload after warm up and synchronization.

For diagnosis, run the same source with ANER_RNN_FUSED=0 to select the reference Tensor route on the same device. Unset the variable, or use ANER_RNN_FUSED=1, for automatic CUDA selection. CPU/MPS continue using their reference implementation. Layer fusion removes many per timestep graph nodes; .budget(...) still checks saved states/gates and temporary buffers across the full reachable graph, so it does not make sequence memory unbounded. Measure the complete workload; no fixed speedup is promised.

fit(..., execution: context) reuses aner.parallel sessions for sample weighted gradient reduction. Local CPU replicas and configured MPI/NCCL contexts share the same optimizer contract. Configure one process per selected physical GPU for distributed GPU training. All ranks must agree on architecture, input data, objective, precision policy and collective order. Global batches can have uneven shards; losses and gradients use valid observation counts. No automatic server discovery or credential management occurs. See parallel computing and CNN compute and collective policy.

Global norm clipping defaults to clip_norm: 1.0; weight_decay: 0.0, optimizer: "adam", shuffle: true, rate: 0.001, batch: 32, epochs: 1 and seed: 42 are explicit fit defaults. Select "sgd" when needed. Weight decay is decoupled: each successful step subtracts rate * weight_decay * previous_weight from named weights and embeddings, excluding biases and normalization gains. Use .budget(tensor_elements, graph_elements) to bound allocations, including unrolled activation graphs. Parameter count does not estimate all training memory; sequence length, spatial geometry and xLSTM matrix memory matter.

Save, resume and inspect

aner
fitted.save("sequence.anerrnn")
let restored = nn.load_recurrent("sequence.anerrnn").on("auto")
let resumed = restored.fit(x, y, epochs: 2)

Use a new checkpoint path. Checkpoints retain architecture, parameters, optimizer moments, update counters, random continuation and explicit retained state. Resume with compatible data, ordering and preprocessing. The checkpoint format and parameter/carry layouts remain compatible with the CUDA layer. The diagnostic route is selected by the process environment, not saved in the checkpoint. Changing the route can change floating point evaluation and reduction order; use a consistent route/profile/runtime for exact replay. A checkpoint cannot restore unrecorded preprocessing or guarantee bit identical results across routes or accelerator architectures.

Development mode records bounded diagrams and training observations:

aner
import aner.dev

dev.capture("Recurrent architecture", model)

Run aner examples/recurrent_basics.aner --dev reports/recurrent-first using a fresh report directory. Run the same source with --prod for normal execution. Production uses the same numerical kernels, shape checks, seeds and resource limits. .summary(), .diagram() and .performance_summary() inspect declarations without training. Captures retain immutable snapshots and do not replay training.

Primary architecture sources: LSTM, GRU, DeepAR, ConvLSTM, AWD LSTM, xLSTM. The canonical native reference documents equations, deviations and validation limits.

Measured CUDA training

On 21 October 2026, an NVIDIA L40 with CUDA 12.4.1 ran paired reference and fused implementations from the same native executable. Each measurement is one complete strict Float32 Adam fit update, including input transfer, backward and optimizer work, with explicit synchronization. At least two finite warmups precede nine measured updates per implementation; execution order alternates. CUDA API profiling is disabled for these timings.

FixtureCellReference median msFused median msObserved speedup
SmallRNN37.4313.36511.12×
SmallLSTM134.3693.36939.88×
SmallGRU122.8173.43135.79×
LargeRNN214.71322.7049.46×
LargeLSTM760.00623.79531.94×
LargeGRU673.50023.62028.51×

Small uses [8,32,4], hidden size 32 and output size 2. Large uses [32,64,32], hidden size 128 and output size 2. Strict, FP16, BF16 and TF32 profiles passed correctness and paired timing checks. On these fixtures, strict fused computation was faster than the mixed profiles; AMP remains an explicit workload choice. These synthetic workloads on one GPU do not establish peak throughput, model quality, cross process variation or distributed scaling. The host exposes one GPU, so physical multiple GPU training remains unvalidated for this fused path campaign; one rank MPI/NCCL transport checks passed.

Aner documentation · Reference and guides