Skip to content

Instantly share code, notes, and snippets.

@morganmcg1
Created December 18, 2020 20:51
Show Gist options
  • Save morganmcg1/11bef00ba82bfcab9f1fa82cb674bafc to your computer and use it in GitHub Desktop.
Save morganmcg1/11bef00ba82bfcab9f1fa82cb674bafc to your computer and use it in GitHub Desktop.
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "view-in-github"
},
"source": [
"<a href=\"https://colab.research.google.com/github/sheikmohdimran/Experiments_2020/blob/master/NLP/SWT_fastai.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"id": "vXXOuS71WiEY"
},
"outputs": [],
"source": [
"# !wget https://raw.githubusercontent.com/tensorflow/tensor2tensor/master/tensor2tensor/test_data/vocab.translate_ende_wmt32k.32768.subwords\n",
"# !pip install -qq git+git://github.com/arampacha/reformer_fastai.git\n",
"\n",
"# !gdown --id 1-AVxs5Hpb7wxRq33hiTI6uteZkqROtYc\n",
"# !gdown --id 1-9vZZ-xr-Fbi1BP34peuc1kEJURoL1Jd\n",
"# !gdown --id 18Cov7aNhoeOizqSqdXN6Y9xiC8jaMyrC"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"id": "ux0ctd-fVysN"
},
"outputs": [],
"source": [
"IN_COLAB = 'google.colab' in str(get_ipython())\n",
"if IN_COLAB:\n",
" !pip install -Uqq fastai einops datasets wandb yappi gprof2dot pyinstrument nbdev fastcore\n",
" import os\n",
" os.kill(os.getpid(), 9)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"id": "YVB_GjWVV37O"
},
"outputs": [],
"source": [
"import six\n",
"from six import int2byte, unichr, PY2, iterkeys, iteritems, text_type\n",
"from six.moves import range as six_range\n",
"import collections\n",
"\n",
"import unicodedata\n",
"from itertools import chain\n",
"\n",
"from fastai.basics import *\n",
"from fastai.text.all import *"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"id": "wWF4HieQV5nY"
},
"outputs": [],
"source": [
"class SubwordTextEncoder(Transform):\n",
" \"\"\"Class for invertibly encoding text using a limited vocabulary.\n",
"\n",
" Invertibly encodes a native string as a sequence of subtokens from a limited\n",
" vocabulary.\n",
"\n",
" A SubwordTextEncoder is built from a corpus (so it is tailored to the text in\n",
" the corpus), and stored to a file. See text_encoder_build_subword.py.\n",
"\n",
" It can then be loaded and used to encode/decode any text.\n",
"\n",
" Encoding has four phases:\n",
"\n",
" 1. Tokenize into a list of tokens. Each token is a unicode string of either\n",
" all alphanumeric characters or all non-alphanumeric characters. We drop\n",
" tokens consisting of a single space that are between two alphanumeric\n",
" tokens.\n",
"\n",
" 2. Escape each token. This escapes away special and out-of-vocabulary\n",
" characters, and makes sure that each token ends with an underscore, and\n",
" has no other underscores.\n",
"\n",
" 3. Represent each escaped token as a the concatenation of a list of subtokens\n",
" from the limited vocabulary. Subtoken selection is done greedily from\n",
" beginning to end. That is, we construct the list in order, always picking\n",
" the longest subtoken in our vocabulary that matches a prefix of the\n",
" remaining portion of the encoded token.\n",
"\n",
" 4. Concatenate these lists. This concatenation is invertible due to the\n",
" fact that the trailing underscores indicate when one list is finished.\n",
"\n",
" \"\"\"\n",
"\n",
" def __init__(self, filename=None, is_lm=True, add_bos=False, seq_len=256):\n",
" \"\"\"Initialize and read from a file, if provided.\n",
"\n",
" Args:\n",
" filename: filename from which to read vocab. If None, do not load a\n",
" vocab\n",
" seq_len : max sequence length of encoded tokens\n",
" \"\"\"\n",
" store_attr()\n",
"# self.native_to_unicode = (lambda s: s.decode(\"utf-8\")) if PY2 else (lambda s: s)\n",
" self._ALPHANUMERIC_CHAR_SET = set(unichr(i) for i in six_range(sys.maxunicode) if (unicodedata.category(unichr(i)).startswith(\"L\") or unicodedata.category(unichr(i)).startswith(\"N\")))\n",
" self.PAD = \"<pad>\"\n",
" self.EOS = \"<EOS>\"\n",
" self.RESERVED_TOKENS = [self.PAD, self.EOS]\n",
" self.NUM_RESERVED_TOKENS = len(self.RESERVED_TOKENS)\n",
" self.PAD_ID = self.RESERVED_TOKENS.index(self.PAD) # Normally 0\n",
" self.EOS_ID = self.RESERVED_TOKENS.index(self.EOS) # Normally 1\n",
" self._UNESCAPE_REGEX = re.compile(r\"\\\\u|\\\\\\\\|\\\\([0-9]+);\")\n",
" self._ESCAPE_CHARS = set(u\"\\\\_u;0123456789\")\n",
" self.ls_lm = is_lm\n",
" self.add_bos = add_bos\n",
"\n",
"\n",
" self._alphabet = set()\n",
" self.filename = filename\n",
" if filename is not None:\n",
" self._load_from_file(filename)\n",
" super(SubwordTextEncoder, self).__init__()\n",
"\n",
" def encodes(self, s):\n",
" \"\"\"Converts a native string to a list of subtoken ids.\n",
"\n",
" Args:\n",
" s: a native string.\n",
" Returns:\n",
" a list of integers in the range [0, vocab_size)\n",
" \"\"\"\n",
" return self.__call__(s)\n",
"\n",
" @typedispatch\n",
" def __call__(self, s:str, **kwargs):\n",
" out = self._tokens_to_subtoken_ids(self._encode(text=self.native_to_unicode(s)))\n",
" out = out[:self.seq_len]\n",
" if self.add_bos: out = [self.PAD_ID] + out # Imran Add <pad> to begining of sentence\n",
" if self.ls_lm: return LMTensorText(out)\n",
" else: return TensorText(out)\n",
"\n",
" def encode_without_tokenizing(self, token_text):\n",
" \"\"\"Converts string to list of subtoken ids without calling tokenizer.\n",
"\n",
" This treats `token_text` as a single token and directly converts it\n",
" to subtoken ids. This may be useful when the default tokenizer doesn't\n",
" do what we want (e.g., when encoding text with tokens composed of lots of\n",
" nonalphanumeric characters). It is then up to the caller to make sure that\n",
" raw text is consistently converted into tokens. Only use this if you are\n",
" sure that `encode` doesn't suit your needs.\n",
"\n",
" Args:\n",
" token_text: A native string representation of a single token.\n",
" Returns:\n",
" A list of subword token ids; i.e., integers in the range [0, vocab_size).\n",
" \"\"\"\n",
" return self._tokens_to_subtoken_ids([self.native_to_unicode(token_text)])\n",
"\n",
" def decodes(self, ids, strip_extraneous=False):\n",
" \"\"\"Converts a sequence of subtoken ids to a native string.\n",
"\n",
" Args:\n",
" ids: a list of integers in the range [0, vocab_size)\n",
" strip_extraneous: bool, whether to strip off extraneous tokens\n",
" (EOS and PAD).\n",
"\n",
" Returns:\n",
" a native string\n",
" \"\"\"\n",
" if strip_extraneous:\n",
" ids = strip_ids(ids, list(six_range(self._num_reserved_ids or 0)))\n",
" return self.unicode_to_native(\n",
" self._decode(self._subtoken_ids_to_tokens(ids)))\n",
"\n",
" def decode_list(self, ids):\n",
" return [self._subtoken_id_to_subtoken_string(s) for s in ids]\n",
"\n",
" @property\n",
" def vocab_size(self):\n",
" \"\"\"The subtoken vocabulary size.\"\"\"\n",
" return len(self._all_subtoken_strings)\n",
"\n",
" def _tokens_to_subtoken_ids(self, tokens):\n",
" \"\"\"Converts a list of tokens to a list of subtoken ids.\n",
"\n",
" Args:\n",
" tokens: a list of strings.\n",
" Returns:\n",
" a list of integers in the range [0, vocab_size)\n",
" \"\"\"\n",
" ret = []\n",
" for token in tokens:\n",
" ret.extend(self._token_to_subtoken_ids(token))\n",
" return ret\n",
"\n",
" def native_to_unicode(self,s):\n",
" if PY2:return s.decode(\"utf-8\")\n",
" else: return s\n",
"\n",
" def _token_to_subtoken_ids(self, token):\n",
" \"\"\"Converts token to a list of subtoken ids.\n",
"\n",
" Args:\n",
" token: a string.\n",
" Returns:\n",
" a list of integers in the range [0, vocab_size)\n",
" \"\"\"\n",
" cache_location = hash(token) % self._cache_size\n",
" cache_key, cache_value = self._cache[cache_location]\n",
" if cache_key == token:\n",
" return cache_value\n",
" ret = self._escaped_token_to_subtoken_ids(\n",
" self._escape_token(token, self._alphabet))\n",
" self._cache[cache_location] = (token, ret)\n",
" return ret\n",
"\n",
" def _subtoken_ids_to_tokens(self, subtokens):\n",
" \"\"\"Converts a list of subtoken ids to a list of tokens.\n",
"\n",
" Args:\n",
" subtokens: a list of integers in the range [0, vocab_size)\n",
" Returns:\n",
" a list of strings.\n",
" \"\"\"\n",
" concatenated = \"\".join(\n",
" [self._subtoken_id_to_subtoken_string(s) for s in subtokens])\n",
" split = concatenated.split(\"_\")\n",
" ret = []\n",
" for t in split:\n",
" if t:\n",
" unescaped = self._unescape_token(t + \"_\")\n",
" if unescaped:\n",
" ret.append(unescaped)\n",
" return ret\n",
"\n",
" def _subtoken_id_to_subtoken_string(self, subtoken):\n",
" \"\"\"Converts a subtoken integer ID to a subtoken string.\"\"\"\n",
" if 0 <= subtoken < self.vocab_size:\n",
" return self._all_subtoken_strings[subtoken]\n",
" return u\"\"\n",
"\n",
" def _escaped_token_to_subtoken_strings(self, escaped_token):\n",
" \"\"\"Converts an escaped token string to a list of subtoken strings.\n",
"\n",
" Args:\n",
" escaped_token: An escaped token as a unicode string.\n",
" Returns:\n",
" A list of subtokens as unicode strings.\n",
" \"\"\"\n",
" # NOTE: This algorithm is greedy; it won't necessarily produce the \"best\"\n",
" # list of subtokens.\n",
" ret = []\n",
" start = 0\n",
" token_len = len(escaped_token)\n",
" while start < token_len:\n",
" for end in six_range(\n",
" min(token_len, start + self._max_subtoken_len), start, -1):\n",
" subtoken = escaped_token[start:end]\n",
" if subtoken in self._subtoken_string_to_id:\n",
" ret.append(subtoken)\n",
" start = end\n",
" break\n",
"\n",
" else: # Did not break\n",
" # If there is no possible encoding of the escaped token then one of the\n",
" # characters in the token is not in the alphabet. This should be\n",
" # impossible and would be indicative of a bug.\n",
" assert False, \"Token substring not found in subtoken vocabulary.\"\n",
"\n",
" return ret\n",
"\n",
" def _escaped_token_to_subtoken_ids(self, escaped_token):\n",
" \"\"\"Converts an escaped token string to a list of subtoken IDs.\n",
"\n",
" Args:\n",
" escaped_token: An escaped token as a unicode string.\n",
" Returns:\n",
" A list of subtoken IDs as integers.\n",
" \"\"\"\n",
" return [\n",
" self._subtoken_string_to_id[subtoken]\n",
" for subtoken in self._escaped_token_to_subtoken_strings(escaped_token)\n",
" ]\n",
"\n",
" @classmethod\n",
" def build_from_generator(cls,\n",
" generator,\n",
" target_size,\n",
" max_subtoken_length=None,\n",
" reserved_tokens=None):\n",
" \"\"\"Builds a SubwordTextEncoder from the generated text.\n",
"\n",
" Args:\n",
" generator: yields text.\n",
" target_size: int, approximate vocabulary size to create.\n",
" max_subtoken_length: Maximum length of a subtoken. If this is not set,\n",
" then the runtime and memory use of creating the vocab is quadratic in\n",
" the length of the longest token. If this is set, then it is instead\n",
" O(max_subtoken_length * length of longest token).\n",
" reserved_tokens: List of reserved tokens. The global variable\n",
" `RESERVED_TOKENS` must be a prefix of `reserved_tokens`. If this\n",
" argument is `None`, it will use `RESERVED_TOKENS`.\n",
"\n",
" Returns:\n",
" SubwordTextEncoder with `vocab_size` approximately `target_size`.\n",
" \"\"\"\n",
" token_counts = collections.defaultdict(int)\n",
" for item in generator:\n",
" for tok in self._encode(self.native_to_unicode(item)):\n",
" token_counts[tok] += 1\n",
" encoder = cls.build_to_target_size(\n",
" target_size, token_counts, 1, 1e3,\n",
" max_subtoken_length=max_subtoken_length,\n",
" reserved_tokens=reserved_tokens)\n",
" return encoder\n",
"\n",
" @classmethod\n",
" def build_to_target_size(cls,\n",
" target_size,\n",
" token_counts,\n",
" min_val,\n",
" max_val,\n",
" max_subtoken_length=None,\n",
" reserved_tokens=None,\n",
" num_iterations=4):\n",
" \"\"\"Builds a SubwordTextEncoder that has `vocab_size` near `target_size`.\n",
"\n",
" Uses simple recursive binary search to find a minimum token count that most\n",
" closely matches the `target_size`.\n",
"\n",
" Args:\n",
" target_size: Desired vocab_size to approximate.\n",
" token_counts: A dictionary of token counts, mapping string to int.\n",
" min_val: An integer; lower bound for the minimum token count.\n",
" max_val: An integer; upper bound for the minimum token count.\n",
" max_subtoken_length: Maximum length of a subtoken. If this is not set,\n",
" then the runtime and memory use of creating the vocab is quadratic in\n",
" the length of the longest token. If this is set, then it is instead\n",
" O(max_subtoken_length * length of longest token).\n",
" reserved_tokens: List of reserved tokens. The global variable\n",
" `RESERVED_TOKENS` must be a prefix of `reserved_tokens`. If this\n",
" argument is `None`, it will use `RESERVED_TOKENS`.\n",
" num_iterations: An integer; how many iterations of refinement.\n",
"\n",
" Returns:\n",
" A SubwordTextEncoder instance.\n",
"\n",
" Raises:\n",
" ValueError: If `min_val` is greater than `max_val`.\n",
" \"\"\"\n",
" if min_val > max_val:\n",
" raise ValueError(\"Lower bound for the minimum token count \"\n",
" \"is greater than the upper bound.\")\n",
" if target_size < 1:\n",
" raise ValueError(\"Target size must be positive.\")\n",
"\n",
" if reserved_tokens is None:\n",
" reserved_tokens = RESERVED_TOKENS\n",
"\n",
" def bisect(min_val, max_val):\n",
" \"\"\"Bisection to find the right size.\"\"\"\n",
" present_count = (max_val + min_val) // 2\n",
" #tf.logging.info(\"Trying min_count %d\" % present_count)\n",
" subtokenizer = cls()\n",
" subtokenizer.build_from_token_counts(\n",
" token_counts, present_count, num_iterations,\n",
" max_subtoken_length=max_subtoken_length,\n",
" reserved_tokens=reserved_tokens)\n",
"\n",
" # Being within 1% of the target size is ok.\n",
" is_ok = abs(subtokenizer.vocab_size - target_size) * 100 < target_size\n",
" # If min_val == max_val, we can't do any better than this.\n",
" if is_ok or min_val >= max_val or present_count < 2:\n",
" return subtokenizer\n",
"\n",
" if subtokenizer.vocab_size > target_size:\n",
" other_subtokenizer = bisect(present_count + 1, max_val)\n",
" else:\n",
" other_subtokenizer = bisect(min_val, present_count - 1)\n",
"\n",
" if other_subtokenizer is None:\n",
" return subtokenizer\n",
"\n",
" if (abs(other_subtokenizer.vocab_size - target_size) <\n",
" abs(subtokenizer.vocab_size - target_size)):\n",
" return other_subtokenizer\n",
" return subtokenizer\n",
"\n",
" return bisect(min_val, max_val)\n",
"\n",
" def build_from_token_counts(self,\n",
" token_counts,\n",
" min_count,\n",
" num_iterations=4,\n",
" reserved_tokens=None,\n",
" max_subtoken_length=None):\n",
" \"\"\"Train a SubwordTextEncoder based on a dictionary of word counts.\n",
"\n",
" Args:\n",
" token_counts: a dictionary of Unicode strings to int.\n",
" min_count: an integer - discard subtokens with lower counts.\n",
" num_iterations: an integer. how many iterations of refinement.\n",
" reserved_tokens: List of reserved tokens. The global variable\n",
" `RESERVED_TOKENS` must be a prefix of `reserved_tokens`. If this\n",
" argument is `None`, it will use `RESERVED_TOKENS`.\n",
" max_subtoken_length: Maximum length of a subtoken. If this is not set,\n",
" then the runtime and memory use of creating the vocab is quadratic in\n",
" the length of the longest token. If this is set, then it is instead\n",
" O(max_subtoken_length * length of longest token).\n",
"\n",
" Raises:\n",
" ValueError: if reserved is not 0 or len(RESERVED_TOKENS). In this case, it\n",
" is not clear what the space is being reserved for, or when it will be\n",
" filled in.\n",
" \"\"\"\n",
" if reserved_tokens is None:\n",
" reserved_tokens = RESERVED_TOKENS\n",
" else:\n",
" # There is not complete freedom in replacing RESERVED_TOKENS.\n",
" for default, proposed in zip(RESERVED_TOKENS, reserved_tokens):\n",
" if default != proposed:\n",
" raise ValueError(\"RESERVED_TOKENS must be a prefix of \"\n",
" \"reserved_tokens.\")\n",
"\n",
" # Initialize the alphabet. Note, this must include reserved tokens or it can\n",
" # result in encoding failures.\n",
" alphabet_tokens = chain(iterkeys(token_counts),\n",
" [self.native_to_unicode(t) for t in reserved_tokens])\n",
"\n",
" self._init_alphabet_from_tokens(alphabet_tokens)\n",
"\n",
" # Bootstrap the initial list of subtokens with the characters from the\n",
" # alphabet plus the escaping characters.\n",
" self._init_subtokens_from_list(list(self._alphabet),\n",
" reserved_tokens=reserved_tokens)\n",
"\n",
" # We build iteratively. On each iteration, we segment all the words,\n",
" # then count the resulting potential subtokens, keeping the ones\n",
" # with high enough counts for our new vocabulary.\n",
" if min_count < 1:\n",
" min_count = 1\n",
" for i in six_range(num_iterations):\n",
" #tf.logging.info(\"Iteration {0}\".format(i))\n",
"\n",
" # Collect all substrings of the encoded token that break along current\n",
" # subtoken boundaries.\n",
" subtoken_counts = collections.defaultdict(int)\n",
" for token, count in iteritems(token_counts):\n",
" iter_start_time = time.time()\n",
" escaped_token = self._escape_token(token, self._alphabet)\n",
" subtokens = self._escaped_token_to_subtoken_strings(escaped_token)\n",
" start = 0\n",
" for subtoken in subtokens:\n",
" last_position = len(escaped_token) + 1\n",
" if max_subtoken_length is not None:\n",
" last_position = min(last_position, start + max_subtoken_length)\n",
"\n",
" for end in six_range(start + 1, last_position):\n",
" new_subtoken = escaped_token[start:end]\n",
" subtoken_counts[new_subtoken] += count\n",
" start += len(subtoken)\n",
" iter_time_secs = time.time() - iter_start_time\n",
" if iter_time_secs > 0.1:\n",
" print(u\"Processing token [{0}] took {1} seconds, consider \"\n",
" \"setting Text2TextProblem.max_subtoken_length to a \"\n",
" \"smaller value.\".format(token, iter_time_secs))\n",
"\n",
" # Array of sets of candidate subtoken strings, by length.\n",
" len_to_subtoken_strings = []\n",
" for subtoken_string, count in iteritems(subtoken_counts):\n",
" lsub = len(subtoken_string)\n",
" if count >= min_count:\n",
" while len(len_to_subtoken_strings) <= lsub:\n",
" len_to_subtoken_strings.append(set())\n",
" len_to_subtoken_strings[lsub].add(subtoken_string)\n",
"\n",
" # Consider the candidates longest to shortest, so that if we accept\n",
" # a longer subtoken string, we can decrement the counts of its prefixes.\n",
" new_subtoken_strings = []\n",
" for lsub in six_range(len(len_to_subtoken_strings) - 1, 0, -1):\n",
" subtoken_strings = len_to_subtoken_strings[lsub]\n",
" for subtoken_string in subtoken_strings:\n",
" count = subtoken_counts[subtoken_string]\n",
" if count >= min_count:\n",
" # Exclude alphabet tokens here, as they must be included later,\n",
" # explicitly, regardless of count.\n",
" if subtoken_string not in self._alphabet:\n",
" new_subtoken_strings.append((count, subtoken_string))\n",
" for l in six_range(1, lsub):\n",
" subtoken_counts[subtoken_string[:l]] -= count\n",
"\n",
" # Include the alphabet explicitly to guarantee all strings are encodable.\n",
" new_subtoken_strings.extend((subtoken_counts.get(a, 0), a)\n",
" for a in self._alphabet)\n",
" new_subtoken_strings.sort(reverse=True)\n",
"\n",
" # Reinitialize to the candidate vocabulary.\n",
" new_subtoken_strings = [subtoken for _, subtoken in new_subtoken_strings]\n",
" if reserved_tokens:\n",
" escaped_reserved_tokens = [\n",
" self._escape_token(self.native_to_unicode(t), self._alphabet)\n",
" for t in reserved_tokens\n",
" ]\n",
" new_subtoken_strings = escaped_reserved_tokens + new_subtoken_strings\n",
"\n",
" self._init_subtokens_from_list(new_subtoken_strings)\n",
" #tf.logging.info(\"vocab_size = %d\" % self.vocab_size)\n",
"\n",
" @property\n",
" def all_subtoken_strings(self):\n",
" return tuple(self._all_subtoken_strings)\n",
"\n",
" def dump(self):\n",
" \"\"\"Debugging dump of the current subtoken vocabulary.\"\"\"\n",
" subtoken_strings = [(i, s)\n",
" for s, i in iteritems(self._subtoken_string_to_id)]\n",
" print(u\", \".join(u\"{0} : '{1}'\".format(i, s)\n",
" for i, s in sorted(subtoken_strings)))\n",
"\n",
" def _init_subtokens_from_list(self, subtoken_strings, reserved_tokens=None):\n",
" \"\"\"Initialize token information from a list of subtoken strings.\n",
"\n",
" Args:\n",
" subtoken_strings: a list of subtokens\n",
" reserved_tokens: List of reserved tokens. We must have `reserved_tokens`\n",
" as None or the empty list, or else the global variable `RESERVED_TOKENS`\n",
" must be a prefix of `reserved_tokens`.\n",
"\n",
" Raises:\n",
" ValueError: if reserved is not 0 or len(RESERVED_TOKENS). In this case, it\n",
" is not clear what the space is being reserved for, or when it will be\n",
" filled in.\n",
" \"\"\"\n",
" if reserved_tokens is None:\n",
" reserved_tokens = []\n",
"\n",
" if reserved_tokens:\n",
" self._all_subtoken_strings = reserved_tokens + subtoken_strings\n",
" else:\n",
" self._all_subtoken_strings = subtoken_strings\n",
"\n",
" # we remember the maximum length of any subtoken to avoid having to\n",
" # check arbitrarily long strings.\n",
" self._max_subtoken_len = max([len(s) for s in subtoken_strings])\n",
" self._subtoken_string_to_id = {\n",
" s: i + len(reserved_tokens)\n",
" for i, s in enumerate(subtoken_strings) if s\n",
" }\n",
" # Initialize the cache to empty.\n",
" self._cache_size = 2 ** 20\n",
" self._cache = [(None, None)] * self._cache_size\n",
"\n",
" def _init_alphabet_from_tokens(self, tokens):\n",
" \"\"\"Initialize alphabet from an iterable of token or subtoken strings.\"\"\"\n",
" # Include all characters from all tokens in the alphabet to guarantee that\n",
" # any token can be encoded. Additionally, include all escaping characters.\n",
" self._alphabet = {c for token in tokens for c in token}\n",
" self._alphabet |= self._ESCAPE_CHARS\n",
"\n",
" def _load_from_file_object(self, f):\n",
" \"\"\"Load from a file object.\n",
"\n",
" Args:\n",
" f: File object to load vocabulary from\n",
" \"\"\"\n",
" subtoken_strings = []\n",
" for line in f:\n",
" s = line.rstrip()\n",
" # Some vocab files wrap words in single quotes, but others don't\n",
" if ((s.startswith(\"'\") and s.endswith(\"'\")) or\n",
" (s.startswith(\"\\\"\") and s.endswith(\"\\\"\"))):\n",
" s = s[1:-1]\n",
" subtoken_strings.append(self.native_to_unicode(s))\n",
" self._init_subtokens_from_list(subtoken_strings)\n",
" self._init_alphabet_from_tokens(subtoken_strings)\n",
"\n",
" def _load_from_file(self, filename):\n",
" \"\"\"Load from a vocab file.\"\"\"\n",
" if not Path(filename).exists():\n",
" raise ValueError(\"File %s not found\" % filename)\n",
" with Path(filename).open() as f:\n",
" self._load_from_file_object(f)\n",
"\n",
" def store_to_file(self, filename, add_single_quotes=True):\n",
" with Path(filename).open('w') as f:\n",
" for subtoken_string in self._all_subtoken_strings:\n",
" if add_single_quotes:\n",
" f.write(\"'\" + self.unicode_to_native(subtoken_string) + \"'\\n\")\n",
" else:\n",
" f.write(self.unicode_to_native(subtoken_string) + \"\\n\")\n",
"\t\t\n",
" def unicode_to_native(self,s):\n",
" if PY2:\n",
" return s.encode(\"utf-8\") if is_unicode(s) else s\n",
" else:\n",
" return s\n",
"\n",
" def _escape_token(self,token, alphabet):\n",
" if not isinstance(token, text_type):\n",
" raise ValueError(\"Expected string type for token, got %s\" % type(token))\n",
"\n",
" token = token.replace(u\"\\\\\", u\"\\\\\\\\\").replace(u\"_\", u\"\\\\u\")\n",
" ret = [c if c in alphabet and c != u\"\\n\" else r\"\\%d;\" % ord(c) for c in token]\n",
" return u\"\".join(ret) + \"_\"\n",
"\n",
"\n",
" def _unescape_token(self,escaped_token):\n",
" def match(m):\n",
" if m.group(1) is None:\n",
" return u\"_\" if m.group(0) == u\"\\\\u\" else u\"\\\\\"\n",
"\n",
" try:\n",
" return unichr(int(m.group(1)))\n",
" except (ValueError, OverflowError) as _:\n",
" return u\"\\u3013\" # Unicode for undefined character.\n",
"\n",
" trimmed = escaped_token[:-1] if escaped_token.endswith(\"_\") else escaped_token\n",
" return self._UNESCAPE_REGEX.sub(match, trimmed)\n",
"\n",
" def _encode(self,text):\n",
" if not text:\n",
" return []\n",
" ret = []\n",
" token_start = 0\n",
" # Classify each character in the input string\n",
" is_alnum = [c in self._ALPHANUMERIC_CHAR_SET for c in text]\n",
" for pos in six_range(1, len(text)):\n",
" if is_alnum[pos] != is_alnum[pos - 1]:\n",
" token = text[token_start:pos]\n",
" if token != u\" \" or token_start == 0:\n",
" ret.append(token)\n",
" token_start = pos\n",
" final_token = text[token_start:]\n",
" ret.append(final_token)\n",
" return ret\n",
"\n",
" def _decode(self,tokens):\n",
" token_is_alnum = [t[0] in self._ALPHANUMERIC_CHAR_SET for t in tokens]\n",
" ret = []\n",
" for i, token in enumerate(tokens):\n",
" if i > 0 and token_is_alnum[i - 1] and token_is_alnum[i]:\n",
" ret.append(u\" \")\n",
" ret.append(token)\n",
" #if self.add_bos: ret.pop()\n",
" return TitledStr(\"\".join(ret))"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"id": "Bt8nNrbjW8jV"
},
"outputs": [],
"source": [
"wonder = \"I wonder how the moon got it's shine?\"\n",
"tok = SubwordTextEncoder(filename='./vocab.translate_ende_wmt32k.32768.subwords', add_bos=True, seq_len=256)\n",
"tok_wonder = tok(wonder)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 195
},
"id": "-KL8tFoRXLhN",
"outputId": "8aeae0fc-05e0-4964-90a4-3eb43795967d"
},
"outputs": [],
"source": [
"# assert type(tok_wonder) == LMTensorText\n",
"# assert len(tok_wonder) == 12\n",
"# assert tok.decode(tok_wonder) == wonder"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"id": "Mk_I8YSZyVZG"
},
"outputs": [
{
"data": {
"text/plain": [
"(LMTensorText([ 0, 44, 7200, 309, 4, 17279, 3512, 40, 85, 14,\n",
" 23111, 529, 102]),\n",
" \"<pad>Iwonder how the moon got it's shine?\",\n",
" \"I wonder how the moon got it's shine?\")"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tok_wonder, tok.decode(tok_wonder), wonder"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"id": "MaYFLmnOXHVR"
},
"outputs": [],
"source": [
"#!pip install -qq datasets\n",
"#from datasets import load_dataset\n",
"#train_dataset = load_dataset('wmt_t2t')"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"id": "6b3JYed8lUd5"
},
"outputs": [],
"source": [
"#test_df = pd.DataFrame(train_dataset['test']['translation'], columns=train_dataset['test']['translation'][0].keys())\n",
"#val_df = pd.DataFrame(train_dataset['validation']['translation'], columns=train_dataset['validation']['translation'][0].keys())\n",
"#train_df = pd.DataFrame(train_dataset['train']['translation'], columns=train_dataset['train']['translation'][0].keys())"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"id": "b3DSPzl5_UNV"
},
"outputs": [],
"source": [
"#train_df.to_feather('./train_df')\n",
"#val_df.to_feather('./val_df')\n",
"#test_df.to_feather('./test_df')"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"id": "z7VSN7iqZBVX"
},
"outputs": [],
"source": [
"val_df=pd.read_feather('./val_df')\n",
"train_df=pd.read_feather('./train_df')\n",
"test_df=pd.read_feather('./test_df')"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 670
},
"id": "F49Ihu5Kmahk",
"outputId": "45f900bd-8429-4ca4-ae65-3c90640ddf5d"
},
"outputs": [
{
"data": {
"text/plain": [
"4592289"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(train_df)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"id": "GZFbMearq3G2"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: user 11.6 s, sys: 771 ms, total: 12.4 s\n",
"Wall time: 12.1 s\n"
]
}
],
"source": [
"%%time\n",
"## Replace test_df with train_df here\n",
"#\n",
"df=pd.concat([ test_df, val_df], ignore_index=True)#test_df #['en\n",
"df=pd.concat([train_df, val_df], ignore_index=True)\n",
"\n",
"cut = int(len(df)*0.8)\n",
"splits = range_of(df)[:cut], range_of(df[cut:])\n",
"\n",
"df['en_lens'] = df['en'].str.len()\n",
"df['de_lens'] = df['de'].str.len()\n",
"\n",
"def add_eos(text):\n",
" return text + f' <EOS>'\n",
"\n",
"def add_pad(text):\n",
" return f'<pad> '+ text\n",
"\n",
"en_tfms = [ColReader(\"en\"), add_eos, tok]\n",
"de_tfms = [ColReader(\"de\"), add_eos, tok]\n",
"\n",
"# dsets = Datasets(df, [en_tfms, de_tfms], splits=splits, dl_type = srtd_dl, dl_kwargs = dl_kwargs)\n",
"dsets = Datasets(df, [en_tfms, de_tfms], splits=splits)\n",
"\n",
"pad_seq2seq = partial(pad_input, pad_idx=tok.PAD_ID, pad_fields=[0,1])"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(4595289, 35861)"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(dsets), max(df['en_lens'].values)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: user 4.91 s, sys: 441 ms, total: 5.35 s\n",
"Wall time: 5.35 s\n"
]
}
],
"source": [
"%%time\n",
"\n",
"srtd_dl = partial(SortedDL, shuffle=True, res=df['en_lens'].values[splits[0]])\n",
"\n",
"dl_kwargs = [{},{'val_res': df['en_lens'].values[splits[1]]}]\n",
"\n",
"dls = dsets.dataloaders(bs=16, before_batch=pad_seq2seq, dl_type = srtd_dl, dl_kwargs = dl_kwargs)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"((16, 257), (16, 257))"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"o = dls.one_batch()\n",
"o[0].size(), o[1].size()"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 636
},
"id": "j2O83KCxrt03",
"outputId": "24e614b9-d8b5-40be-dc41-e0bb943fc332"
},
"outputs": [
{
"data": {
"text/html": [
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>text</th>\n",
" <th>text_</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>&lt;pad&gt;theorem (7) N!ai, the Story of a !Kung Woman (8) N!xau (9) N!xau G!kau (10) N$ (11) N&amp;H (12) N&amp;J Quarterly (13) N&amp;NE (14) N&amp;O (15) N&amp;S (16) N&amp;W (17) N&amp;W \"M\" Series 4-8-0 (18) N'-Formylkynurenine (19) N'-formylkynurenine (20) N'-nitrosonornicotine (21) N'Astirh (22) N'Avoue Jamais (23) N'Bushe Wright (24) N'Dalantando (25) N'Dalatando (26) N'Dali (27) N'Dama (28) N'Dayi Kalenga (29) N'Dayi Kalenga (footballer born 1967) (30) N'Dayi Kalenga (footballer born 1978) (31) N'Dea Davenport (32) N'Deaye Ba</td>\n",
" <td>&lt;pad&gt;(3) N!faculty (4) N!xau (5) N$ (6) N&amp;ER (7) N&amp;R (8) N&amp;W (9) N'Bushe Wright (10) N'Dea Davenport (11) N'Diaye (12) N'Diaye Papa Waigo (13) N'Diayé Papa Waigo (14) N'Diefi (15) N'Diwa (16) N'Djamena (17) N'Djamena-Dschibuti-Highway (18) N'Do (19) N'Dongo (20) N'Dorola (21) N'Drangheta (22) N'EX (23) N'Game (24) N'Gatta Coulibaly (25) N'Goyo (26) N'Guigmi (Departement) (27) N'Ko (28) N'Kufo (29) N'Sync (30) N'djamena (31) N'zi-Comoé (32) N*E*R*D (33) N,N'-Bis</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>&lt;pad&gt;Thenext item is the debate on the recommendation for second reading (A4-0218/97) by Mrs Hautala, on behalf of the Committee on Economic and Monetary Affairs and Industrial Policy on the common position adopted by the Council with a view to the adoption of a European Parliament and Council Directive amending Council Directives 74/150/EEC, 74/151/EEC, 74/152/EEC, 74/346/EEC, 74/347/EEC, 75/321/EEC, 75/322/EEC, 76/432/EEC, 76/763/EEC, 77/311/EEC, 77/537/EEC, 78/764/EEC, 78/933/EEC, 79/532/EEC, 79/533/EEC, 80/720/EEC, 86/297/EEC, 86/415/EEC and 89/173/EEC relating to the maximum design speed of wheeled agricultural or forestry tractors (C4-0150/97-96/0129(COD)). &lt;EOS&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;</td>\n",
" <td>&lt;pad&gt;Nachder Tagesordnung folgt die Aussprache über die Empfehlung für die zweite Lesung (A40218/97) von Frau Hautala im Namen des Ausschusses für Wirtschaft, Währung und Industriepolitik betreffend den Gemeinsamen Standpunkt des Rates im Hinblick auf den Erlaß der Richtlinie des Europäischen Parlaments und des Rates zur Änderung der Richtlinien des Rates 74/150/EWG, 74/151/EWG, 74/152/EWG, 74/346/EWG, 74/347/EWG, 75/321/EWG, 75/322/EWG, 76/432/EWG, 76/763/EWG, 77/311/EWG, 77/537/EWG, 78/764/EWG, 78/933/EWG, 79/532/EWG, 79/533/EWG, 80/720/EWG, 86/297/EWG, 86/415/EWG und 89/173/EWG über die bauartbedingte Höchstgeschwindigkeit von land- und forstwirtschaftlichen Zugmaschinen auf Rädern (C4-0150/97-96/0129(COD)). &lt;EOS&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;&lt;pad&gt;</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: user 2.54 s, sys: 71.3 ms, total: 2.61 s\n",
"Wall time: 2.61 s\n"
]
}
],
"source": [
"%%time\n",
"dls.show_batch(max_n=2)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"id": "hwLENqGGcGnO"
},
"outputs": [],
"source": [
"# xb,yb=dls.one_batch()\n",
"# tok.decode(yb[0].detach().numpy())"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"id": "BClhp-cEcsUo"
},
"outputs": [],
"source": [
"enc_vocab_sz=tok.vocab_size\n",
"dec_vocab_sz=tok.vocab_size\n",
"\n",
"d_model = 768\n",
"# d_ff = 2048"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"id": "e_IME_kwkBGe"
},
"outputs": [],
"source": [
"class CombineInputOutputCallback(Callback):\n",
" '''Callback to combine the input and target text into self.xb'''\n",
" def __init__(self): pass\n",
" def before_batch(self): \n",
" self.learn.xb = (self.xb[0], self.yb[0][:, :-1])\n",
" \n",
"\n",
"class RemoveEOSCallback(Callback):\n",
" '''\n",
" Shift the target presented to the model during training to remove the \"eos\" token as \n",
" we don't want the model to learn to translate EOS when it sees EOS.\n",
" \n",
" In practice we actually mask the EOS token as due to batching the last token will often be a <pad> token,\n",
" not EOS\n",
" '''\n",
" def __init__(self, eos_idx): self.eos_idx=eos_idx\n",
" def before_batch(self): \n",
" eos_mask=(self.learn.xb[1]!=self.eos_idx)\n",
" sz=torch.tensor(self.learn.xb[1].size())\n",
" sz[1]=sz[1]-1\n",
" self.learn.xb = (self.learn.xb[0], self.learn.xb[1][eos_mask].view((sz[0],sz[1])))\n",
" print(self.learn.xb[0])\n",
"\n",
"\n",
"class LossTargetShiftCallback(Callback):\n",
" '''\n",
" Shift the target shown to the loss to exclude the \"bos\" token as the first token we want predicted\n",
" should be an actual word, not the \"bos\" token (as we have already given the model \"bos\" )\n",
" '''\n",
" def __init__(self): pass\n",
" def after_pred(self):\n",
" self.learn.yb = (self.learn.yb[0][:,1:],)\n"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"# from reformer_fastai.transformer import TransformerEncDec\n",
"# # TransformerEncDec??"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [],
"source": [
"from reformer_fastai.layers import TransformerEmbedding\n",
"from reformer_fastai.transformer import TransformerEncoderBlock, TransformerDecoderBlock, TransformerEncoder, TransformerDecoder\n",
"from reformer_fastai.core import *"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [],
"source": [
"class TransformerEncDec(Module):\n",
" \"\"\"\n",
" Basic Transformer Encoder-Decoder model\n",
" Parameters:\n",
" * enc_vocab_sz: int - source vocab size\n",
" * dec_vocab_sz: int - target vocab size\n",
" * d_model: int - inner dimension of the model\n",
" * n_enc_layers: int (default: 6)\n",
" * n_dec_layers: int (default: 6)\n",
" * heads: int (default: 8)\n",
" * d_ff: int - inner dimension of the pointwise FeedForward net, if None defaults to 4*d_model\n",
" * attn_dropout: float - attention dropout\n",
" * ff_dropout: float - feed-forward dropout\n",
" * emb_dropout: float - embedding dropout\n",
" * max_seq_len: int (default: 512)\n",
" * prenorm: bool - whether to use PreNorm or PostNorm\n",
" * attn_bias: bool - whether to allow biases in attention projection layers\n",
" * pad_idx: int - padding token id, if pad_idx is provided, and no mask/context_mask are\n",
" passed to forward method will be used to generate padding masks\n",
" * tie_weights: bool - if True target embedding weights are used for computation output projection\n",
" * shared_emb: bool - if True encoder and decoder will use shared embedding layer\n",
" * pos_enc: str from {'absolute', 'fixed', 'axial'} - type of positional encoding to use\n",
" * axial_shape: tuple - required if 'axial' positional encoding are used, should be factors of\n",
" max_seq_len\n",
" * axial_emb_dims: tuple - [optional] axial embedding components, should sum to d_model\n",
" Inputs:\n",
" * src - source input ids, shape [bs, src_sl]\n",
" * tgt - target input ids, shape [bs, tgt_sl]\n",
" * src_mask - optional boolean source mask, shape [bs, src_sl]\n",
" * tgt_mask - optional boolean target mask, shape [bs, tgt_sl]\n",
" Returns:\n",
" * logits - target token logits, shape [bs, tgt_sl, tgt_vocab_sz]\n",
" \"\"\"\n",
" def __init__(self,\n",
" enc_vocab_sz,\n",
" dec_vocab_sz,\n",
" d_model,\n",
" n_enc_layers=6,\n",
" n_dec_layers=6,\n",
" heads=8,\n",
" d_ff=None,\n",
" pad_idx=None,\n",
" tie_weights=True,\n",
" shared_emb = False,\n",
" attn_dropout=0.1,\n",
" ff_dropout=0.1,\n",
" emb_dropout=0.1,\n",
" prenorm=False,\n",
" attn_bias=False,\n",
" comb_attn=False,\n",
" pos_enc='absolute',\n",
" max_seq_len=512,\n",
" axial_shape=None,\n",
" axial_emb_dims=None):\n",
" store_attr('max_seq_len, n_enc_layers, n_dec_layers, pad_idx')\n",
" self.enc_emb = TransformerEmbedding(enc_vocab_sz, d_model, max_seq_len, dropout=emb_dropout, pos_enc=pos_enc,\n",
" axial_shape=axial_shape, axial_emb_dims=axial_emb_dims)\n",
" if shared_emb:\n",
" assert (enc_vocab_sz == dec_vocab_sz), \"Encoder and decoder vocab size doesn't match\"\n",
" self.dec_emb = self.enc_emb\n",
" else:\n",
" self.dec_emb = TransformerEmbedding(dec_vocab_sz, d_model, max_seq_len, dropout=emb_dropout, pos_enc=pos_enc,\n",
" axial_shape=axial_shape, axial_emb_dims=axial_emb_dims)\n",
" final_norm = nn.LayerNorm if prenorm else None\n",
" self.encoder = TransformerEncoder(d_model, n_enc_layers, heads, d_ff=d_ff, attn_dropout=attn_dropout, ff_dropout=ff_dropout,\n",
" prenorm=prenorm, attn_bias=attn_bias, final_norm=final_norm, causal=False)\n",
" self.decoder = TransformerDecoder(d_model, n_dec_layers, heads, d_ff=d_ff, attn_dropout=attn_dropout, ff_dropout=ff_dropout,\n",
" prenorm=prenorm, comb_attn=comb_attn, attn_bias=attn_bias, final_norm=final_norm)\n",
" self.proj = nn.Linear(d_model, dec_vocab_sz)\n",
" if tie_weights: self.proj.weight = self.dec_emb.emb.weight\n",
"\n",
" def forward(self, src, tgt, src_mask=None, tgt_mask=None):\n",
" src_mask = default(src_mask, self.get_padding_mask(src))\n",
" tgt_mask = default(tgt_mask, self.get_padding_mask(tgt))\n",
" enc = self.encoder(self.enc_emb(src), mask=src_mask)\n",
" out = self.decoder(self.dec_emb(tgt), context=enc, mask=tgt_mask, context_mask=src_mask)\n",
" return self.proj(out)\n",
"\n",
" def get_padding_mask(self, x):\n",
" if self.pad_idx is None: return None\n",
" return (x != self.pad_idx)\n",
"\n",
" #TODO add beam search and refactor\n",
" @torch.no_grad()\n",
" def generate(self, src,\n",
" src_mask=None,\n",
" max_len=50,\n",
" temperature=1.,\n",
" method = 'top_k',\n",
" top_k = 20,\n",
" top_p = 0.9,\n",
" early_stopping=False,\n",
" bos_idx=2, # TODO change to match future usecases\n",
" eos_idx=None):\n",
" self.to(src.device) #TODO test for potential problems\n",
" self.eval()\n",
" thresh = top_k if method=='top_k' else top_p\n",
" sampler = _sampler[method]\n",
" src = expand_dim1(src)\n",
" bs = src.size(0)\n",
" inp = src.new_full((bs, 1), bos_idx) #start with bos tokens\n",
" src_mask = default(src_mask, self.get_padding_mask(src))\n",
" enc = self.encoder(self.enc_emb(src), mask = src_mask)\n",
" out = inp\n",
" for _ in range(max_len):\n",
" x = out[:, -self.max_seq_len:]\n",
" dec = self.decoder(self.dec_emb(out), context=enc)\n",
" logits = self.proj(dec)[:, -1, :]\n",
" if method == 'greedy':\n",
" sample = sampler(logits)\n",
" else:\n",
" filtered_logits = sampler(logits, thresh)\n",
" probs = F.softmax(filtered_logits / temperature, dim=-1)\n",
" sample = torch.multinomial(probs, 1)\n",
"\n",
" out = torch.cat((out, sample), dim=-1)\n",
"\n",
" if (early_stopping and\n",
" ((sample == eos_idx).all() or\n",
" (sample == self.pad_idx).all())):\n",
" break\n",
" #TODO mb output cleanup\n",
" return out\n",
"\n",
" def store_attention(self, layer_ids=None, store_encoder=False, store_decoder=True):\n",
" #defaults to storing attention for all layers\n",
" layer_ids = default(layer_ids, list(range(self.n_enc_layers)))\n",
" for module in self.children():\n",
" if isinstance(module, TransformerEncoder) and store_encoder:\n",
" for i, l in enumerate(module.layers):\n",
" if i in layer_ids:\n",
" for m in l.modules():\n",
" if isinstance(m, (ScaledDotProdAttention)):\n",
" m.store_attention = True\n",
" elif isinstance(module, TransformerDecoder) and store_encoder:\n",
" for i, l in enumerate(module.layers):\n",
" if i in layer_ids:\n",
" for m in l.modules():\n",
" if isinstance(m, (ScaledDotProdAttention)):\n",
" m.store_attention = True\n",
" #TODO mb separate encoder and decoder attention\n",
" def get_attention_matrix(self, get_encoder=False, get_decoder=True):\n",
" res = []\n",
" if get_encoder:\n",
" for m in self.encoder.modules():\n",
" if isinstance(m, (ScaledDotProdAttention)):\n",
" attention = getattr(m, 'attention', None)\n",
" if attention is not None:\n",
" res.append(attention)\n",
" # reset stored attention\n",
" m.attention = None\n",
" m.store_attention = False\n",
" if get_decoder:\n",
" for m in self.decoder.modules():\n",
" if isinstance(m, (ScaledDotProdAttention)):\n",
" attention = getattr(m, 'attention', None)\n",
" if attention is not None:\n",
" res.append(attention)\n",
" # reset stored attention\n",
" m.attention = None\n",
" m.store_attention = False\n",
" return res"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"# # cbs = [CombineInputOutputCallback(), LossTargetShiftCallback(), TerminateOnNaNCallback()] # RemoveEOSCallback(dls.o2i[0][EOS]),\n",
"# cbs = [CombineInputOutputCallback(), LossTargetShiftCallback()] # RemoveEOSCallback(dls.o2i[0][EOS]),\n",
"\n",
"# model = TransformerEncDec(enc_vocab_sz, dec_vocab_sz, d_model, pad_idx=tok.PAD_ID, max_seq_len=256, pos_enc='absolute', \n",
"# attn_dropout=0, ff_dropout=0, emb_dropout=0, prenorm=False, tie_weights=True, shared_emb=True)\n",
" \n",
" \n",
"# learn = Learner(dls, model, loss_func=CrossEntropyLossFlat(ignore_index=tok.PAD_ID), cbs=cbs,\n",
"# metrics=[accuracy, CorpusBLEUMetric()]).to_native_fp16()\n",
"# total_params(learn.model)\n",
" \n",
"# # learn = Learner(dls, TransformerEncDec(enc_vocab_sz, dec_vocab_sz, d_model, pad_idx=tok.PAD_ID, max_seq_len=256, pos_enc='absolute', \n",
"# # attn_dropout=0, ff_dropout=0, emb_dropout=0, prenorm=False, tie_weights=True, shared_emb=True),\n",
"# # loss_func=CrossEntropyLossFlat(ignore_index=tok.PAD_ID), cbs=cbs,\n",
"# # metrics=[accuracy, CorpusBLEUMetric()]).to_native_fp16()\n",
"# # total_params(learn.model)"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "8VqQ-LATr2Qy",
"outputId": "88c610f3-5389-4148-a8e2-7ccaa29de786"
},
"outputs": [
{
"data": {
"text/plain": [
"(125104044, True)"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# from reformer_fastai.transformer import TransformerEncDec\n",
"cbs = [CombineInputOutputCallback(),LossTargetShiftCallback()]# RemoveEOSCallback(eos_idx=tok.EOS_ID)]#,\n",
"\n",
"model = TransformerEncDec(enc_vocab_sz, dec_vocab_sz, d_model=d_model, heads=8, \n",
" max_seq_len=256, pad_idx=tok.PAD_ID, tie_weights=True, shared_emb=True,\n",
" attn_dropout=0.0, ff_dropout=0.0, emb_dropout=0.0,\n",
"# pos_enc='fixed', d_ff=d_ff, comb_attn=False)\n",
" pos_enc='fixed', comb_attn=False)\n",
"\n",
"learn = Learner(dls, model,\n",
" loss_func=CrossEntropyLossFlat(ignore_index=tok.PAD_ID), cbs=cbs,\n",
" metrics=[accuracy, CorpusBLEUMetric()]).to_native_fp16()\n",
"total_params(learn.model)"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 300
},
"id": "BDBj0TL6w370",
"outputId": "891f2e78-72cf-4ad8-83b6-cab58ffad9cf"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"█\r"
]
},
{
"data": {
"text/plain": [
"SuggestedLRs(lr_min=0.03019951581954956, lr_steep=0.25118863582611084)"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAYgAAAEKCAYAAAAIO8L1AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/d3fzzAAAACXBIWXMAAAsTAAALEwEAmpwYAAAsMUlEQVR4nO3deXxV5b3v8c8vIQOEQCAJQ4AwCSiiDEZwYtAeFdE6naPVWmurlautba1tr3rb0/b21HNs7elxqF5rq1WrglqroiCKVgWsA4PMoCBjSCAJQ0IgJCT53T/2xsa4ExLJ3mvv5Pt+vfJir7XX2vubDeSX53nWeh5zd0RERBpLCjqAiIjEJxUIERGJSAVCREQiUoEQEZGIVCBERCQiFQgREYmoU9AB2lJOTo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Ls3OeWzu1eZ2TJCM4JiZtcD08M5NwBXA2MIrd0w2cx+Cvxr+PTPfZ9f9HOTjkctCOmIHgK+6+4nAT8CHgjvXwicEv6tfSbwvxuccxKh+fu/Gt4+ltA05OOBn5tZSoT3GQvcTOi3+iHA6WaWDvwBOM/dzyD0w7tZZtYDGMY/p2v/m7uf7O6jgbWEpnL4B6G5fX7s7mPc/ZNmvk+RFlELQjoUM+sKnAY8G1pTBvjnQkT9gafNrC+h3843NTh1lrtXNdie7e7VQLWZlRBa8a7xkqgfuHth+H2XEWqBVAIb3f3wa88g1BqIZKKZrQBGAHe6+47w/lFm9itCa2R0BV5t5fcp0iIqENLRJAF73X1MhOfuA37n7rMadBEdtr/RsdUNHtcR+f9SpGMirQvQlAXufoGZDQcWmtnz7r4MeBS42N2XhxcjmhLh3Oa+T5EWUReTdCgeWjJ2k5ldBqGlKc1sdPjp7sD28ONrohRhHTCkwZKUXznSCe7+MfBfwK3hXZlAcbhb66oGh+4LP3ek71OkRVQgpL3rYmaFDb5uIfRD9TozWw6sBi4KH/sLQl0yCwgNILe5cDfVt4G5ZrYQ2AmUt+DUB4FJZjYY+HfgfWAeoYJz2Ezgx+FLY4fS9Pcp0iKa7lskxsysq7tXWmhw4H5gvbv/T9C5RBpTC0Ik9q4PD1qvJtSt9Ydg44hEphaEiIhEpBaEiIhEpAIhIiIRqUCIiEhEKhAiIhKRCoSIiESkAiEiIhH9fxQsrtgEWhDtAAAAAElFTkSuQmCC\n",
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"learn.lr_find()"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"\u001b[34m\u001b[1mwandb\u001b[0m: Currently logged in as: \u001b[33mmorgan\u001b[0m (use `wandb login --relogin` to force relogin)\n"
]
},
{
"data": {
"text/html": [
"\n",
" Tracking run with wandb version 0.10.12<br/>\n",
" Syncing run <strong style=\"color:#cdcd00\">wmt14_transformer_swt</strong> to <a href=\"https://wandb.ai\" target=\"_blank\">Weights & Biases</a> <a href=\"https://docs.wandb.com/integrations/jupyter.html\" target=\"_blank\">(Documentation)</a>.<br/>\n",
" Project page: <a href=\"https://wandb.ai/fastai_community/reformer-fastai\" target=\"_blank\">https://wandb.ai/fastai_community/reformer-fastai</a><br/>\n",
" Run page: <a href=\"https://wandb.ai/fastai_community/reformer-fastai/runs/15s64cjw\" target=\"_blank\">https://wandb.ai/fastai_community/reformer-fastai/runs/15s64cjw</a><br/>\n",
" Run data is saved locally in <code>/home/morgan/ml/projects/reformer_fastai/nbs/exploration/wandb/run-20201218_194945-15s64cjw</code><br/><br/>\n",
" "
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<h1>Run(15s64cjw)</h1><p></p><iframe src=\"https://wandb.ai/fastai_community/reformer-fastai/runs/15s64cjw\" style=\"border:none;width:100%;height:400px\"></iframe>"
],
"text/plain": [
"<wandb.sdk.wandb_run.Run at 0x7fccfb24e890>"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import wandb\n",
"from fastai.callback.wandb import *\n",
"\n",
"WANDB_NAME = 'wmt14_transformer_swt'\n",
"GROUP = 'TEST'\n",
"NOTES = 'Test TransformerEncDec with WMT14 using SubWordTokenizer, with shared emb and weight tying'\n",
"CONFIG = {}\n",
"TAGS =['enc_dec','std_attn','test']\n",
"\n",
"wandb.init(reinit=True, project=\"reformer-fastai\", entity=\"fastai_community\", \n",
" name=WANDB_NAME, group=GROUP, notes=NOTES, tags=TAGS)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 195
},
"id": "khP3hBgcDx5K",
"outputId": "b5348ca8-b740-48ad-e5bf-a21a4272621a"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"epoch train_loss valid_loss accuracy corpus_bleu time \n",
"█\r"
]
}
],
"source": [
"learn.fit_one_cycle(1, 1e-4, cbs=WandbCallback(log_preds=False, log_model=False))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "-EjtYGeywQLc"
},
"outputs": [],
"source": [
"torch.save(dls, 'wmt_bs16')"
]
}
],
"metadata": {
"accelerator": "GPU",
"colab": {
"authorship_tag": "ABX9TyOXpo4Ch/LYQKfaEfX7F5od",
"collapsed_sections": [],
"include_colab_link": true,
"mount_file_id": "10HjrHOggvJPvoKx8_TgBT3upn_xSYNHd",
"name": "SWT_fastai.ipynb",
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.8"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment