LSTM gates
Quick answer
Long short-term memory (LSTM) adds a cell state alongside the hidden state. Learned gates control what to keep, what to write and what to expose. The additive cell update can preserve information more effectively than a plain recurrent transition. Examples are static Python snippets tested locally on CPU; PyTorch is required for selected examples. ByteMind execution is unverified.
Hand-computed cell update
import mathc=0.75*2+0.5*(-0.4)h=0.25*math.tanh(c)print(round(c,6),round(h,6))Expected output (locally tested): 1.3 0.215431. The forget gate retains 1.5 and the input gate writes -0.2.
How it works
In a standard LSTM without projections or peepholes, input i, forget f and output o are sigmoid gates, while candidate g uses tanh. Each is computed from the current x and previous h using its own affine transform. The cell update is c=fc_prev+ig; the exposed hidden state is h=o*tanh(c). Products are elementwise. A forget gate near 1 can preserve an existing cell value along the direct state path, while a gate near 0 erases it. This direct derivative is f if the gates are held fixed; the full recurrent gradient also includes paths through the gates. PyTorch LSTMCell stores concatenated gate rows in order i,f,g,o. nn.LSTM returns output,(h_n,c_n), not a single tensor for state. For a single-layer unidirectional network without projection, both final states have shape (1,batch,hidden_size). With variable lengths, pack padded inputs or gather valid states carefully. The examples use a deliberately controlled gate setup to verify the recurrence, not trained weights.
Verify native gate order and state
import torchcell=torch.nn.LSTMCell(1,1)with torch.no_grad(): for p in cell.parameters():p.zero_() h,c=cell(torch.zeros(1,1),(torch.zeros(1,1),torch.tensor([[2.]])))print(round(c.item(),6),round(h.item(),6))Expected output (locally tested): 1.0 0.380797. All sigmoid gates equal 0.5 and the candidate is zero.
Common mistakes
Do not mistake the cell state for the hidden state or apply sigmoid to the candidate g. Forget gates do not guarantee indefinite memory. Do not take the state after padding as the final valid state.
Practice and next steps
Compute an LSTM update with fixed gate values and verify that a zero-parameter LSTMCell halves its existing cell state.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
LSTM gates — knowledge check
Apply lstm gates to small examples and debugging scenarios.
Which gate controls retained cell memory?
Which activation is used for the candidate?
What state tuple does nn.LSTM return?
If f=0 and i=0, what is the new cell?
Does a forget gate near 1 guarantee all gradients stay large?