{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Implementation of the language models" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hide_input": true }, "outputs": [], "source": [ "from fastai.gen_doc.nbdoc import *\n", "from fastai.text import * \n", "from fastai.text.models import * " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[`text.models`](/text.models.html#text.models) module fully implements the [AWD-LSTM](https://arxiv.org/pdf/1708.02182.pdf) from Stephen Merity et al. The main idea of the article is to use a [RNN](http://www.pnas.org/content/79/8/2554) with dropout everywhere, but in an intelligent way. There is a difference with the usual dropout, which is why you’ll see a [`RNNDropout`](/text.models.html#RNNDropout) module: we zero things, as is usual in dropout, but we always zero the same thing according to the sequence dimension (which is the first dimension in pytorch). This ensures consistency when updating the hidden state through the whole sentences/articles. \n", "\n", "This being given, there are five different dropouts in the AWD-LSTM:\n", "\n", "- the first one, embedding dropout, is applied when we look the ids of our tokens inside the embedding matrix (to transform them from numbers to a vector of float). We zero some lines of it, so random ids are sent to a vector of zeros instead of being sent to their embedding vector.\n", "- the second one, input dropout, is applied to the result of the embedding with dropout. We forget random pieces of the embedding matrix (but as stated in the last paragraph, the same ones in the sequence dimension).\n", "- the third one is the weight dropout. It’s the trickiest to implement as we randomly replace by 0s some weights of the hidden-to-hidden matrix inside the RNN: this needs to be done in a way that ensure the gradients are still computed and the initial weights still updated.\n", "- the fourth one is the hidden dropout. It’s applied to the output of one of the layers of the RNN before it’s used as input of the next layer (again same coordinates are zeroed in the sequence dimension). This one isn’t applied to the last output, but rather…\n", "- the fifth one is the output dropout, it’s applied to the last output of the model (and like the others, it’s applied the same way through the first dimension)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Basic functions to get a model" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "hide_input": true }, "outputs": [ { "data": { "text/markdown": [ "
get_language_model
[source]get_language_model
(`vocab_sz`:`int`, `emb_sz`:`int`, `n_hid`:`int`, `n_layers`:`int`, `pad_token`:`int`, `tie_weights`:`bool`=`True`, `qrnn`:`bool`=`False`, `bias`:`bool`=`True`, `bidir`:`bool`=`False`, `output_p`:`float`=`0.4`, `hidden_p`:`float`=`0.2`, `input_p`:`float`=`0.6`, `embed_p`:`float`=`0.1`, `weight_p`:`float`=`0.5`) → [`Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)\n",
"\n",
"Create a full AWD-LSTM. "
],
"text/plain": [
"get_rnn_classifier
[source]get_rnn_classifier
(`bptt`:`int`, `max_seq`:`int`, `vocab_sz`:`int`, `emb_sz`:`int`, `n_hid`:`int`, `n_layers`:`int`, `pad_token`:`int`, `layers`:`Collection`\\[`int`\\], `drops`:`Collection`\\[`float`\\], `bidir`:`bool`=`False`, `qrnn`:`bool`=`False`, `hidden_p`:`float`=`0.2`, `input_p`:`float`=`0.6`, `embed_p`:`float`=`0.1`, `weight_p`:`float`=`0.5`) → [`Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)\n",
"\n",
"Create a RNN classifier model. "
],
"text/plain": [
"class
EmbeddingDropout
[source]EmbeddingDropout
(`emb`:[`Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module), `embed_p`:`float`) :: [`Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)\n",
"\n",
"Apply dropout with probabily `embed_p` to an embedding layer `emb`. "
],
"text/plain": [
"class
RNNDropout
[source]RNNDropout
(`p`:`float`=`0.5`) :: [`Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)\n",
"\n",
"Dropout with probability `p` that is consistent on the seq_len dimension. "
],
"text/plain": [
"class
WeightDropout
[source]WeightDropout
(`module`:[`Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module), `weight_p`:`float`, `layer_names`:`StrList`=`['weight_hh_l0']`) :: [`Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)\n",
"\n",
"A module that warps another layer in which some weights will be replaced by 0 during training. "
],
"text/plain": [
"class
SequentialRNN
[source]SequentialRNN
(`args`) :: [`Sequential`](https://pytorch.org/docs/stable/nn.html#torch.nn.Sequential)\n",
"\n",
"A sequential module that passes the reset call to its children. "
],
"text/plain": [
"reset
[source]reset
()"
],
"text/plain": [
"dropout_mask
[source]dropout_mask
(`x`:`Tensor`, `sz`:`Collection`\\[`int`\\], `p`:`float`)\n",
"\n",
"Return a dropout mask of the same type as `x`, size `sz`, with probability `p` to cancel an element. "
],
"text/plain": [
"class
RNNCore
[source]RNNCore
(`vocab_sz`:`int`, `emb_sz`:`int`, `n_hid`:`int`, `n_layers`:`int`, `pad_token`:`int`, `bidir`:`bool`=`False`, `hidden_p`:`float`=`0.2`, `input_p`:`float`=`0.6`, `embed_p`:`float`=`0.1`, `weight_p`:`float`=`0.5`, `qrnn`:`bool`=`False`) :: [`Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)\n",
"\n",
"AWD-LSTM/QRNN inspired by https://arxiv.org/abs/1708.02182. "
],
"text/plain": [
"reset
[source]reset
()\n",
"\n",
"Reset the hidden states. "
],
"text/plain": [
"class
LinearDecoder
[source]LinearDecoder
(`n_out`:`int`, `n_hid`:`int`, `output_p`:`float`, `tie_encoder`:[`Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)=`None`, `bias`:`bool`=`True`) :: [`Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)\n",
"\n",
"To go on top of a RNNCore module and create a Language Model. "
],
"text/plain": [
"class
MultiBatchRNNCore
[source]MultiBatchRNNCore
(`bptt`:`int`, `max_seq`:`int`, `args`, `kwargs`) :: [`RNNCore`](/text.models.html#RNNCore)\n",
"\n",
"Create a RNNCore module that can process a full sentence. "
],
"text/plain": [
"concat
[source]concat
(`arrs`:`Collection`\\[`Tensor`\\]) → `Tensor`\n",
"\n",
"Concatenate the `arrs` along the batch dimension. "
],
"text/plain": [
"class
PoolingLinearClassifier
[source]PoolingLinearClassifier
(`layers`:`Collection`\\[`int`\\], `drops`:`Collection`\\[`float`\\]) :: [`Module`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)\n",
"\n",
"Create a linear classifier with pooling. "
],
"text/plain": [
"pool
[source]pool
(`x`:`Tensor`, `bs`:`int`, `is_max`:`bool`)\n",
"\n",
"Pool the tensor along the seq_len dimension. "
],
"text/plain": [
"forward
[source]forward
(`args`:`ArgStar`)\n",
"\n",
"Defines the computation performed at every call. Should be overridden by all subclasses.\n",
"\n",
".. note::\n",
" Although the recipe for forward pass needs to be defined within\n",
" this function, one should call the :class:`Module` instance afterwards\n",
" instead of this since the former takes care of running the\n",
" registered hooks while the latter silently ignores them. "
],
"text/plain": [
"forward
[source]forward
(`input`:`LongTensor`) → `Tuple`\\[`Tensor`, `Tensor`\\]\n",
"\n",
"Defines the computation performed at every call. Should be overridden by all subclasses.\n",
"\n",
".. note::\n",
" Although the recipe for forward pass needs to be defined within\n",
" this function, one should call the :class:`Module` instance afterwards\n",
" instead of this since the former takes care of running the\n",
" registered hooks while the latter silently ignores them. "
],
"text/plain": [
"forward
[source]forward
(`words`:`LongTensor`, `scale`:`Optional`\\[`float`\\]=`None`) → `Tensor`\n",
"\n",
"Defines the computation performed at every call. Should be overridden by all subclasses.\n",
"\n",
".. note::\n",
" Although the recipe for forward pass needs to be defined within\n",
" this function, one should call the :class:`Module` instance afterwards\n",
" instead of this since the former takes care of running the\n",
" registered hooks while the latter silently ignores them. "
],
"text/plain": [
"forward
[source]forward
(`x`:`Tensor`) → `Tensor`\n",
"\n",
"Defines the computation performed at every call. Should be overridden by all subclasses.\n",
"\n",
".. note::\n",
" Although the recipe for forward pass needs to be defined within\n",
" this function, one should call the :class:`Module` instance afterwards\n",
" instead of this since the former takes care of running the\n",
" registered hooks while the latter silently ignores them. "
],
"text/plain": [
"reset
[source]reset
()"
],
"text/plain": [
"forward
[source]forward
(`input`:`Tuple`\\[`Tensor`, `Tensor`\\]) → `Tuple`\\[`Tensor`, `Tensor`, `Tensor`\\]\n",
"\n",
"Defines the computation performed at every call. Should be overridden by all subclasses.\n",
"\n",
".. note::\n",
" Although the recipe for forward pass needs to be defined within\n",
" this function, one should call the :class:`Module` instance afterwards\n",
" instead of this since the former takes care of running the\n",
" registered hooks while the latter silently ignores them. "
],
"text/plain": [
"forward
[source]forward
(`input`:`LongTensor`) → `Tuple`\\[`Tensor`, `Tensor`\\]\n",
"\n",
"Defines the computation performed at every call. Should be overridden by all subclasses.\n",
"\n",
".. note::\n",
" Although the recipe for forward pass needs to be defined within\n",
" this function, one should call the :class:`Module` instance afterwards\n",
" instead of this since the former takes care of running the\n",
" registered hooks while the latter silently ignores them. "
],
"text/plain": [
"forward
[source]forward
(`input`:`Tuple`\\[`Tensor`, `Tensor`\\]) → `Tuple`\\[`Tensor`, `Tensor`, `Tensor`\\]\n",
"\n",
"Defines the computation performed at every call. Should be overridden by all subclasses.\n",
"\n",
".. note::\n",
" Although the recipe for forward pass needs to be defined within\n",
" this function, one should call the :class:`Module` instance afterwards\n",
" instead of this since the former takes care of running the\n",
" registered hooks while the latter silently ignores them. "
],
"text/plain": [
"