AI Logic

Regularization

Zoneout

Updated:

An RNN unrolled over 3 time steps, comparing Dropout on the recurrent connections with Zoneout. At the top, Dropout sets the selected elements of the hidden state to 0 at each time step. At the bottom, Zoneout leaves the selected elements un-updated at each time step and carries over the value from the previous step (blue lines show the paths passed straight through from the previous step). The selected elements change from step to step

Background and Overview

Zoneout is a regularization method that, at each RNN time step, randomly selects some elements of the hidden state and keeps them at their previous values without updating them. Krueger and colleagues presented it at ICLR in 2017.

An RNN repeats the same update computation at every time step. As a result, small fluctuations in the hidden state can grow large as they are repeated. Zoneout injects noise into the hidden state during training, which produces an RNN that is robust to these fluctuations.

Injecting noise is the same as in Dropout, but instead of setting the selected elements to 0, Zoneout replaces them with their values from the previous time step. Setting an element to 0 cuts off the information it carried. Keeping the previous value passes the information straight on to the next step, and during training the gradient also travels back to earlier steps along the same path.

To use an analogy of copying notes: Dropout "leaves randomly chosen lines blank," while Zoneout "does not rewrite randomly chosen lines and copies over what was on the previous page." Leaving lines blank loses the previous content; copying it keeps it.

Zoneout can be used with any of LSTM, GRU, and simple RNNs.

Theory (The Zoneout Equations)

The explanation follows the equations in Section 3 of the original paper. ⊙\odot denotes the element-wise product.

  1. The RNN computes the ordinary update h~t\tilde{h}_t from the previous hidden state ht−1h_{t-1} and the input xtx_t. h~t=T~(ht−1,xt)\tilde{h}_t = \tilde{T}(h_{t-1}, x_t)
  2. At each time step, choose a mask dtd_t indicating, for each element of the hidden state, whether to keep its previous value. The probability zz that each element is 1 is called the zoneout probability. The mask is redrawn at every time step. dt∼Bernoulli(z)d_t \sim \mathrm{Bernoulli}(z)
  3. Elements with dt=1d_t = 1 keep their previous values, and elements with dt=0d_t = 0 are updated as usual. ht=dt⊙ht−1+(1−dt)⊙h~th_t = d_t \odot h_{t-1} + (1 - d_t) \odot \tilde{h}_t
  4. In an LSTM, the cell ctc_t and the hidden state hth_t use separate masks dtcd_t^c and dthd_t^h (probabilities zcz_c and zhz_h). The update of hth_t uses the cell value before zoneout is applied. ct=dtc⊙ct−1+(1−dtc)⊙(ft⊙ct−1+it⊙gt)c_t = d_t^c \odot c_{t-1} + (1 - d_t^c) \odot \bigl(f_t \odot c_{t-1} + i_t \odot g_t\bigr) ht=dth⊙ht−1+(1−dth)⊙(ot⊙tanh⁡(ft⊙ct−1+it⊙gt))h_t = d_t^h \odot h_{t-1} + (1 - d_t^h) \odot \Bigl(o_t \odot \tanh\bigl(f_t \odot c_{t-1} + i_t \odot g_t\bigr)\Bigr)
  5. At inference, as with Dropout, use the expected value of the noise. Instead of a mask, multiply by zz to blend the previous and new values. ht=z ht−1+(1−z) h~th_t = z\, h_{t-1} + (1 - z)\, \tilde{h}_t

By comparison, applying Dropout to the hidden state sets the selected elements to 0 (Section 3.1 of the paper).

Dropout:ht=(1−dt)⊙h~tZoneout:ht=dt⊙ht−1+(1−dt)⊙h~t\text{Dropout:}\quad h_t = (1 - d_t) \odot \tilde{h}_t \qquad\qquad \text{Zoneout:}\quad h_t = d_t \odot h_{t-1} + (1 - d_t) \odot \tilde{h}_t

The equation in step 3 can be rewritten as follows.

ht=ht−1+(1−dt)⊙(h~t−ht−1)h_t = h_{t-1} + (1 - d_t) \odot \bigl(\tilde{h}_t - h_{t-1}\bigr)

In other words, Zoneout can be viewed as Dropout applied to the "change" in the hidden state (Figure 1 of the paper). Elements whose change is dropped stay at their previous values.

Note that the equation in Section 3.1 of the paper uses dt=1d_t = 1 to mean "update," the opposite of the LSTM equations in Section 3.2. This article follows the convention of Section 3.2 (dt=1d_t = 1 keeps the previous value).

Why It Works

The paper explains Zoneout's effect with two factors.

  • Robustness to fluctuations in the hidden state: During training, part of the hidden state randomly stays at old values, so the RNN learns to "work correctly even when the hidden state is slightly off." As with Dropout, it also becomes a kind of ensemble (a pseudo-ensemble) that trains many networks with different masks while sharing weights.
  • Information and gradients propagate across time more easily: An element that keeps its previous value becomes an identity connection that passes the value straight from one time step to the next. In the paper's permuted MNIST experiment (Figure 6), an LSTM with Zoneout on the cell delivered gradients to far earlier time steps than an LSTM with Dropout at the same probability or an unregularized LSTM. This helps mitigate the vanishing gradient problem.

In an experiment in the appendix, choosing the mask only once at the start of training and fixing it (identity connections only, no noise) did worse than an unregularized LSTM. This means that noise redrawn randomly every time is essential for the regularizing effect.

Zoneout can also be viewed as a "per-unit version" of Stochastic Depth (Section 2.3 of the paper). Stochastic Depth turns an entire residual block into the identity, but doing that in an RNN would ignore the whole input at that time step. Making individual elements the identity ensures every time step of the input sequence is taken in. In the paper's character-level experiments, too, Zoneout's per-element selection did better than skipping whole time steps.

Experimental Results

Language modeling results from Table 1 of the paper (test values; character level in bits per character (BPC), word level in perplexity; lower is better for both). Character-level Penn Treebank and Text8 use a 1-layer LSTM, and word-level Penn Treebank uses a 2-layer LSTM.

MethodChar-level PTB (BPC)Word-level PTBText8 (BPC)
No regularization1.356114.51.408
Weight noise1.344—1.367
Skipping whole time steps (the Stochastic Depth idea)1.343—1.343
Recurrent Dropout (Semeniuta et al.)1.28687.01.401
Zoneout1.25277.41.336
  • Character level: The combination of cell probability zc=0.5z_c = 0.5 and hidden-state probability zh=0.05z_h = 0.05 gave the best results. For GRUs and simple RNNs as well, Zoneout with small probabilities (0.05–0.25) lowered BPC from 1.53 to 1.41 for the GRU and from 1.67 to 1.52 for the simple RNN.
  • Word level: Adding Zoneout with zc=0.25z_c = 0.25 and zh=0.025z_h = 0.025 to Zaremba et al.'s large model (with Dropout on inputs and outputs) lowered test perplexity from 78.4 to 77.4. The same table also lists 73.4 for Variational Dropout (RNN).

Error rates on permuted MNIST (a task where pixels are fed one at a time in a fixed random order and the digit must be identified) from Table 2 of the paper. The model is a 1-layer LSTM with 100 units.

MethodValidationTest
No regularization0.0920.102
Recurrent Dropout (p=0.5p = 0.5)0.0830.075
Zoneout (zc=zh=0.15z_c = z_h = 0.15)0.0630.069
Recurrent batch normalization—0.046
Recurrent batch normalization + Zoneout0.0450.041

Both word-level Penn Treebank and permuted MNIST show that it also works well in combination with other regularizers.

Practical Considerations

The probabilities for the cell and the hidden state differ greatly in size. In the paper, large probabilities around 0.5 worked well for the LSTM cell, and small ones around 0.05 for the hidden state. The conclusion summarizes that "small probabilities of 0.05–0.2 on the hidden state consistently improved existing models." Using a large probability on the hidden state leaves the model barely able to take in new input.

  • Combine with other Dropout in large models: For the large word-level Penn Treebank model, Zoneout alone did not give sufficient results; it improved when combined with Dropout on the inputs and outputs (the non-recurrent connections).
  • Use the expected value at inference: At inference, use no random numbers and blend the previous and new values with z ht−1+(1−z) h~tz\,h_{t-1} + (1-z)\,\tilde{h}_t (the paper's official implementation does the same). Switch with model.train() and model.eval().
  • Redraw the mask per time step and per element: In the paper's character-level experiments, neither sharing the same mask between the cell and hidden state nor skipping whole time steps matched choosing separate masks per element.
  • Not built into PyTorch: Write the time-step loop with something like nn.LSTMCell and blend after each step's update (see the code example below). Since nn.LSTM, which computes everything at once with cuDNN, cannot be used, training is slower.

Comparison with Other Methods

The table compares the main ways of regularizing an RNN along the time dimension by what happens to the selected elements.

MethodWhat happens to selected elementsMaskInformation from earlier steps
Dropout on the hidden stateSet to 0Redrawn every time stepCut off at the selected elements
Recurrent Dropout (Semeniuta et al.)The cell update it⊙gti_t \odot g_t is set to 0—The cell persists according to the forget gate
Variational Dropout (RNN)Elements of the inputs, recurrent connections, and outputs set to 0Same at all time steps within a sequenceThe same elements are always missing within a sequence
ZoneoutKept at the previous step's valueRedrawn every time stepPassed straight to the next step
Stochastic DepthA residual block's transformation is skipped entirelyPer mini-batchPassed via the identity shortcut (along depth, not RNN time)
  • When information and gradients from distant time steps must be reliably preserved in long sequences, Zoneout is well suited, because the information in selected elements is not cut off.
  • When the goal is simply to lower perplexity in a word-level language model, the paper's table shows a lower value for Variational Dropout (73.4) than for Zoneout (77.4). However, the comparison is not under identical settings.
  • Both can be combined with Dropout on the inputs and outputs. For Zoneout probabilities, start small for the hidden state (around 0.05) and larger for the LSTM cell (around 0.5).

PyTorch example

Show code
python
import torch
import torch.nn as nn


class ZoneoutLSTMCell(nn.Module):
    """An LSTM cell with Zoneout, following the equations in Section 3.2 of Krueger et al. (2017)"""
    def __init__(self, input_size, hidden_size, z_c=0.5, z_h=0.05):
        super().__init__()
        self.cell = nn.LSTMCell(input_size, hidden_size)
        self.z_c, self.z_h = z_c, z_h   # probability of keeping the previous value (separate for cell and hidden state)

    def forward(self, x, state):
        h_prev, c_prev = state
        h_new, c_new = self.cell(x, (h_prev, c_prev))   # ordinary update (h_new is computed from the pre-zoneout cell)
        if self.training:
            # Redraw the mask per time step and per element (1 means keep the previous value)
            d_c = torch.bernoulli(torch.full_like(c_prev, self.z_c))
            d_h = torch.bernoulli(torch.full_like(h_prev, self.z_h))
            c = d_c * c_prev + (1 - d_c) * c_new
            h = d_h * h_prev + (1 - d_h) * h_new
        else:
            # Inference: use the expected value of the noise (blend in the previous value by z)
            c = self.z_c * c_prev + (1 - self.z_c) * c_new
            h = self.z_h * h_prev + (1 - self.z_h) * h_new
        return h, c


class ZoneoutLM(nn.Module):
    """Example character-level language model (1-layer LSTM, z_c = 0.5 and z_h = 0.05 as in the paper's character-level experiments)"""
    def __init__(self, vocab=50, hidden=1000):
        super().__init__()
        self.emb = nn.Embedding(vocab, hidden)
        self.rnn = ZoneoutLSTMCell(hidden, hidden, z_c=0.5, z_h=0.05)
        self.head = nn.Linear(hidden, vocab)
        self.hidden = hidden

    def forward(self, tokens):                  # tokens: [batch, T]
        B, T = tokens.shape
        h = torch.zeros(B, self.hidden)
        c = torch.zeros(B, self.hidden)
        outputs = []
        for t in range(T):
            h, c = self.rnn(self.emb(tokens[:, t]), (h, c))
            outputs.append(h)
        return self.head(torch.stack(outputs, dim=1))


model = ZoneoutLM()
optimizer = torch.optim.Adam(model.parameters(), lr=0.002)
tokens = torch.randint(0, 50, (32, 100))       # dummy mini-batch (32 sequences × 100 characters)
targets = torch.randint(0, 50, (32, 100))

model.train()                                  # training: randomly keep previous values
logits = model(tokens)
loss = nn.functional.cross_entropy(logits.reshape(-1, 50), targets.reshape(-1))
optimizer.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)   # clip the gradient norm at 1, as in the paper's character-level experiments
optimizer.step()

model.eval()                                   # inference: blend by the expected value (same result every time)
with torch.no_grad():
    next_char = model(tokens)[:, -1].argmax(dim=-1)

FAQ

Q. How should the zoneout probabilities be chosen?
A.

For an LSTM, start around 0.5 for the cell and around 0.05 for the hidden state. On character-level Penn Treebank in the paper, z_c = 0.5 and z_h = 0.05 worked best, and the conclusion also states that small probabilities of 0.05–0.2 on the hidden state consistently improved existing models. GRUs and simple RNNs also improved with small probabilities of 0.05–0.25.

Q. As with Dropout, can I do nothing at inference?
A.

At inference, use the expected value of the noise instead of a mask, blending in the previous value by the fraction z (h_t = z·h_{t−1} + (1 − z)·h̃_t). The paper's official implementation also uses this equation. Doing nothing (updating normally every time) makes the behavior differ from training.

Q. Should I use this or Variational Dropout (RNN)?
A.

Both regularize an RNN along the time dimension, and they can also be combined. Variational Dropout keeps zeroing the same elements throughout a sequence and has shown strong results on word-level Penn Treebank. Zoneout keeps selected elements at their previous values, and its strength is that information and gradients reach earlier time steps easily. Try Zoneout first for tasks where long-range dependencies matter and Variational Dropout first for language models, then compare on validation data.

References

  1. D. Krueger, T. Maharaj, J. Kramár, M. Pezeshki, N. Ballas, N. R. Ke, A. Goyal, Y. Bengio, A. Courville, and C. Pal, "Zoneout: Regularizing RNNs by Randomly Preserving Hidden Activations," ICLR, 2017.
  2. T. Maharaj and D. Krueger, "zoneout" (the paper's official implementation), GitHub.
  3. G. Huang, Y. Sun, Z. Liu, D. Sedra, and K. Q. Weinberger, "Deep Networks with Stochastic Depth," ECCV, 2016.
  4. Y. Gal and Z. Ghahramani, "A Theoretically Grounded Application of Dropout in Recurrent Neural Networks," NeurIPS, 2016.
  5. S. Semeniuta, A. Severyn, and E. Barth, "Recurrent Dropout without Memory Loss," COLING, 2016.