AWD-LSTM

Open In Colab

AWD LSTM from Smerity et al.

  1. /usr/local/lib/python3.8/dist-packages/torch/cuda/__init__.py:52: UserWarning: CUDA initialization: Found no NVIDIA driver on your system. Please check that you have an NVIDIA GPU and installed a driver from http://www.nvidia.com/Download/index.aspx (Triggered internally at /pytorch/c10/cuda/CUDAFunctions.cpp:100.)
  2. return torch._C._cuda_getDeviceCount() > 0

Basic NLP modules

On top of the pytorch or the fastai layers, the language models use some custom layers specific to NLP.

dropout_mask[source]

dropout_mask(x, sz, p)

Return a dropout mask of the same type as x, size sz, with probability p to cancel an element.

  1. t = dropout_mask(torch.randn(3,4), [4,3], 0.25)
  2. test_eq(t.shape, [4,3])
  3. assert ((t == 4/3) + (t==0)).all()

class RNNDropout[source]

RNNDropout(p=0.5) :: Module

Dropout with probability p that is consistent on the seq_len dimension.

  1. dp = RNNDropout(0.3)
  2. tst_inp = torch.randn(4,3,7)
  3. tst_out = dp(tst_inp)
  4. for i in range(4):
  5. for j in range(7):
  6. if tst_out[i,0,j] == 0: assert (tst_out[i,:,j] == 0).all()
  7. else: test_close(tst_out[i,:,j], tst_inp[i,:,j]/(1-0.3))

It also supports doing dropout over a sequence of images where time dimesion is the 1st axis, 10 images of 3 channels and 32 by 32.

  1. _ = dp(torch.rand(4,10,3,32,32))

class WeightDropout[source]

WeightDropout(module, weight_p, layer_names='weight_hh_l0') :: Module

A module that wraps another layer in which some weights will be replaced by 0 during training.

  1. module = nn.LSTM(5,7)
  2. dp_module = WeightDropout(module, 0.4)
  3. wgts = dp_module.module.weight_hh_l0
  4. tst_inp = torch.randn(10,20,5)
  5. h = torch.zeros(1,20,7), torch.zeros(1,20,7)
  6. dp_module.reset()
  7. x,h = dp_module(tst_inp,h)
  8. loss = x.sum()
  9. loss.backward()
  10. new_wgts = getattr(dp_module.module, 'weight_hh_l0')
  11. test_eq(wgts, getattr(dp_module, 'weight_hh_l0_raw'))
  12. assert 0.2 <= (new_wgts==0).sum().float()/new_wgts.numel() <= 0.6
  13. assert dp_module.weight_hh_l0_raw.requires_grad
  14. assert dp_module.weight_hh_l0_raw.grad is not None
  15. assert ((dp_module.weight_hh_l0_raw.grad == 0.) & (new_wgts == 0.)).any()

class EmbeddingDropout[source]

EmbeddingDropout(emb, embed_p) :: Module

Apply dropout with probability embed_p to an embedding layer emb.

  1. enc = nn.Embedding(10, 7, padding_idx=1)
  2. enc_dp = EmbeddingDropout(enc, 0.5)
  3. tst_inp = torch.randint(0,10,(8,))
  4. tst_out = enc_dp(tst_inp)
  5. for i in range(8):
  6. assert (tst_out[i]==0).all() or torch.allclose(tst_out[i], 2*enc.weight[tst_inp[i]])

class AWD_LSTM[source]

AWD_LSTM(vocab_sz, emb_sz, n_hid, n_layers, pad_token=1, hidden_p=0.2, input_p=0.6, embed_p=0.1, weight_p=0.5, bidir=False) :: Module

AWD-LSTM inspired by https://arxiv.org/abs/1708.02182

This is the core of an AWD-LSTM model, with embeddings from vocab_sz and emb_sz, n_layers LSTMs potentially bidir stacked, the first one going from emb_sz to n_hid, the last one from n_hid to emb_sz and all the inner ones from n_hid to n_hid. pad_token is passed to the PyTorch embedding layer. The dropouts are applied as such:

  • the embeddings are wrapped in EmbeddingDropout of probability embed_p;
  • the result of this embedding layer goes through an RNNDropout of probability input_p;
  • each LSTM has WeightDropout applied with probability weight_p;
  • between two of the inner LSTM, an RNNDropout is applied with probability hidden_p.

THe module returns two lists: the raw outputs (without being applied the dropout of hidden_p) of each inner LSTM and the list of outputs with dropout. Since there is no dropout applied on the last output, those two lists have the same last element, which is the output that should be fed to a decoder (in the case of a language model).

  1. tst = AWD_LSTM(100, 20, 10, 2, hidden_p=0.2, embed_p=0.02, input_p=0.1, weight_p=0.2)
  2. x = torch.randint(0, 100, (10,5))
  3. r = tst(x)
  4. test_eq(tst.bs, 10)
  5. test_eq(len(tst.hidden), 2)
  6. test_eq([h_.shape for h_ in tst.hidden[0]], [[1,10,10], [1,10,10]])
  7. test_eq([h_.shape for h_ in tst.hidden[1]], [[1,10,20], [1,10,20]])
  8. test_eq(r.shape, [10,5,20])
  9. test_eq(r[:,-1], tst.hidden[-1][0][0]) #hidden state is the last timestep in raw outputs
  10. tst.eval()
  11. tst.reset()
  12. tst(x);
  13. tst(x);

awd_lstm_lm_split[source]

awd_lstm_lm_split(model)

Split a RNN model in groups for differential learning rates.

awd_lstm_clas_split[source]

awd_lstm_clas_split(model)

Split a RNN model in groups for differential learning rates.

QRNN

class AWD_QRNN[source]

AWD_QRNN(vocab_sz, emb_sz, n_hid, n_layers, pad_token=1, hidden_p=0.2, input_p=0.6, embed_p=0.1, weight_p=0.5, bidir=False) :: AWD_LSTM

Same as an AWD-LSTM, but using QRNNs instead of LSTMs

  1. # cpp
  2. model = AWD_QRNN(vocab_sz=10, emb_sz=20, n_hid=16, n_layers=2, bidir=False)
  3. x = torch.randint(0, 10, (7,5))
  4. y = model(x)
  5. test_eq(y.shape, (7, 5, 20))

Company logo

©2021 fast.ai. All rights reserved.
Site last generated: Mar 31, 2021