Carry RNN state through padding with a mask
Why it matters Batched RNN inference in speech and text models uses masks so padded batches give the same answers as unpadded ones.
When a batch is padded, padded steps must not change the hidden state. Masking the update lets one loop handle left or right padding.
Write masked_rnn(x, mask, W, U, b). x is (B, T, d), mask is (B, T) of 0/1 (1 = real token), W (d, h), U (h, h), b (h,), start h = 0. At each step compute h_new = tanh(x_t @ W + h @ U + b), then h = m * h_new + (1 - m) * h with m = mask[:, t] as a column. The output at step t is h_new * m (zeros at padded steps). Return (outputs (B, T, h), final h (B, h)).
def masked_rnn(x, mask, W, U, b)Example
x = [[[1], [5]]], mask = [[1, 0]], W = [[1]], U = [[1]], b = [0] gives outputs [[[0.7616], [0]]] and final [[0.7616]]: the padded 5 is ignored.
Understand the idea
Sequences in a batch have different lengths, so short ones are padded with filler. The RNN still runs a step at every position, but a mask says which steps are real. At filler steps we simply keep the old memory, like pausing a stopwatch while you are not running.
Tiny example: one sequence [1, 5] where the 5 is padding. Step 0: h = tanh(1) = 0.7616. Step 1: the candidate tanh(5 + 0.7616) is about 1, but the mask is 0, so h stays 0.7616 and the output there is 0.
Rule: h_new = tanh(x_t W + h U + b); h = m * h_new + (1 - m) * h; out_t = m * h_new.
This works for left padding too (common in decoder-only batching), where real tokens are at the end and the state must stay 0 until they start.
Shapes and data flow
x (B,T,d), mask (B,T) -> m (B,1) per step -> h (B,h), outputs (B,T,h)
Similar problems
- Implement one step of an LSTM cellMediumPro
- Run one step of a GRU cell on a batchMediumPro
- Decode the best HMM path with ViterbiMediumPro
- Compute Bahdanau additive attentionMediumPro