* first copy & past commit from Bert and morgans LSH code * add easy way to compare to trax original code * translate most of function * make trax lsh self attention deterministic with numpy seed + copy paste code * add same config * add same config * make layer init work * implemented hash_vectors function for lsh attention * continue reformer translation * hf LSHSelfAttentionLayer gives same output as trax layer * refactor code * refactor code * refactor code * refactor * refactor + add reformer config * delete bogus file * split reformer attention layer into two layers * save intermediate step * save intermediate step * make test work * add complete reformer block layer * finish reformer layer * implement causal and self mask * clean reformer test and refactor code * fix merge conflicts * fix merge conflicts * update init * fix device for GPU * fix chunk length init for tests * include morgans optimization * improve memory a bit * improve comment * factorize num_buckets * better testing parameters * make whole model work * make lm model work * add t5 copy paste tokenizer * add chunking feed forward * clean config * add improved assert statements * make tokenizer work * improve test * correct typo * extend config * add complexer test * add new axial position embeddings * add local block attention layer * clean tests * refactor * better testing * save intermediate progress * clean test file * make shorter input length work for model * allow variable input length * refactor * make forward pass for pretrained model work * add generation possibility * finish dropout and init * make style * refactor * add first version of RevNet Layers * make forward pass work and add convert file * make uploaded model forward pass work * make uploaded model forward pass work * refactor code * add namedtuples and cache buckets * correct head masks * refactor * made reformer more flexible * make style * remove set max length * add attention masks * fix up tests * fix lsh attention mask * make random seed optional for the moment * improve memory in reformer * add tests * make style * make sure masks work correctly * detach gradients * save intermediate * correct backprob through gather * make style * change back num hashes * rename to labels * fix rotation shape * fix detach * update * fix trainer * fix backward dropout * make reformer more flexible * fix conflict * fix * fix * add tests for fixed seed in reformer layer * fix trainer typo * fix typo in activations * add fp16 tests * add fp16 training * support fp16 * correct gradient bug in reformer * add fast gelu * re-add dropout for embedding dropout * better naming * better naming * renaming * finalize test branch * finalize tests * add more tests * finish tests * fix * fix type trainer * fix fp16 tests * fix tests * fix tests * fix tests * fix issue with dropout * fix dropout seeds * correct random seed on gpu * finalize random seed for dropout * finalize random seed for dropout * remove duplicate line * correct half precision bug * make style * refactor * refactor * docstring * remove sinusoidal position encodings for reformer * move chunking to modeling_utils * make style * clean config * make style * fix tests * fix auto tests * pretrained models * fix docstring * update conversion file * Update pretrained_models.rst * fix rst * fix rst * update copyright * fix test path * fix test path * fix small issue in test * include reformer in generation tests * add docs for axial position encoding * finish docs * Update convert_reformer_trax_checkpoint_to_pytorch.py * remove isort * include sams comments * remove wrong comment in utils * correct typos * fix typo * Update reformer.rst * applied morgans optimization * make style * make gpu compatible * remove bogus file * big test refactor * add example for chunking * fix typo * add to README
180 lines
6.6 KiB
Python
180 lines
6.6 KiB
Python
# coding=utf-8
|
|
# Copyright 2020 The Trax Authors and The HuggingFace Inc. team.
|
|
#
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
# you may not use this file except in compliance with the License.
|
|
# You may obtain a copy of the License at
|
|
#
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
#
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
# See the License for the specific language governing permissions and
|
|
# limitations under the License.
|
|
""" Tokenization class for model Reformer."""
|
|
|
|
|
|
import logging
|
|
import os
|
|
from shutil import copyfile
|
|
|
|
from .tokenization_utils import PreTrainedTokenizer
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
SPIECE_UNDERLINE = "▁"
|
|
|
|
|
|
####################################################
|
|
# Mapping from the keyword arguments names of Tokenizer `__init__`
|
|
# to file names for serializing Tokenizer instances
|
|
####################################################
|
|
VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
|
|
|
|
####################################################
|
|
# Mapping from the keyword arguments names of Tokenizer `__init__`
|
|
# to pretrained vocabulary URL for all the model shortcut names.
|
|
####################################################
|
|
PRETRAINED_VOCAB_FILES_MAP = {
|
|
"vocab_file": {
|
|
"google/reformer-crime-and-punishment": "https://cdn.huggingface.co/google/reformer-crime-and-punishment/spiece.model"
|
|
}
|
|
}
|
|
|
|
####################################################
|
|
# Mapping from model shortcut names to max length of inputs
|
|
####################################################
|
|
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
|
|
"google/reformer-crime-and-punishment": 524288,
|
|
}
|
|
|
|
|
|
class ReformerTokenizer(PreTrainedTokenizer):
|
|
"""
|
|
Constructs an Reformer tokenizer. Based on `SentencePiece <https://github.com/google/sentencepiece>`__ .
|
|
|
|
This tokenizer inherits from :class:`~transformers.PreTrainedTokenizer` which contains most of the methods. Users
|
|
should refer to the superclass for more information regarding methods.
|
|
|
|
Args:
|
|
vocab_file (:obj:`string`):
|
|
`SentencePiece <https://github.com/google/sentencepiece>`__ file (generally has a `.spm` extension) that
|
|
contains the vocabulary necessary to instantiate a tokenizer.
|
|
eos_token (:obj:`string`, `optional`, defaults to "</s>"):
|
|
The end of sequence token.
|
|
|
|
.. note::
|
|
|
|
When building a sequence using special tokens, this is not the token that is used for the end
|
|
of sequence. The token used is the :obj:`sep_token`.
|
|
unk_token (:obj:`string`, `optional`, defaults to "<unk>"):
|
|
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
|
token instead.
|
|
pad_token (:obj:`string`, `optional`, defaults to "<pad>"):
|
|
The token used for padding, for example when batching sequences of different lengths.
|
|
additional_special_tokens (:obj:`List[str]`, `optional`, defaults to :obj:`None`):
|
|
Additional special tokens used by the tokenizer.
|
|
"""
|
|
|
|
vocab_files_names = VOCAB_FILES_NAMES
|
|
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
|
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
|
|
|
|
def __init__(
|
|
self,
|
|
vocab_file,
|
|
eos_token="</s>",
|
|
unk_token="<unk>",
|
|
pad_token="<pad>",
|
|
additional_special_tokens=[],
|
|
**kwargs
|
|
):
|
|
super().__init__(
|
|
eos_token=eos_token,
|
|
unk_token=unk_token,
|
|
pad_token=pad_token,
|
|
additional_special_tokens=additional_special_tokens,
|
|
**kwargs,
|
|
)
|
|
|
|
try:
|
|
import sentencepiece as spm
|
|
except ImportError:
|
|
logger.warning(
|
|
"You need to install SentencePiece to use ReformerTokenizer:"
|
|
"https://github.com/google/sentencepiece"
|
|
"pip install sentencepiece"
|
|
)
|
|
raise
|
|
|
|
self.vocab_file = vocab_file
|
|
self.sp_model = spm.SentencePieceProcessor()
|
|
self.sp_model.Load(vocab_file)
|
|
|
|
@property
|
|
def vocab_size(self):
|
|
return self.sp_model.get_piece_size()
|
|
|
|
def get_vocab(self):
|
|
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
|
vocab.update(self.added_tokens_encoder)
|
|
return vocab
|
|
|
|
def __getstate__(self):
|
|
state = self.__dict__.copy()
|
|
state["sp_model"] = None
|
|
return state
|
|
|
|
def __setstate__(self, d):
|
|
self.__dict__ = d
|
|
try:
|
|
import sentencepiece as spm
|
|
except ImportError:
|
|
logger.warning(
|
|
"You need to install SentencePiece to use ReformerTokenizer: https://github.com/google/sentencepiece"
|
|
"pip install sentencepiece"
|
|
)
|
|
raise
|
|
self.sp_model = spm.SentencePieceProcessor()
|
|
self.sp_model.Load(self.vocab_file)
|
|
|
|
def _tokenize(self, text, sample=False):
|
|
""" Take as input a string and return a list of strings (tokens) for words/sub-words
|
|
"""
|
|
if not sample:
|
|
pieces = self.sp_model.EncodeAsPieces(text)
|
|
else:
|
|
pieces = self.sp_model.SampleEncodeAsPieces(text, 64, 0.1)
|
|
return pieces
|
|
|
|
def _convert_token_to_id(self, token):
|
|
""" Converts a token (str) in an id using the vocab. """
|
|
return self.sp_model.piece_to_id(token)
|
|
|
|
def _convert_id_to_token(self, index):
|
|
"""Converts an index (integer) in a token (str) using the vocab."""
|
|
if index < self.sp_model.get_piece_size():
|
|
token = self.sp_model.IdToPiece(index)
|
|
return token
|
|
|
|
def convert_tokens_to_string(self, tokens):
|
|
""" Converts a sequence of tokens (string) in a single string. """
|
|
out_string = self.sp_model.decode_pieces(tokens)
|
|
return out_string
|
|
|
|
def save_vocabulary(self, save_directory):
|
|
""" Save the sentencepiece vocabulary (copy original file) and special tokens file
|
|
to a directory.
|
|
"""
|
|
if not os.path.isdir(save_directory):
|
|
logger.error("Vocabulary path ({}) should be a directory".format(save_directory))
|
|
return
|
|
out_vocab_file = os.path.join(save_directory, VOCAB_FILES_NAMES["vocab_file"])
|
|
|
|
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
|
|
copyfile(self.vocab_file, out_vocab_file)
|
|
|
|
return (out_vocab_file,)
|