Autograd node for the single-layer LSTM with BPTT backward.
Implements the standard Hochreiter & Schmidhuber (1997) LSTM gating equations:
where is the logistic sigmoid, is the element-wise
(Hadamard) product, and the four gates 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 time steps in reverse, accumulating the
gradient contributions through both the cell-state path
and the gate path
, then maps cell-state
gradients back through the sigmoid / tanh derivatives to give
per-time-step weight gradients ,
, ,
. 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(T, B, input_size) retained for the backward pass.saved_ h0Storage(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(T, B, 4H) in [i, f, g, o] order, written by the training-mode forward.cells_ allStoragec_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.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.dtypeDtypeapply(). Default: Dtype::F32.deviceDeviceNotes
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
to , 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
1forward
→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(T, B, input_size). The batch_first flag in opts is forwarded but the Python LSTM wrapper always passes sequence-first.h0TensorImplPtr(1, B, H_rec) where H_rec == proj_size if projection is enabled, else hidden_size.c0TensorImplPtr(1, B, hidden_size).weightsstd::vector<TensorImplPtr>{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.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
InvalidArgumentopts.seq_len < 1 (the reference refuses an empty sequence), or the weight count is not 4 (5 projected).DeviceMismatchh0, c0 or a weight is not on the input's device.DtypeMismatchShapeMismatchopts.NotImplementedErrornum_layers != 1, bidirectional or batch_first.Virtual methods
3Free the saved forward state once a pass that did not retain the graph has run.
Refuse backward when input, h0 or a weight was written in place since forward: BPTT reads the values they held then.
Raises
VersionMismatchMethods
6Park 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
LucidErrorinput_nr names no output of this node.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
NotImplementedErrorThe 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.
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).
Return the node name for debug / graph visualisation.
Returns
std::string_viewThe literal "LstmBackward".