liveBook · Manning

GRU

As explained in Inside Deep Learning: Math, Algorithms, Models

A gated recurrent neural network architecture that updates a hidden state over sequence steps with reset and update gates.

A gated recurrent unit (GRU) is an RNN that carries one hidden state, hₜ, from step to step. Unlike an LSTM, it does not maintain a separate context state, Cₜ: its hidden state serves both roles. That makes GRU code simpler and can reduce time and memory use, though an LSTM may be more accurate for some tasks. section 6.6.2 section 6.6.3

In PyTorch, choose the interface to match how inputs arrive. `nn.GRU` takes a sequence of time steps together; `nn.GRUCell` updates a hidden state one item at a time. The cell is slower, but its stepwise interface is convenient when generating tokens or handling an output whose length is not known in advance. section 7.5.1 section 11.4.1

Next-character prediction

For an autoregressive character model, embed each input character, pass its vector and the previous hidden state through a `GRUCell`, then predict the next character from the resulting state. Repeat across the input chunk. With multiple recurrent layers, keep one hidden-state tensor per layer and pass each layer’s new state to the next. A two-layer implementation uses `ModuleList` for the cells, initializes states to zeros, and stacks the predictions across time. section 7.5.1

def step(self, x_in, h_prevs=None): 
    """ 
    x_in: the input for this current time step and has shape (B) 
    if the values need to be embedded, and (B, D) if they 
    have already been embedded.

    h_prevs: a list of hidden state tensors each with shape 
    (B, self.hidden_size) for each layer in the network.
    These contain the current hidden state of the RNN layers 
    and will be updated by this call. 
    """

    if len(x_in.shape) == 1:                               #1 
        x_in = self.embd(x_in)                             #2

    if h_prevs is None:
        h_prevs = self.initHiddenStates(x_in.shape[0])

    for l in range(len(self.layers)):                      #3 
        h_prev = h_prevs[l] 
        h = self.norms[l](self.layers[l](x_in, h_prev))    #4

        h_prevs[l] = h 
        x_in = h 
    return self.pred_class(x_in)                           #5

The `step` implementation embeds a token if needed, updates each layer’s hidden state with its `GRUCell`, and returns next-token prediction scores. section 7.5.1

Sequence-to-sequence encoder and decoder

When the entire input is available, a bidirectional `nn.GRU` can encode it in one pass. A decoder generating one token at a time instead uses `nn.GRUCell` and tracks its layers’ hidden states explicitly. It starts from the encoder’s final hidden state, which supplies input context and connects the decoder’s learning signal back to the encoder. Attention can then combine the decoder state with relevant encoder states before the next-word prediction. section 11.4.1 section 11.3

class Seq2SeqAttention(nn.Module):

    def __init__(self, num_embeddings, embd_size, hidden_size, 
     padding_idx=None, layers=1, max_decode_length=20):
        super(Seq2SeqAttention, self).__init__() 
        self.padding_idx = padding_idx 
        self.hidden_size = hidden_size 
        self.embd = nn.Embedding(num_embeddings, embd_size, 
         padding_idx=padding_idx) 
        self.encode_layers = nn.GRU(input_size= 
         embd_size, hidden_size=hidden_size//2, #1
         num_layers=layers, bidirectional=True) 
        self.decode_layers = nn.ModuleList([      #2 
         nn.GRUCell(embd_size, hidden_size)] +
         [nn.GRUCell(hidden_size, hidden_size)
         for i in range(layers-1)])
        self.score_net = DotScore(hidden_size) 
        self.predict_word = nn.Sequential(        #3 
            nn.Linear(2*hidden_size, hidden_size), 
            nn.LeakyReLU(), 
            nn.LayerNorm(hidden_size), 
            nn.Linear(hidden_size, hidden_size), 
            nn.LeakyReLU(), 
            nn.LayerNorm(hidden_size), 
            nn.Linear(hidden_size, num_embeddings) 
        ) 
        self.max_decode_length = max_decode_length 
        self.apply_attn = ApplyAttention()
#1 We set the hidden size to half the intended length because we make the encoder bidirectional. That means we get two hidden state representations, which we concatenate together, giving us the desired size.
#2 The decoder is uni-directional, and we need to use GRUCells so that we can do the decoding one step at a time.
#3 predict_word is a small, fully connected network that converts the result of the attention mechanism and the local context into a prediction of the next word.

The constructor places a bidirectional `nn.GRU` in the encoder and a `ModuleList` of `nn.GRUCell` layers in the decoder. section 11.4.1

GRU is a practical alternative to LSTM, not a guaranteed improvement. For a given task, compare their accuracy and the time needed to reach it while varying layer counts and hidden sizes. This implementation-focused treatment uses PyTorch’s GRU modules rather than deriving the GRU’s gate equations. section 6.7 section 7.5.1 section 6.6.3

How Inside Deep Learning: Math, Algorithms, Models covers it

How deep it goes
Works through PyTorch GRU and GRUCell integration and manual hidden-state updates, but does not derive GRU gate equations.
Examples
Builds a character-level predictor and an attention-based encoder-decoder, then proposes comparing GRU and LSTM training times.
What it assumes
Assumes RNN hidden states and token embeddings while showing how to initialize and update states across GRUCell layers.
What you can do after
Apply it via PyTorch nn.GRU and nn.GRUCell to assemble sequence models and choose between whole-sequence and stepwise processing.
How it connects
Connects GRUs to LSTMs, autoregressive modeling, sequence-to-sequence learning, bidirectional RNNs, and attention.

Also explained in

Compare how 7 books explain GRU →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Inside Deep Learning: Math, Algorithms, Models. The section links point to the parts of the book it draws on.