AI Logic

Regularization

Variational Dropout (RNN)

Updated:

An RNN unrolled over 3 time steps, comparing how Dropout masks are applied. At the top, ordinary Dropout applies masks only to the input x and output y, with a different mask pattern at each time step; the recurrent connections (from h to the next RNN step) are not masked. At the bottom, Variational Dropout applies masks to the input, the recurrent connections, and the output, and each mask has the same pattern at every time step

Background and Overview

Variational Dropout (RNN) is a regularization method that, within a single RNN sequence, uses the same Dropout mask at every time step and also applies it to the recurrent connections. Gal and Ghahramani presented it at NeurIPS in 2016. The paper calls an RNN using this method a Variational RNN (or a Variational LSTM for an LSTM).

RNNs such as the LSTM and GRU overfit quickly. Yet applying Dropout to the recurrent connections (from the hidden state at one time step to the next) was thought not to work: dropping different units at each time step makes the noise accumulate over long sequences and drown out the signal. So the standard practice until then (Zaremba et al. 2014) applied Dropout only to the RNN's inputs and outputs. Even so, the paper's experiments showed that overfitting remained.

Gal and Ghahramani applied to RNNs the theory that views Dropout as an approximation to Bayesian inference (the idea behind MC Dropout). What came out of it is a simple change: drop the same units across time steps. Because the same units rest every time, the noise does not change from step to step and accumulate, and even the recurrent connections can be regularized.

A different method has the same name. The "Variational Dropout" of Kingma et al. (2015) reinterprets Dropout with Gaussian noise as Bayesian inference and learns the drop rate (the noise level) itself from data. It has nothing to do with masks shared across RNN time steps. Both names come from Bayesian "variational inference," but their goals and procedures differ, so when reading papers or code, check which one is meant. This article covers the method of Gal and Ghahramani.

Theory (Where and How to Apply the Masks)

Following Section 4 of the paper, this section explains how the Bayesian view leads to the way masks are applied. pp is the drop probability (the opposite of the Dropout article, where pp is the keep probability).

  1. Treat the RNN weights ω={Wh,Uh,bh,Wy,by}\omega = \{W_h, U_h, b_h, W_y, b_y\} as random variables rather than fixed values. A simple RNN updates its hidden state as follows. ht=σ(xtWh+ht−1Uh+bh)h_t = \sigma(x_t W_h + h_{t-1} U_h + b_h)
  2. Approximate the posterior of the weights row by row with the following distribution qq (mkm_k is a learned parameter and σ2\sigma^2 is small). With probability pp the row is near 0, and with probability 1−p1-p it is near mkm_k. q(wk)=p N(wk; 0, σ2I)+(1−p) N(wk; mk, σ2I)q(w_k) = p\,\mathcal{N}(w_k;\, 0,\, \sigma^2 I) + (1-p)\,\mathcal{N}(w_k;\, m_k,\, \sigma^2 I)
  3. During training, sample the weights from qq only once per sequence and use the same weights at every time step of that sequence. Zeroing a row of the weights with probability pp is the same as dropping the input element that multiplies that row, so this amounts to "Dropout with the same mask at all time steps."
  4. In an LSTM, multiply the input xtx_t and the previous hidden state ht−1h_{t-1} by masks zxz_x and zhz_h, each shared across all time steps, before computing the gates (Equation 7). The output is likewise multiplied by a mask shared across all time steps. (ifog)=(sigmsigmsigmtanh⁡)((xt∘zxht−1∘zh)⋅W)\begin{pmatrix} i \\ f \\ o \\ g \end{pmatrix} = \begin{pmatrix} \mathrm{sigm} \\ \mathrm{sigm} \\ \mathrm{sigm} \\ \tanh \end{pmatrix} \left( \begin{pmatrix} x_t \circ z_x \\ h_{t-1} \circ z_h \end{pmatrix} \cdot W \right)
  5. The KL divergence term that measures the quality of the approximation can be approximated by L2 regularization on mkm_k (Weight Decay). The objective therefore becomes the ordinary RNN loss plus Weight Decay.

By comparison, the previous standard method (Zaremba et al.) redraws the input mask zxtz_x^t at every time step and applies no mask to ht−1h_{t-1} (Equation 8).

(ifog)=(sigmsigmsigmtanh⁡)((xt∘zxtht−1)⋅W)\begin{pmatrix} i \\ f \\ o \\ g \end{pmatrix} = \begin{pmatrix} \mathrm{sigm} \\ \mathrm{sigm} \\ \mathrm{sigm} \\ \tanh \end{pmatrix} \left( \begin{pmatrix} x_t \circ z_x^t \\ h_{t-1} \end{pmatrix} \cdot W \right)

The figure above shows the difference between the two over 3 time steps.

The equation in step 4 combines the weights of the four gates into a single matrix WW (what the paper calls tied weights). With a separate matrix per gate (untied weights), a different mask can be applied to each gate. In the paper's experiments, the two forms had similar accuracy, and tied weights, which need only one matrix multiplication, were faster.

Applying Dropout to Word Embeddings

For models that take words as input, the paper proposes applying Dropout to the embedding matrix in the same spirit (Section 4.2). The embedding matrix is the largest layer in a language model, yet it often goes unregularized.

For each sequence, the rows of the embedding matrix (word types) are zeroed with probability pp. Because the mask is the same at all time steps, within a sentence every occurrence of the same word disappears together. In the paper's example, "the dog and the cat" can become "— dog and — cat" or "the — and the cat," but never "— dog and the cat" (with only the first "the" removed).

This encourages the model not to rely too heavily on individual words and to draw its answer from the sentence as a whole. When the vocabulary size VV is large, drawing VV random numbers is wasteful, so it is more efficient to first convert words to embeddings and then zero them out by word type.

Experimental Results

Results from Table 1 of the paper for word-level language modeling on Penn Treebank (perplexity, lower is better). The model is the same 2-layer LSTM as in Zaremba et al. (medium: 650 units per layer; large: 1500 units per layer), and only the way Dropout is applied and the Weight Decay tuning differ. The Variational values are averages over 3 runs.

MethodMedium, validationMedium, testLarge, validationLarge, test
No regularization (Early Stopping)121.1121.7128.3127.4
Moon et al. (same mask on the cell at all steps)100.797.0122.9118.7
Zaremba et al. (inputs and outputs only, different mask per step)86.282.782.278.4
Variational (tied weights)81.879.777.375.0
Variational (tied weights, MC)—79.0—74.1
Variational (untied weights)81.979.777.975.2
Variational (untied weights, MC)—78.6—73.4

"MC" means predicting 1000 times with Dropout still applied at inference and averaging.

  • Larger models pay off: Without regularization, the large model was worse than the medium one. With Variational Dropout, the large model was clearly better. There is no longer a need to choose a small model to prevent overfitting.
  • Best single model: The large model's test perplexity fell from Zaremba et al.'s 78.4 to 73.4, the best single-model result on Penn Treebank at the time of the paper.
  • Works in ensembles too: Averaging 10 large models gave 68.7, matching the value Zaremba et al. obtained by averaging 38 models.
  • Resists overfitting on small tasks: In sentiment analysis of movie reviews (5,000 examples), the Variational LSTM was the only compared method that did not overfit.

The best drop probabilities in the paper were 0.3 for the embeddings and recurrent connections and 0.5 for the inputs and outputs in the large model, and 0.2 and 0.35 respectively in the medium model (Zaremba et al. used 0.6 and 0.5, respectively).

Inference and Practical Considerations

There are two ways to run inference (Equation 4 of the paper).

  • The same approximation as ordinary Dropout: Apply no mask at inference and scale the output to match its average during training. Only one pass is needed.
  • MC Dropout: Keep the masks at inference, predict KK times, and average. It costs KK times as much computation, but in the paper it gave slightly better values, and the spread of predictions also gives an estimate of uncertainty (MC Dropout).

PyTorch's nn.LSTM(dropout=...) is not this method. That argument applies ordinary Dropout to the output of each stacked layer (except the last); it does not touch the recurrent connections, and the mask differs at every time step. To use Variational Dropout, write the time-step loop yourself with something like nn.LSTMCell, and reuse a mask chosen per sequence at every time step (see the code example below).

  • Computation slows down: Writing the time-step loop in Python is slower than nn.LSTM, which computes everything at once with cuDNN. Even in the paper's implementation, the form with a separate mask per gate (untied weights) dropped from 2.4K to 1.6K words processed per second for the large model.
  • Set drop probabilities per location: The paper uses one probability for the embeddings and recurrent connections and one for the inputs and outputs, chosen by grid search on validation perplexity. For both model sizes, the chosen values were smaller for the embeddings and recurrent connections than for the inputs and outputs.
  • Tune together with Weight Decay: In theory, the KL term corresponds to Weight Decay. The paper tunes Weight Decay too (Zaremba et al.'s setting used 0).
  • Switch with model.train() / model.eval(): As in the code example, create masks only during training and not at inference. Create masks at inference only when running MC Dropout.

Comparison with Other Methods

The table compares the main ways of applying Dropout to RNNs by where the masks go and whether they are redrawn at each time step.

MethodWhere the mask is appliedMaskRegularizes recurrent connections
Ordinary Dropout (Zaremba et al. 2014)Inputs and outputsRedrawn every time stepNo
Moon et al. (rnnDrop, 2015)LSTM cell ctc_tSame at all time stepsThrough the cell
Variational Dropout (Gal and Ghahramani)Inputs, outputs, recurrent connections, embeddingsSame at all time stepsYes
ZoneoutHidden state (replaced with the previous step's value instead of 0)Redrawn every time stepYes
Variational Dropout (Kingma et al. 2015)Layer inputs (Gaussian noise)—Not a method for RNNs
  • When overfitting is a problem in an RNN, such as a word-level language model, try Variational Dropout first. In the paper's Penn Treebank experiments, it improved substantially over ordinary Dropout.
  • When information and gradients from earlier time steps must be passed reliably through long sequences, Zoneout is also a candidate. Zoneout keeps dropped elements at their previous values instead of zeroing them, so information is not cut off. The two can also be combined.
  • Kingma et al.'s method of the same name is for learning the drop rate and has nothing to do with how RNN time steps are handled.

PyTorch example

Show code
python
import torch
import torch.nn as nn


def make_mask(batch, dim, p, like):
    """A mask created only once per sequence. Drop probability p; kept elements are scaled by 1/(1 − p) (inverted dropout)"""
    return like.new_empty(batch, dim).bernoulli_(1 - p) / (1 - p)


class VariationalLSTM(nn.Module):
    """A 1-layer LSTM following Eq. 7 (tied weights) of Gal and Ghahramani (2016)"""
    def __init__(self, vocab, emb_dim, hidden, p_emb=0.3, p_in=0.5, p_h=0.3, p_out=0.5):
        super().__init__()
        self.emb = nn.Embedding(vocab, emb_dim)
        self.cell = nn.LSTMCell(emb_dim, hidden)   # the four gates' weights combined into one
        self.head = nn.Linear(hidden, vocab)
        self.hidden = hidden
        self.p_emb, self.p_in, self.p_h, self.p_out = p_emb, p_in, p_h, p_out

    def forward(self, tokens):                     # tokens: [batch, T]
        B, T = tokens.shape
        e = self.emb(tokens)                       # [batch, T, emb_dim]
        if self.training:
            # Word embedding Dropout: drop by word type (the same word disappears together within a sentence)
            keep = e.new_empty(B, self.emb.num_embeddings).bernoulli_(1 - self.p_emb) / (1 - self.p_emb)
            e = e * keep.gather(1, tokens).unsqueeze(-1)
            # Create input, recurrent, and output masks only once per sequence (reused at every time step)
            z_x = make_mask(B, e.size(-1), self.p_in, e)
            z_h = make_mask(B, self.hidden, self.p_h, e)
            z_y = make_mask(B, self.hidden, self.p_out, e)
        h = e.new_zeros(B, self.hidden)
        c = e.new_zeros(B, self.hidden)
        outputs = []
        for t in range(T):
            x_t = e[:, t]
            if self.training:
                x_t, h_in = x_t * z_x, h * z_h     # Eq. 7: x_t ∘ z_x, h_{t−1} ∘ z_h (the same z at every time step)
            else:
                h_in = h                           # inference: no masks (the ordinary Dropout approximation)
            h, c = self.cell(x_t, (h_in, c))
            outputs.append(h * z_y if self.training else h)
        return self.head(torch.stack(outputs, dim=1))   # [batch, T, vocab]


model = VariationalLSTM(vocab=10000, emb_dim=200, hidden=200)
tokens = torch.randint(0, 10000, (20, 35))          # dummy mini-batch (20 sequences × 35 words)
targets = torch.randint(0, 10000, (20, 35))
optimizer = torch.optim.SGD(model.parameters(), lr=1.0, weight_decay=1e-6)  # the KL term corresponds to Weight Decay

model.train()                                       # create masks
logits = model(tokens)
loss = nn.functional.cross_entropy(logits.reshape(-1, 10000), targets.reshape(-1))
optimizer.zero_grad()
loss.backward()
optimizer.step()

model.eval()                                        # no masks
with torch.no_grad():
    probs = model(tokens).softmax(dim=-1)

# For MC Dropout inference, stay in train() mode, predict K times, and average
model.train()
with torch.no_grad():
    mc_probs = torch.stack([model(tokens).softmax(dim=-1) for _ in range(10)]).mean(dim=0)

FAQ

Q. How does it differ from the Variational Dropout of Kingma et al.?
A.

They are different methods. The method of Gal and Ghahramani (this article) reuses the same Dropout mask at every time step within an RNN sequence and also applies it to the recurrent connections. The Variational Dropout of Kingma et al. (2015) reinterprets Dropout with Gaussian noise as Bayesian inference and learns the drop rate itself; it has nothing to do with how RNN time steps are handled. Both names come from variational inference, which is why they share a name.

Q. Is it the same as using the dropout argument of PyTorch's nn.LSTM?
A.

No. The dropout argument of nn.LSTM applies ordinary Dropout to the output of each stacked layer (except the last); it does not touch the recurrent connections, and the masks are independent at each time step. To get Variational Dropout, write the time-step loop with something like nn.LSTMCell and reuse a mask created per sequence at every time step.

Q. Why does reusing the same mask make it work on the recurrent connections?
A.

Dropping different units at each time step makes the noise accumulate over long sequences and wipe out information from earlier steps. Reusing the same mask means running "a slightly smaller RNN missing some units" all the way through the sequence, so the noise does not change from step to step. Theoretically, it also matches the Bayesian approximation of sampling the weights once per sequence and using them at every time step.

References

  1. Y. Gal and Z. Ghahramani, "A Theoretically Grounded Application of Dropout in Recurrent Neural Networks," NeurIPS, 2016.
  2. D. P. Kingma, T. Salimans, and M. Welling, "Variational Dropout and the Local Reparameterization Trick," NeurIPS, 2015.
  3. W. Zaremba, I. Sutskever, and O. Vinyals, "Recurrent Neural Network Regularization," arXiv:1409.2329, 2014.
  4. D. Krueger et al., "Zoneout: Regularizing RNNs by Randomly Preserving Hidden Activations," ICLR, 2017.
  5. PyTorch Documentation, "torch.nn.LSTM."