Skip to content
class

LstmBackward

extendsNodeGraphBarrier
LstmBackward

Autograd node for the single-layer LSTM with BPTT backward.

Implements the standard Hochreiter & Schmidhuber (1997) LSTM gating equations:

it=σ(Wii xt+bii+Whi ht−1+bhi)ft=σ(Wif xt+bif+Whf ht−1+bhf)gt=tanh⁡(Wig xt+big+Whg ht−1+bhg)ot=σ(Wio xt+bio+Who ht−1+bho)ct=ft⊙ct−1+it⊙gtht=ot⊙tanh⁡(ct) \begin{aligned} i_t &= \sigma(W_{ii}\,x_t + b_{ii} + W_{hi}\,h_{t-1} + b_{hi}) \\ f_t &= \sigma(W_{if}\,x_t + b_{if} + W_{hf}\,h_{t-1} + b_{hf}) \\ g_t &= \tanh(W_{ig}\,x_t + b_{ig} + W_{hg}\,h_{t-1} + b_{hg}) \\ o_t &= \sigma(W_{io}\,x_t + b_{io} + W_{ho}\,h_{t-1} + b_{ho}) \\ c_t &= f_t \odot c_{t-1} + i_t \odot g_t \\ h_t &= o_t \odot \tanh(c_t) \end{aligned}

where σ\sigma is the logistic sigmoid, ⊙\odot is the element-wise (Hadamard) product, and the four gates i,f,g,oi, f, g, o are stored in that exact concatenation order along the leading axis of gates_all (i.e. gates_all[..., 0:H] is the input-gate pre-activation, gates_all[..., H:2H] the forget gate, and so on).

Inherits directly from Node rather than FuncOp because the 7-edge topology {input, h0, c0, wih, whh, bih, bhh} is built by hand: each tensor that requires a gradient gets an explicit AccumulateGrad leaf wired in forward(), and non-differentiable tensors (such as biases when has_bias=false) get a null edge. All three outputs carry this node as their grad_fn, at output slots 0 (sequence), 1 (hn) and 2 (cn). The final state is a differentiable output: an encoder's hn seeding a decoder, or the state a packed sequence carries from one run of timesteps to the next, sends its gradient back through BPTT as dh_n / dc_n. The node is therefore a barrier (is_barrier): the engine parks each output's gradient in its slot and runs the backward once, after the last arrives.

Math

The BPTT backward unrolls TT time steps in reverse, accumulating the gradient contributions through both the cell-state path ∂ct/∂ct−1=ft\partial c_t / \partial c_{t-1} = f_t and the gate path ∂ct/∂{it,ft,gt}\partial c_t / \partial \{i_t, f_t, g_t\}, then maps cell-state gradients back through the sigmoid / tanh derivatives to give per-time-step weight gradients ∂L/∂Wih\partial \mathcal{L}/\partial W_{ih}, ∂L/∂Whh\partial \mathcal{L}/\partial W_{hh}, ∂L/∂bih\partial \mathcal{L}/\partial b_{ih}, ∂L/∂bhh\partial \mathcal{L}/\partial b_{hh}. The full unrolled BLAS path lives in IBackend::lstm_backward.

References

Hochreiter & Schmidhuber, "Long Short-Term Memory" (Neural Computation 1997). Hochreiter, "Untersuchungen zu dynamischen neuronalen Netzen" (1991) for the original analysis of the vanishing-gradient problem that motivates the gating mechanism.

Attributes

saved_inputStorage
Original input sequence shaped (T, B, input_size) retained for the backward pass.
saved_h0Storage
Initial hidden state shaped (1, B, H_rec) where H_rec is proj_size if projection is enabled, otherwise hidden_size.
saved_weightsstd::vector<Storage>
{wih, whh, bih, bhh} (plus whr when projected) in that exact order. BPTT reads the matrices only — the biases' gradient is the gates' gradient summed — so the bias slots hold zero-element placeholders of the right device and dtype, not the biases: holding them would make a write into a bias after forward refused (the CPU write guard) where the reference allows it.
gates_allStorage
All pre-activation gate values shaped (T, B, 4H) in [i, f, g, o] order, written by the training-mode forward.
cells_allStorage
Cell states c_0, c_1, ..., c_T shaped (T+1, B, H); cells_all[0] is the supplied c_0 and cells_all[T] is cn. For the 16-bit dtypes both trajectories are float32: the backends compute those in float32 and only lstm_backward reads them.
optsbackend::IBackend::LstmOpts
Bundle of structural parameters propagated from forward() to apply() — input_size, hidden_size, seq_len, batch_size, has_bias, proj_size. num_layers and bidirectional are always 1 and false here; multi-layer and bidirectional configurations are composed in Python.
dtypeDtype
Element type for the gradient buffers allocated in apply(). Default: Dtype::F32.
deviceDevice
Backend device on which to allocate gradients. Default: CPU.

Notes

Backend dispatch. CPU runs Apple Accelerate-backed hand-rolled BLAS through lstm_forward_train / lstm_backward (float32 and float64 natively, the 16-bit formats through float32 — see backend/cpu/Lstm.h). GPU dispatches to the MLX backend (backend/gpu/Lstm.h). The Python wrapper in lucid.nn.modules.rnn.LSTM always invokes the engine one-layer-one-direction at a time and composes stacking, bidirectionality and inter-layer dropout itself, so this node only ever sees num_layers == 1 and bidirectional == false.

Projection variant (lstm_proj). When opts.proj_size > 0 the recurrent path applies an additional learnable projection Whr∈Rproj_size×HW_{hr} \in \mathbb{R}^{\text{proj\_size} \times H} to hth_t, so the hidden state fed to the next step has dimension proj_size. The cell state c_t is left at dimension hidden_size. This matches the LSTMP variant used in many speech-recognition stacks and reduces recurrent compute when proj_size < hidden_size.

Peephole connections are not supported — Lucid's LSTM follows the vanilla 1997 formulation without direct cell-to-gate links.

Static methods

1
static

forward

→std::vector<TensorImplPtr>
int forward(const int & input, const int & h0, const int & c0, const int & weights, const backend::IBackend::LstmOpts & opts)

Run the LSTM forward pass and return {output, hn, cn}.

Decides between inference and training paths based on GradMode::is_enabled() and whether any of input, h0, c0 or the elements of weights require a gradient. On the training path the backend's lstm_forward_train is invoked and a fresh LstmBackward node is wired with saved_input, saved_h0, saved_weights, gates_all and cells_all populated for BPTT. On the inference path the backend's lighter lstm_forward may be used (some backends route this through lstm_forward_train and discard the saved tensors).

Parameters

inputTensorImplPtr
Input sequence shaped (T, B, input_size). The batch_first flag in opts is forwarded but the Python LSTM wrapper always passes sequence-first.
h0TensorImplPtr
Initial hidden state shaped (1, B, H_rec) where H_rec == proj_size if projection is enabled, else hidden_size.
c0TensorImplPtr
Initial cell state shaped (1, B, hidden_size).
weightsstd::vector<TensorImplPtr>
Layer weights in order {W_ih, W_hh, b_ih, b_hh} (and a trailing W_hr when opts.proj_size > 0). Each gate weight is the vertically-stacked 4-gate matrix in [i, f, g, o] order — see the class docstring's Math section.
optsbackend::IBackend::LstmOpts
Structural parameters: input_size, hidden_size, seq_len, batch_size, has_bias, proj_size. Always called with num_layers == 1 and bidirectional == false; stacking is composed in Python.

Returns

std::vector<TensorImplPtr>

Three tensors {output, hn, cn} where output is shaped (T, B, H_out), hn is shaped (1, B, H_out) and cn is shaped (1, B, hidden_size). On the training path all three share this node as their grad_fn.

Raises

InvalidArgument
An operand is null, opts.seq_len < 1 (the reference refuses an empty sequence), or the weight count is not 4 (5 projected).
DeviceMismatch
h0, c0 or a weight is not on the input's device.
DtypeMismatch
The input is not floating point, or an operand's dtype differs.
ShapeMismatch
An operand's shape does not follow from opts.
NotImplementedError
num_layers != 1, bidirectional or batch_first.

Virtual methods

3
virt

release_saved

void release_saved()

Free the saved forward state once a pass that did not retain the graph has run.

virt

validate_versions

void validate_versions()

Refuse backward when input, h0 or a weight was written in place since forward: BPTT reads the values they held then.

Raises

VersionMismatch
One of them moved past the version recorded at forward.

Methods

6
fn

accumulate_barrier_grad

void accumulate_barrier_grad(int input_nr, int grad)

Park one output's gradient in its slot (0 = sequence, 1 = hn, 2 = cn). A slot reached by several paths sums them, into a copy this node owns. Slots from an earlier backward pass are dropped.

Raises

LucidError
input_nr names no output of this node.
fn

accumulate_barrier_grad_for_graph

void accumulate_barrier_grad_for_graph(int input_nr, int grad)

create_graph is not supported: BPTT runs on storages, not graph ops. Implementing the graph half of the barrier protocol makes the refusal a clear NotImplementedError at the first arriving gradient, rather than the engine summing the three outputs' gradients into one tensor (a ShapeMismatch when hn and the sequence differ in shape).

Raises

NotImplementedError
Always.
fn

apply

int apply(int grad_out)

The output sequence's gradient alone: slot 0, then the barrier flush. The engine never calls this (the node is a barrier); it keeps a direct apply meaning what it always meant.

fn

apply_barrier

→std::vector<Storage>
int apply_barrier()

Run BPTT once with every output's gradient, seeding the recurrence with dh_n / dc_n. An output the loss never reached contributes zeros.

Returns

std::vector<Storage>

Edge order {dInput, dh0, dc0, dW_ih, dW_hh, db_ih, db_hh} (plus dW_hr when projected).

fn

apply_barrier_for_graph

int apply_barrier_for_graph()
fnconst

name

→std::string_view
int name()

Return the node name for debug / graph visualisation.

Returns

std::string_view

The literal "LstmBackward".