text
stringlengths
2
11.8k
Here it's important to see how DP rank 0 doesn't see GPU2 and DP rank 1 doesn't see GPU3. To DP there is just GPUs 0 and 1 where it feeds data as if there were just 2 GPUs. GPU0 "secretly" offloads some of its load to GPU2 using PP. And GPU1 does the same by enlisting GPU3 to its aid. Since each dimension requires at least 2 GPUs, here you'd need at least 4 GPUs. Implementations: - DeepSpeed - Megatron-LM - Varuna - SageMaker - OSLO πŸ€— Transformers status: not yet implemented Data Parallelism + Pipeline Parallelism + Tensor Parallelism To get an even more efficient training a 3D parallelism is used where PP is combined with TP and DP. This can be seen in the following diagram.
This diagram is from a blog post 3D parallelism: Scaling to trillion-parameter models, which is a good read as well. Since each dimension requires at least 2 GPUs, here you'd need at least 8 GPUs. Implementations: - DeepSpeed - DeepSpeed also includes an even more efficient DP, which they call ZeRO-DP. - Megatron-LM - Varuna - SageMaker - OSLO πŸ€— Transformers status: not yet implemented, since we have no PP and TP. ZeRO Data Parallelism + Pipeline Parallelism + Tensor Parallelism One of the main features of DeepSpeed is ZeRO, which is a super-scalable extension of DP. It has already been discussed in ZeRO Data Parallelism. Normally it's a standalone feature that doesn't require PP or TP. But it can be combined with PP and TP. When ZeRO-DP is combined with PP (and optionally TP) it typically enables only ZeRO stage 1 (optimizer sharding). While it's theoretically possible to use ZeRO stage 2 (gradient sharding) with Pipeline Parallelism, it will have negative performance impacts. There would need to be an additional reduce-scatter collective for every micro-batch to aggregate the gradients before sharding, which adds a potentially significant communication overhead. By nature of Pipeline Parallelism, small micro-batches are used and instead the focus is on trying to balance arithmetic intensity (micro-batch size) with minimizing the Pipeline bubble (number of micro-batches). Therefore those communication costs are going to impact the performance. In addition, there are already fewer layers than normal due to PP and so the memory savings won't be huge. PP already reduces gradient size by 1/PP, and so gradient sharding savings on top of that are less significant than pure DP. ZeRO stage 3 is not a good choice either for the same reason - more inter-node communications required. And since we have ZeRO, the other benefit is ZeRO-Offload. Since this is stage 1 optimizer states can be offloaded to CPU. Implementations: - Megatron-DeepSpeed and Megatron-Deepspeed from BigScience, which is the fork of the former repo. - OSLO Important papers:
Using DeepSpeed and Megatron to Train Megatron-Turing NLG 530B, A Large-Scale Generative Language Model πŸ€— Transformers status: not yet implemented, since we have no PP and TP. FlexFlow FlexFlow also solves the parallelization problem in a slightly different approach. Paper: "Beyond Data and Model Parallelism for Deep Neural Networks" by Zhihao Jia, Matei Zaharia, Alex Aiken It performs a sort of 4D Parallelism over Sample-Operator-Attribute-Parameter.
Sample = Data Parallelism (sample-wise parallel) Operator = Parallelize a single operation into several sub-operations Attribute = Data Parallelism (length-wise parallel) Parameter = Model Parallelism (regardless of dimension - horizontal or vertical) Examples: * Sample Let's take 10 batches of sequence length 512. If we parallelize them by sample dimension into 2 devices, we get 10 x 512 which becomes be 5 x 2 x 512. Operator
Operator If we perform layer normalization, we compute std first and mean second, and then we can normalize data. Operator parallelism allows computing std and mean in parallel. So if we parallelize them by operator dimension into 2 devices (cuda:0, cuda:1), first we copy input data into both devices, and cuda:0 computes std, cuda:1 computes mean at the same time. Attribute We have 10 batches of 512 length. If we parallelize them by attribute dimension into 2 devices, 10 x 512 will be 10 x 2 x 256.
Attribute We have 10 batches of 512 length. If we parallelize them by attribute dimension into 2 devices, 10 x 512 will be 10 x 2 x 256. Parameter It is similar with tensor model parallelism or naive layer-wise model parallelism.
The significance of this framework is that it takes resources like (1) GPU/TPU/CPU vs. (2) RAM/DRAM vs. (3) fast-intra-connect/slow-inter-connect and it automatically optimizes all these algorithmically deciding which parallelisation to use where. One very important aspect is that FlexFlow is designed for optimizing DNN parallelizations for models with static and fixed workloads, since models with dynamic behavior may prefer different parallelization strategies across iterations. So the promise is very attractive - it runs a 30min simulation on the cluster of choice and it comes up with the best strategy to utilise this specific environment. If you add/remove/replace any parts it'll run and re-optimize the plan for that. And then you can train. A different setup will have its own custom optimization. πŸ€— Transformers status: Transformers models are FX-trace-able via transformers.utils.fx, which is a prerequisite for FlexFlow, however, changes are required on the FlexFlow side to make it work with Transformers models. GPU selection When training on multiple GPUs, you can specify the number of GPUs to use and in what order. This can be useful for instance when you have GPUs with different computing power and want to use the faster GPU first. The selection process works for both DistributedDataParallel and DataParallel to use only a subset of the available GPUs, and you don't need Accelerate or the DeepSpeed integration. Number of GPUs For example, if you have 4 GPUs and you only want to use the first 2:
Use the --nproc_per_node to select how many GPUs to use. torchrun --nproc_per_node=2 trainer-program.py Use --num_processes to select how many GPUs to use. accelerate launch --num_processes 2 trainer-program.py Use --num_gpus to select how many GPUs to use. deepspeed --num_gpus 2 trainer-program.py
accelerate launch --num_processes 2 trainer-program.py Use --num_gpus to select how many GPUs to use. deepspeed --num_gpus 2 trainer-program.py Order of GPUs Now, to select which GPUs to use and their order, you'll use the CUDA_VISIBLE_DEVICES environment variable. It is easiest to set the environment variable in a ~/bashrc or another startup config file. CUDA_VISIBLE_DEVICES is used to map which GPUs are used. For example, if you have 4 GPUs (0, 1, 2, 3) and you only want to run GPUs 0 and 2:
CUDA_VISIBLE_DEVICES=0,2 torchrun trainer-program.py Only the 2 physical GPUs (0 and 2) are "visible" to PyTorch and these are mapped to cuda:0 and cuda:1 respectively. You can also reverse the order of the GPUs to use 2 first. Now, the mapping is cuda:1 for GPU 0 and cuda:0 for GPU 2. CUDA_VISIBLE_DEVICES=2,0 torchrun trainer-program.py You can also set the CUDA_VISIBLE_DEVICES environment variable to an empty value to create an environment without GPUs.
CUDA_VISIBLE_DEVICES=2,0 torchrun trainer-program.py You can also set the CUDA_VISIBLE_DEVICES environment variable to an empty value to create an environment without GPUs. CUDA_VISIBLE_DEVICES= python trainer-program.py
CUDA_VISIBLE_DEVICES= python trainer-program.py As with any environment variable, they can be exported instead of being added to the command line. However, this is not recommended because it can be confusing if you forget how the environment variable was setup and you end up using the wrong GPUs. Instead, it is common practice to set the environment variable for a specific training run on the same command line.
CUDA_DEVICE_ORDER is an alternative environment variable you can use to control how the GPUs are ordered. You can either order them by: PCIe bus ID's that matches the order of nvidia-smi and rocm-smi for NVIDIA and AMD GPUs respectively export CUDA_DEVICE_ORDER=PCI_BUS_ID GPU compute ability
GPU compute ability export CUDA_DEVICE_ORDER=FASTEST_FIRST The CUDA_DEVICE_ORDER is especially useful if your training setup consists of an older and newer GPU, where the older GPU appears first, but you cannot physically swap the cards to make the newer GPU appear first. In this case, set CUDA_DEVICE_ORDER=FASTEST_FIRST to always use the newer and faster GPU first (nvidia-smi or rocm-smi still reports the GPUs in their PCIe order). Or you could also set export CUDA_VISIBLE_DEVICES=1,0.
Templates for Chat Models Introduction An increasingly common use case for LLMs is chat. In a chat context, rather than continuing a single string of text (as is the case with a standard language model), the model instead continues a conversation that consists of one or more messages, each of which includes a role, like "user" or "assistant", as well as message text. Much like tokenization, different models expect very different input formats for chat. This is the reason we added chat templates as a feature. Chat templates are part of the tokenizer. They specify how to convert conversations, represented as lists of messages, into a single tokenizable string in the format that the model expects. Let's make this concrete with a quick example using the BlenderBot model. BlenderBot has an extremely simple default template, which mostly just adds whitespace between rounds of dialogue: thon
from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill") chat = [ {"role": "user", "content": "Hello, how are you?"}, {"role": "assistant", "content": "I'm doing great. How can I help you today?"}, {"role": "user", "content": "I'd like to show off how chat templating works!"}, ] tokenizer.apply_chat_template(chat, tokenize=False) " Hello, how are you? I'm doing great. How can I help you today? I'd like to show off how chat templating works!"
Notice how the entire chat is condensed into a single string. If we use tokenize=True, which is the default setting, that string will also be tokenized for us. To see a more complex template in action, though, let's use the mistralai/Mistral-7B-Instruct-v0.1 model. thon
from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1") chat = [ {"role": "user", "content": "Hello, how are you?"}, {"role": "assistant", "content": "I'm doing great. How can I help you today?"}, {"role": "user", "content": "I'd like to show off how chat templating works!"}, ] tokenizer.apply_chat_template(chat, tokenize=False) "[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today? [INST] I'd like to show off how chat templating works! [/INST]"
Note that this time, the tokenizer has added the control tokens [INST] and [/INST] to indicate the start and end of user messages (but not assistant messages!). Mistral-instruct was trained with these tokens, but BlenderBot was not. How do I use chat templates? As you can see in the example above, chat templates are easy to use. Simply build a list of messages, with role and content keys, and then pass it to the [~PreTrainedTokenizer.apply_chat_template] method. Once you do that, you'll get output that's ready to go! When using chat templates as input for model generation, it's also a good idea to use add_generation_prompt=True to add a generation prompt. Here's an example of preparing input for model.generate(), using the Zephyr assistant model: thon from transformers import AutoModelForCausalLM, AutoTokenizer checkpoint = "HuggingFaceH4/zephyr-7b-beta" tokenizer = AutoTokenizer.from_pretrained(checkpoint) model = AutoModelForCausalLM.from_pretrained(checkpoint) # You may want to use bfloat16 and/or move to GPU here messages = [ { "role": "system", "content": "You are a friendly chatbot who always responds in the style of a pirate", }, {"role": "user", "content": "How many helicopters can a human eat in one sitting?"}, ] tokenized_chat = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt") print(tokenizer.decode(tokenized_chat[0])) This will yield a string in the input format that Zephyr expects.text <|system|> You are a friendly chatbot who always responds in the style of a pirate <|user|> How many helicopters can a human eat in one sitting? <|assistant|>
Now that our input is formatted correctly for Zephyr, we can use the model to generate a response to the user's question: python outputs = model.generate(tokenized_chat, max_new_tokens=128) print(tokenizer.decode(outputs[0])) This will yield: text <|system|> You are a friendly chatbot who always responds in the style of a pirate</s> <|user|> How many helicopters can a human eat in one sitting?</s> <|assistant|> Matey, I'm afraid I must inform ye that humans cannot eat helicopters. Helicopters are not food, they are flying machines. Food is meant to be eaten, like a hearty plate o' grog, a savory bowl o' stew, or a delicious loaf o' bread. But helicopters, they be for transportin' and movin' around, not for eatin'. So, I'd say none, me hearties. None at all. Arr, 'twas easy after all! Is there an automated pipeline for chat? Yes, there is! Our text generation pipelines support chat inputs, which makes it easy to use chat models. In the past, we used to use a dedicated "ConversationalPipeline" class, but this has now been deprecated and its functionality has been merged into the [TextGenerationPipeline]. Let's try the Zephyr example again, but this time using a pipeline: thon from transformers import pipeline pipe = pipeline("text-generation", "HuggingFaceH4/zephyr-7b-beta") messages = [ { "role": "system", "content": "You are a friendly chatbot who always responds in the style of a pirate", }, {"role": "user", "content": "How many helicopters can a human eat in one sitting?"}, ] print(pipe(messages, max_new_tokens=128)[0]['generated_text'][-1]) # Print the assistant's response
text {'role': 'assistant', 'content': "Matey, I'm afraid I must inform ye that humans cannot eat helicopters. Helicopters are not food, they are flying machines. Food is meant to be eaten, like a hearty plate o' grog, a savory bowl o' stew, or a delicious loaf o' bread. But helicopters, they be for transportin' and movin' around, not for eatin'. So, I'd say none, me hearties. None at all."} The pipeline will take care of all the details of tokenization and calling apply_chat_template for you - once the model has a chat template, all you need to do is initialize the pipeline and pass it the list of messages! What are "generation prompts"? You may have noticed that the apply_chat_template method has an add_generation_prompt argument. This argument tells the template to add tokens that indicate the start of a bot response. For example, consider the following chat: python messages = [ {"role": "user", "content": "Hi there!"}, {"role": "assistant", "content": "Nice to meet you!"}, {"role": "user", "content": "Can I ask a question?"} ] Here's what this will look like without a generation prompt, using the ChatML template we saw in the Zephyr example: python tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False) """<|im_start|>user Hi there!<|im_end|> <|im_start|>assistant Nice to meet you!<|im_end|> <|im_start|>user Can I ask a question?<|im_end|> """ And here's what it looks like with a generation prompt: python tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) """<|im_start|>user Hi there!<|im_end|> <|im_start|>assistant Nice to meet you!<|im_end|> <|im_start|>user Can I ask a question?<|im_end|> <|im_start|>assistant """ Note that this time, we've added the tokens that indicate the start of a bot response. This ensures that when the model generates text it will write a bot response instead of doing something unexpected, like continuing the user's message. Remember, chat models are still just language models - they're trained to continue text, and chat is just a special kind of text to them! You need to guide them with appropriate control tokens, so they know what they're supposed to be doing. Not all models require generation prompts. Some models, like BlenderBot and LLaMA, don't have any special tokens before bot responses. In these cases, the add_generation_prompt argument will have no effect. The exact effect that add_generation_prompt has will depend on the template being used. Can I use chat templates in training? Yes! We recommend that you apply the chat template as a preprocessing step for your dataset. After this, you can simply continue like any other language model training task. When training, you should usually set add_generation_prompt=False, because the added tokens to prompt an assistant response will not be helpful during training. Let's see an example: thon from transformers import AutoTokenizer from datasets import Dataset tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta") chat1 = [ {"role": "user", "content": "Which is bigger, the moon or the sun?"}, {"role": "assistant", "content": "The sun."} ] chat2 = [ {"role": "user", "content": "Which is bigger, a virus or a bacterium?"}, {"role": "assistant", "content": "A bacterium."} ] dataset = Dataset.from_dict({"chat": [chat1, chat2]}) dataset = dataset.map(lambda x: {"formatted_chat": tokenizer.apply_chat_template(x["chat"], tokenize=False, add_generation_prompt=False)}) print(dataset['formatted_chat'][0]) And we get:text <|user|> Which is bigger, the moon or the sun? <|assistant|> The sun.
From here, just continue training like you would with a standard language modelling task, using the formatted_chat column. Advanced: How do chat templates work? The chat template for a model is stored on the tokenizer.chat_template attribute. If no chat template is set, the default template for that model class is used instead. Let's take a look at the template for BlenderBot: thon
from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill") tokenizer.default_chat_template "{% for message in messages %}{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}{{ message['content'] }}{% if not loop.last %}{{ ' ' }}{% endif %}{% endfor %}{{ eos_token }}"
That's kind of intimidating. Let's add some newlines and indentation to make it more readable. Note that the first newline after each block as well as any preceding whitespace before a block are ignored by default, using the Jinja trim_blocks and lstrip_blocks flags. However, be cautious - although leading whitespace on each line is stripped, spaces between blocks on the same line are not. We strongly recommend checking that your template isn't printing extra spaces where it shouldn't be! {% for message in messages %} {% if message['role'] == 'user' %} {{ ' ' }} {% endif %} {{ message['content'] }} {% if not loop.last %} {{ ' ' }} {% endif %} {% endfor %} {{ eos_token }} If you've never seen one of these before, this is a Jinja template. Jinja is a templating language that allows you to write simple code that generates text. In many ways, the code and syntax resembles Python. In pure Python, this template would look something like this: python for idx, message in enumerate(messages): if message['role'] == 'user': print(' ') print(message['content']) if not idx == len(messages) - 1: # Check for the last message in the conversation print(' ') print(eos_token) Effectively, the template does three things: 1. For each message, if the message is a user message, add a blank space before it, otherwise print nothing. 2. Add the message content 3. If the message is not the last message, add two spaces after it. After the final message, print the EOS token. This is a pretty simple template - it doesn't add any control tokens, and it doesn't support "system" messages, which are a common way to give the model directives about how it should behave in the subsequent conversation. But Jinja gives you a lot of flexibility to do those things! Let's see a Jinja template that can format inputs similarly to the way LLaMA formats them (note that the real LLaMA template includes handling for default system messages and slightly different system message handling in general - don't use this one in your actual code!) {% for message in messages %} {% if message['role'] == 'user' %} {{ bos_token + '[INST] ' + message['content'] + ' [/INST]' }} {% elif message['role'] == 'system' %} {{ '<<SYS>>\\n' + message['content'] + '\\n<</SYS>>\\n\\n' }} {% elif message['role'] == 'assistant' %} {{ ' ' + message['content'] + ' ' + eos_token }} {% endif %} {% endfor %} Hopefully if you stare at this for a little bit you can see what this template is doing - it adds specific tokens based on the "role" of each message, which represents who sent it. User, assistant and system messages are clearly distinguishable to the model because of the tokens they're wrapped in. Advanced: Adding and editing chat templates How do I create a chat template? Simple, just write a jinja template and set tokenizer.chat_template. You may find it easier to start with an existing template from another model and simply edit it for your needs! For example, we could take the LLaMA template above and add "[ASST]" and "[/ASST]" to assistant messages: {% for message in messages %} {% if message['role'] == 'user' %} {{ bos_token + '[INST] ' + message['content'].strip() + ' [/INST]' }} {% elif message['role'] == 'system' %} {{ '<<SYS>>\\n' + message['content'].strip() + '\\n<</SYS>>\\n\\n' }} {% elif message['role'] == 'assistant' %} {{ '[ASST] ' + message['content'] + ' [/ASST]' + eos_token }} {% endif %} {% endfor %} Now, simply set the tokenizer.chat_template attribute. Next time you use [~PreTrainedTokenizer.apply_chat_template], it will use your new template! This attribute will be saved in the tokenizer_config.json file, so you can use [~utils.PushToHubMixin.push_to_hub] to upload your new template to the Hub and make sure everyone's using the right template for your model! python template = tokenizer.chat_template template = template.replace("SYS", "SYSTEM") # Change the system token tokenizer.chat_template = template # Set the new template tokenizer.push_to_hub("model_name") # Upload your new template to the Hub! The method [~PreTrainedTokenizer.apply_chat_template] which uses your chat template is called by the [TextGenerationPipeline] class, so once you set the correct chat template, your model will automatically become compatible with [TextGenerationPipeline].
If you're fine-tuning a model for chat, in addition to setting a chat template, you should probably add any new chat control tokens as special tokens in the tokenizer. Special tokens are never split, ensuring that your control tokens are always handled as single tokens rather than being tokenized in pieces. You should also set the tokenizer's eos_token attribute to the token that marks the end of assistant generations in your template. This will ensure that text generation tools can correctly figure out when to stop generating text.
What are "default" templates? Before the introduction of chat templates, chat handling was hardcoded at the model class level. For backwards compatibility, we have retained this class-specific handling as default templates, also set at the class level. If a model does not have a chat template set, but there is a default template for its model class, the TextGenerationPipeline class and methods like apply_chat_template will use the class template instead. You can find out what the default template for your tokenizer is by checking the tokenizer.default_chat_template attribute. This is something we do purely for backward compatibility reasons, to avoid breaking any existing workflows. Even when the class template is appropriate for your model, we strongly recommend overriding the default template by setting the chat_template attribute explicitly to make it clear to users that your model has been correctly configured for chat, and to future-proof in case the default templates are ever altered or deprecated. What template should I use? When setting the template for a model that's already been trained for chat, you should ensure that the template exactly matches the message formatting that the model saw during training, or else you will probably experience performance degradation. This is true even if you're training the model further - you will probably get the best performance if you keep the chat tokens constant. This is very analogous to tokenization - you generally get the best performance for inference or fine-tuning when you precisely match the tokenization used during training. If you're training a model from scratch, or fine-tuning a base language model for chat, on the other hand, you have a lot of freedom to choose an appropriate template! LLMs are smart enough to learn to handle lots of different input formats. Our default template for models that don't have a class-specific template follows the ChatML format, and this is a good, flexible choice for many use-cases. It looks like this: {% for message in messages %} {{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}} {% endfor %} If you like this one, here it is in one-liner form, ready to copy into your code. The one-liner also includes handy support for generation prompts, but note that it doesn't add BOS or EOS tokens! If your model expects those, they won't be added automatically by apply_chat_template - in other words, the text will be tokenized with add_special_tokens=False. This is to avoid potential conflicts between the template and the add_special_tokens logic. If your model expects special tokens, make sure to add them to the template! python tokenizer.chat_template = "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}" This template wraps each message in <|im_start|> and <|im_end|> tokens, and simply writes the role as a string, which allows for flexibility in the roles you train with. The output looks like this: text <|im_start|>system You are a helpful chatbot that will do its best not to say anything so stupid that people tweet about it.<|im_end|> <|im_start|>user How are you?<|im_end|> <|im_start|>assistant I'm doing great!<|im_end|> The "user", "system" and "assistant" roles are the standard for chat, and we recommend using them when it makes sense, particularly if you want your model to operate well with [TextGenerationPipeline]. However, you are not limited to these roles - templating is extremely flexible, and any string can be a role. I want to add some chat templates! How should I get started? If you have any chat models, you should set their tokenizer.chat_template attribute and test it using [~PreTrainedTokenizer.apply_chat_template], then push the updated tokenizer to the Hub. This applies even if you're not the model owner - if you're using a model with an empty chat template, or one that's still using the default class template, please open a pull request to the model repository so that this attribute can be set properly! Once the attribute is set, that's it, you're done! tokenizer.apply_chat_template will now work correctly for that model, which means it is also automatically supported in places like TextGenerationPipeline! By ensuring that models have this attribute, we can make sure that the whole community gets to use the full power of open-source models. Formatting mismatches have been haunting the field and silently harming performance for too long - it's time to put an end to them! Advanced: Template writing tips If you're unfamiliar with Jinja, we generally find that the easiest way to write a chat template is to first write a short Python script that formats messages the way you want, and then convert that script into a template. Remember that the template handler will receive the conversation history as a variable called messages. Each message is a dictionary with two keys, role and content. You will be able to access messages in your template just like you can in Python, which means you can loop over it with {% for message in messages %} or access individual messages with, for example, {{ messages[0] }}. You can also use the following tips to convert your code to Jinja: For loops For loops in Jinja look like this: {% for message in messages %} {{ message['content'] }} {% endfor %} Note that whatever's inside the {{ expression block }} will be printed to the output. You can use operators like + to combine strings inside expression blocks. If statements If statements in Jinja look like this: {% if message['role'] == 'user' %} {{ message['content'] }} {% endif %} Note how where Python uses whitespace to mark the beginnings and ends of for and if blocks, Jinja requires you to explicitly end them with {% endfor %} and {% endif %}. Special variables Inside your template, you will have access to the list of messages, but you can also access several other special variables. These include special tokens like bos_token and eos_token, as well as the add_generation_prompt variable that we discussed above. You can also use the loop variable to access information about the current loop iteration, for example using {% if loop.last %} to check if the current message is the last message in the conversation. Here's an example that puts these ideas together to add a generation prompt at the end of the conversation if add_generation_prompt is True: {% if loop.last and add_generation_prompt %} {{ bos_token + 'Assistant:\n' }} {% endif %} Notes on whitespace As much as possible, we've tried to get Jinja to ignore whitespace outside of {{ expressions }}. However, be aware that Jinja is a general-purpose templating engine, and it may treat whitespace between blocks on the same line as significant and print it to the output. We strongly recommend checking that your template isn't printing extra spaces where it shouldn't be before you upload it!
How to add a model to πŸ€— Transformers? The πŸ€— Transformers library is often able to offer new models thanks to community contributors. But this can be a challenging project and requires an in-depth knowledge of the πŸ€— Transformers library and the model to implement. At Hugging Face, we're trying to empower more of the community to actively add models and we've put together this guide to walk you through the process of adding a PyTorch model (make sure you have PyTorch installed).
If you're interested in implementing a TensorFlow model, take a look at the How to convert a πŸ€— Transformers model to TensorFlow guide! Along the way, you'll: get insights into open-source best practices understand the design principles behind one of the most popular deep learning libraries learn how to efficiently test large models learn how to integrate Python utilities like black, ruff, and make fix-copies to ensure clean and readable code
A Hugging Face team member will be available to help you along the way so you'll never be alone. πŸ€— ❀️ To get started, open a New model addition issue for the model you want to see in πŸ€— Transformers. If you're not especially picky about contributing a specific model, you can filter by the New model label to see if there are any unclaimed model requests and work on it. Once you've opened a new model request, the first step is to get familiar with πŸ€— Transformers if you aren't already! General overview of πŸ€— Transformers First, you should get a general overview of πŸ€— Transformers. πŸ€— Transformers is a very opinionated library, so there is a chance that you don't agree with some of the library's philosophies or design choices. From our experience, however, we found that the fundamental design choices and philosophies of the library are crucial to efficiently scale πŸ€— Transformers while keeping maintenance costs at a reasonable level. A good first starting point to better understand the library is to read the documentation of our philosophy. As a result of our way of working, there are some choices that we try to apply to all models:
Composition is generally favored over-abstraction Duplicating code is not always bad if it strongly improves the readability or accessibility of a model Model files are as self-contained as possible so that when you read the code of a specific model, you ideally only have to look into the respective modeling_.py file.
In our opinion, the library's code is not just a means to provide a product, e.g. the ability to use BERT for inference, but also as the very product that we want to improve. Hence, when adding a model, the user is not only the person who will use your model, but also everybody who will read, try to understand, and possibly tweak your code. With this in mind, let's go a bit deeper into the general library design. Overview of models To successfully add a model, it is important to understand the interaction between your model and its config, [PreTrainedModel], and [PretrainedConfig]. For exemplary purposes, we will call the model to be added to πŸ€— Transformers BrandNewBert. Let's take a look:
As you can see, we do make use of inheritance in πŸ€— Transformers, but we keep the level of abstraction to an absolute minimum. There are never more than two levels of abstraction for any model in the library. BrandNewBertModel inherits from BrandNewBertPreTrainedModel which in turn inherits from [PreTrainedModel] and that's it. As a general rule, we want to make sure that a new model only depends on [PreTrainedModel]. The important functionalities that are automatically provided to every new model are [~PreTrainedModel.from_pretrained] and [~PreTrainedModel.save_pretrained], which are used for serialization and deserialization. All of the other important functionalities, such as BrandNewBertModel.forward should be completely defined in the new modeling_brand_new_bert.py script. Next, we want to make sure that a model with a specific head layer, such as BrandNewBertForMaskedLM does not inherit from BrandNewBertModel, but rather uses BrandNewBertModel as a component that can be called in its forward pass to keep the level of abstraction low. Every new model requires a configuration class, called BrandNewBertConfig. This configuration is always stored as an attribute in [PreTrainedModel], and thus can be accessed via the config attribute for all classes inheriting from BrandNewBertPreTrainedModel: python model = BrandNewBertModel.from_pretrained("brandy/brand_new_bert") model.config # model has access to its config Similar to the model, the configuration inherits basic serialization and deserialization functionalities from [PretrainedConfig]. Note that the configuration and the model are always serialized into two different formats - the model to a pytorch_model.bin file and the configuration to a config.json file. Calling [~PreTrainedModel.save_pretrained] will automatically call [~PretrainedConfig.save_pretrained], so that both model and configuration are saved. Code style When coding your new model, keep in mind that Transformers is an opinionated library and we have a few quirks of our own regarding how code should be written :-)
The forward pass of your model should be fully written in the modeling file while being fully independent of other models in the library. If you want to reuse a block from another model, copy the code and paste it with a # Copied from comment on top (see here for a good example and there for more documentation on Copied from). The code should be fully understandable, even by a non-native English speaker. This means you should pick descriptive variable names and avoid abbreviations. As an example, activation is preferred to act. One-letter variable names are strongly discouraged unless it's an index in a for loop. More generally we prefer longer explicit code to short magical one. Avoid subclassing nn.Sequential in PyTorch but subclass nn.Module and write the forward pass, so that anyone using your code can quickly debug it by adding print statements or breaking points. Your function signature should be type-annotated. For the rest, good variable names are way more readable and understandable than type annotations.
Overview of tokenizers Not quite ready yet :-( This section will be added soon! Step-by-step recipe to add a model to πŸ€— Transformers Everyone has different preferences of how to port a model so it can be very helpful for you to take a look at summaries of how other contributors ported models to Hugging Face. Here is a list of community blog posts on how to port a model: Porting GPT2 Model by Thomas Porting WMT19 MT Model by Stas
Porting GPT2 Model by Thomas Porting WMT19 MT Model by Stas From experience, we can tell you that the most important things to keep in mind when adding a model are:
Don't reinvent the wheel! Most parts of the code you will add for the new πŸ€— Transformers model already exist somewhere in πŸ€— Transformers. Take some time to find similar, already existing models and tokenizers you can copy from. grep and rg are your friends. Note that it might very well happen that your model's tokenizer is based on one model implementation, and your model's modeling code on another one. E.g. FSMT's modeling code is based on BART, while FSMT's tokenizer code is based on XLM. It's more of an engineering challenge than a scientific challenge. You should spend more time creating an efficient debugging environment rather than trying to understand all theoretical aspects of the model in the paper. Ask for help, when you're stuck! Models are the core component of πŸ€— Transformers so we at Hugging Face are more than happy to help you at every step to add your model. Don't hesitate to ask if you notice you are not making progress.
In the following, we try to give you a general recipe that we found most useful when porting a model to πŸ€— Transformers. The following list is a summary of everything that has to be done to add a model and can be used by you as a To-Do List: ☐ (Optional) Understood the model's theoretical aspects ☐ Prepared πŸ€— Transformers dev environment ☐ Set up debugging environment of the original repository ☐ Created script that successfully runs the forward() pass using the original repository and checkpoint ☐ Successfully added the model skeleton to πŸ€— Transformers ☐ Successfully converted original checkpoint to πŸ€— Transformers checkpoint ☐ Successfully ran forward() pass in πŸ€— Transformers that gives identical output to original checkpoint ☐ Finished model tests in πŸ€— Transformers ☐ Successfully added tokenizer in πŸ€— Transformers ☐ Run end-to-end integration tests ☐ Finished docs ☐ Uploaded model weights to the Hub ☐ Submitted the pull request ☐ (Optional) Added a demo notebook To begin with, we usually recommend starting by getting a good theoretical understanding of BrandNewBert. However, if you prefer to understand the theoretical aspects of the model on-the-job, then it is totally fine to directly dive into the BrandNewBert's code-base. This option might suit you better if your engineering skills are better than your theoretical skill, if you have trouble understanding BrandNewBert's paper, or if you just enjoy programming much more than reading scientific papers. 1. (Optional) Theoretical aspects of BrandNewBert You should take some time to read BrandNewBert's paper, if such descriptive work exists. There might be large sections of the paper that are difficult to understand. If this is the case, this is fine - don't worry! The goal is not to get a deep theoretical understanding of the paper, but to extract the necessary information required to effectively re-implement the model in πŸ€— Transformers. That being said, you don't have to spend too much time on the theoretical aspects, but rather focus on the practical ones, namely:
What type of model is brand_new_bert? BERT-like encoder-only model? GPT2-like decoder-only model? BART-like encoder-decoder model? Look at the model_summary if you're not familiar with the differences between those. What are the applications of brand_new_bert? Text classification? Text generation? Seq2Seq tasks, e.g., summarization? What is the novel feature of the model that makes it different from BERT/GPT-2/BART? Which of the already existing πŸ€— Transformers models is most similar to brand_new_bert? What type of tokenizer is used? A sentencepiece tokenizer? Word piece tokenizer? Is it the same tokenizer as used for BERT or BART?
After you feel like you have gotten a good overview of the architecture of the model, you might want to write to the Hugging Face team with any questions you might have. This might include questions regarding the model's architecture, its attention layer, etc. We will be more than happy to help you. 2. Next prepare your environment Fork the repository by clicking on the β€˜Fork' button on the repository's page. This creates a copy of the code under your GitHub user account.
Fork the repository by clicking on the β€˜Fork' button on the repository's page. This creates a copy of the code under your GitHub user account. Clone your transformers fork to your local disk, and add the base repository as a remote: git clone https://github.com/[your Github handle]/transformers.git cd transformers git remote add upstream https://github.com/huggingface/transformers.git Set up a development environment, for instance by running the following command:
Set up a development environment, for instance by running the following command: python -m venv .env source .env/bin/activate pip install -e ".[dev]" Depending on your OS, and since the number of optional dependencies of Transformers is growing, you might get a failure with this command. If that's the case make sure to install the Deep Learning framework you are working with (PyTorch, TensorFlow and/or Flax) then do:
pip install -e ".[quality]" which should be enough for most use cases. You can then return to the parent directory cd .. We recommend adding the PyTorch version of brand_new_bert to Transformers. To install PyTorch, please follow the instructions on https://pytorch.org/get-started/locally/. Note: You don't need to have CUDA installed. Making the new model work on CPU is sufficient. To port brand_new_bert, you will also need access to its original repository:
git clone https://github.com/org_that_created_brand_new_bert_org/brand_new_bert.git cd brand_new_bert pip install -e . Now you have set up a development environment to port brand_new_bert to πŸ€— Transformers. 3.-4. Run a pretrained checkpoint using the original repository At first, you will work on the original brand_new_bert repository. Often, the original implementation is very β€œresearchy”. Meaning that documentation might be lacking and the code can be difficult to understand. But this should be exactly your motivation to reimplement brand_new_bert. At Hugging Face, one of our main goals is to make people stand on the shoulders of giants which translates here very well into taking a working model and rewriting it to make it as accessible, user-friendly, and beautiful as possible. This is the number-one motivation to re-implement models into πŸ€— Transformers - trying to make complex new NLP technology accessible to everybody. You should start thereby by diving into the original repository. Successfully running the official pretrained model in the original repository is often the most difficult step. From our experience, it is very important to spend some time getting familiar with the original code-base. You need to figure out the following:
Where to find the pretrained weights? How to load the pretrained weights into the corresponding model? How to run the tokenizer independently from the model? Trace one forward pass so that you know which classes and functions are required for a simple forward pass. Usually, you only have to reimplement those functions. Be able to locate the important components of the model: Where is the model's class? Are there model sub-classes, e.g. EncoderModel, DecoderModel? Where is the self-attention layer? Are there multiple different attention layers, e.g. self-attention, cross-attention? How can you debug the model in the original environment of the repo? Do you have to add print statements, can you work with an interactive debugger like ipdb, or should you use an efficient IDE to debug the model, like PyCharm?
It is very important that before you start the porting process, you can efficiently debug code in the original repository! Also, remember that you are working with an open-source library, so do not hesitate to open an issue, or even a pull request in the original repository. The maintainers of this repository are most likely very happy about someone looking into their code! At this point, it is really up to you which debugging environment and strategy you prefer to use to debug the original model. We strongly advise against setting up a costly GPU environment, but simply work on a CPU both when starting to dive into the original repository and also when starting to write the πŸ€— Transformers implementation of the model. Only at the very end, when the model has already been successfully ported to πŸ€— Transformers, one should verify that the model also works as expected on GPU. In general, there are two possible debugging environments for running the original model
Jupyter notebooks / google colab Local python scripts.
Jupyter notebooks have the advantage that they allow for cell-by-cell execution which can be helpful to better split logical components from one another and to have faster debugging cycles as intermediate results can be stored. Also, notebooks are often easier to share with other contributors, which might be very helpful if you want to ask the Hugging Face team for help. If you are familiar with Jupyter notebooks, we strongly recommend you work with them. The obvious disadvantage of Jupyter notebooks is that if you are not used to working with them you will have to spend some time adjusting to the new programming environment and you might not be able to use your known debugging tools anymore, like ipdb. For each code-base, a good first step is always to load a small pretrained checkpoint and to be able to reproduce a single forward pass using a dummy integer vector of input IDs as an input. Such a script could look like this (in pseudocode): python model = BrandNewBertModel.load_pretrained_checkpoint("/path/to/checkpoint/") input_ids = [0, 4, 5, 2, 3, 7, 9] # vector of input ids original_output = model.predict(input_ids) Next, regarding the debugging strategy, there are generally a few from which to choose from:
Decompose the original model into many small testable components and run a forward pass on each of those for verification Decompose the original model only into the original tokenizer and the original model, run a forward pass on those, and use intermediate print statements or breakpoints for verification
Again, it is up to you which strategy to choose. Often, one or the other is advantageous depending on the original code base. If the original code-base allows you to decompose the model into smaller sub-components, e.g. if the original code-base can easily be run in eager mode, it is usually worth the effort to do so. There are some important advantages to taking the more difficult road in the beginning:
at a later stage when comparing the original model to the Hugging Face implementation, you can verify automatically for each component individually that the corresponding component of the πŸ€— Transformers implementation matches instead of relying on visual comparison via print statements it can give you some rope to decompose the big problem of porting a model into smaller problems of just porting individual components and thus structure your work better separating the model into logical meaningful components will help you to get a better overview of the model's design and thus to better understand the model at a later stage those component-by-component tests help you to ensure that no regression occurs as you continue changing your code
Lysandre's integration checks for ELECTRA gives a nice example of how this can be done. However, if the original code-base is very complex or only allows intermediate components to be run in a compiled mode, it might be too time-consuming or even impossible to separate the model into smaller testable sub-components. A good example is T5's MeshTensorFlow library which is very complex and does not offer a simple way to decompose the model into its sub-components. For such libraries, one often relies on verifying print statements. No matter which strategy you choose, the recommended procedure is often the same that you should start to debug the starting layers first and the ending layers last. It is recommended that you retrieve the output, either by print statements or sub-component functions, of the following layers in the following order:
Retrieve the input IDs passed to the model Retrieve the word embeddings Retrieve the input of the first Transformer layer Retrieve the output of the first Transformer layer Retrieve the output of the following n - 1 Transformer layers Retrieve the output of the whole BrandNewBert Model
Input IDs should thereby consists of an array of integers, e.g. input_ids = [0, 4, 4, 3, 2, 4, 1, 7, 19] The outputs of the following layers often consist of multi-dimensional float arrays and can look like this: [[ [-0.1465, -0.6501, 0.1993, , 0.1451, 0.3430, 0.6024], [-0.4417, -0.5920, 0.3450, , -0.3062, 0.6182, 0.7132], [-0.5009, -0.7122, 0.4548, , -0.3662, 0.6091, 0.7648], , [-0.5613, -0.6332, 0.4324, , -0.3792, 0.7372, 0.9288], [-0.5416, -0.6345, 0.4180, , -0.3564, 0.6992, 0.9191], [-0.5334, -0.6403, 0.4271, , -0.3339, 0.6533, 0.8694]]], We expect that every model added to πŸ€— Transformers passes a couple of integration tests, meaning that the original model and the reimplemented version in πŸ€— Transformers have to give the exact same output up to a precision of 0.001! Since it is normal that the exact same model written in different libraries can give a slightly different output depending on the library framework, we accept an error tolerance of 1e-3 (0.001). It is not enough if the model gives nearly the same output, they have to be almost identical. Therefore, you will certainly compare the intermediate outputs of the πŸ€— Transformers version multiple times against the intermediate outputs of the original implementation of brand_new_bert in which case an efficient debugging environment of the original repository is absolutely important. Here is some advice to make your debugging environment as efficient as possible.
Find the best way of debugging intermediate results. Is the original repository written in PyTorch? Then you should probably take the time to write a longer script that decomposes the original model into smaller sub-components to retrieve intermediate values. Is the original repository written in Tensorflow 1? Then you might have to rely on TensorFlow print operations like tf.print to output intermediate values. Is the original repository written in Jax? Then make sure that the model is not jitted when running the forward pass, e.g. check-out this link. Use the smallest pretrained checkpoint you can find. The smaller the checkpoint, the faster your debug cycle becomes. It is not efficient if your pretrained model is so big that your forward pass takes more than 10 seconds. In case only very large checkpoints are available, it might make more sense to create a dummy model in the new environment with randomly initialized weights and save those weights for comparison with the πŸ€— Transformers version of your model Make sure you are using the easiest way of calling a forward pass in the original repository. Ideally, you want to find the function in the original repository that only calls a single forward pass, i.e. that is often called predict, evaluate, forward or __call__. You don't want to debug a function that calls forward multiple times, e.g. to generate text, like autoregressive_sample, generate. Try to separate the tokenization from the model's forward pass. If the original repository shows examples where you have to input a string, then try to find out where in the forward call the string input is changed to input ids and start from this point. This might mean that you have to possibly write a small script yourself or change the original code so that you can directly input the ids instead of an input string. Make sure that the model in your debugging setup is not in training mode, which often causes the model to yield random outputs due to multiple dropout layers in the model. Make sure that the forward pass in your debugging environment is deterministic so that the dropout layers are not used. Or use transformers.utils.set_seed if the old and new implementations are in the same framework.
The following section gives you more specific details/tips on how you can do this for brand_new_bert. 5.-14. Port BrandNewBert to πŸ€— Transformers Next, you can finally start adding new code to πŸ€— Transformers. Go into the clone of your πŸ€— Transformers' fork:
cd transformers In the special case that you are adding a model whose architecture exactly matches the model architecture of an existing model you only have to add a conversion script as described in this section. In this case, you can just re-use the whole model architecture of the already existing model. Otherwise, let's start generating a new model. You have two choices here:
transformers-cli add-new-model-like to add a new model like an existing one transformers-cli add-new-model to add a new model from our template (will look like BERT or Bart depending on the type of model you select)
In both cases, you will be prompted with a questionnaire to fill in the basic information of your model. The second command requires to install cookiecutter, you can find more information on it here. Open a Pull Request on the main huggingface/transformers repo Before starting to adapt the automatically generated code, now is the time to open a β€œWork in progress (WIP)” pull request, e.g. β€œ[WIP] Add brand_new_bert”, in πŸ€— Transformers so that you and the Hugging Face team can work side-by-side on integrating the model into πŸ€— Transformers. You should do the following:
Create a branch with a descriptive name from your main branch git checkout -b add_brand_new_bert Commit the automatically generated code: git add . git commit Fetch and rebase to current main git fetch upstream git rebase upstream/main Push the changes to your account using: git push -u origin a-descriptive-name-for-my-changes
git add . git commit Fetch and rebase to current main git fetch upstream git rebase upstream/main Push the changes to your account using: git push -u origin a-descriptive-name-for-my-changes Once you are satisfied, go to the webpage of your fork on GitHub. Click on β€œPull request”. Make sure to add the GitHub handle of some members of the Hugging Face team as reviewers, so that the Hugging Face team gets notified for future changes.
Change the PR into a draft by clicking on β€œConvert to draft” on the right of the GitHub pull request web page. In the following, whenever you have made some progress, don't forget to commit your work and push it to your account so that it shows in the pull request. Additionally, you should make sure to update your work with the current main from time to time by doing:
git fetch upstream git merge upstream/main In general, all questions you might have regarding the model or your implementation should be asked in your PR and discussed/solved in the PR. This way, the Hugging Face team will always be notified when you are committing new code or if you have a question. It is often very helpful to point the Hugging Face team to your added code so that the Hugging Face team can efficiently understand your problem or question. To do so, you can go to the β€œFiles changed” tab where you see all of your changes, go to a line regarding which you want to ask a question, and click on the β€œ+” symbol to add a comment. Whenever a question or problem has been solved, you can click on the β€œResolve” button of the created comment. In the same way, the Hugging Face team will open comments when reviewing your code. We recommend asking most questions on GitHub on your PR. For some very general questions that are not very useful for the public, feel free to ping the Hugging Face team by Slack or email. 5. Adapt the generated models code for brand_new_bert At first, we will focus only on the model itself and not care about the tokenizer. All the relevant code should be found in the generated files src/transformers/models/brand_new_bert/modeling_brand_new_bert.py and src/transformers/models/brand_new_bert/configuration_brand_new_bert.py. Now you can finally start coding :). The generated code in src/transformers/models/brand_new_bert/modeling_brand_new_bert.py will either have the same architecture as BERT if it's an encoder-only model or BART if it's an encoder-decoder model. At this point, you should remind yourself what you've learned in the beginning about the theoretical aspects of the model: How is the model different from BERT or BART?". Implement those changes which often means changing the self-attention layer, the order of the normalization layer, etc… Again, it is often useful to look at the similar architecture of already existing models in Transformers to get a better feeling of how your model should be implemented. Note that at this point, you don't have to be very sure that your code is fully correct or clean. Rather, it is advised to add a first unclean, copy-pasted version of the original code to src/transformers/models/brand_new_bert/modeling_brand_new_bert.py until you feel like all the necessary code is added. From our experience, it is much more efficient to quickly add a first version of the required code and improve/correct the code iteratively with the conversion script as described in the next section. The only thing that has to work at this point is that you can instantiate the πŸ€— Transformers implementation of brand_new_bert, i.e. the following command should work: thon from transformers import BrandNewBertModel, BrandNewBertConfig model = BrandNewBertModel(BrandNewBertConfig())
The above command will create a model according to the default parameters as defined in BrandNewBertConfig() with random weights, thus making sure that the init() methods of all components works. Note that all random initialization should happen in the _init_weights method of your BrandnewBertPreTrainedModel class. It should initialize all leaf modules depending on the variables of the config. Here is an example with the BERT _init_weights method: py def _init_weights(self, module): """Initialize the weights""" if isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() elif isinstance(module, nn.LayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0) You can have some more custom schemes if you need a special initialization for some modules. For instance, in Wav2Vec2ForPreTraining, the last two linear layers need to have the initialization of the regular PyTorch nn.Linear but all the other ones should use an initialization as above. This is coded like this: py def _init_weights(self, module): """Initialize the weights""" if isinstance(module, Wav2Vec2ForPreTraining): module.project_hid.reset_parameters() module.project_q.reset_parameters() module.project_hid._is_hf_initialized = True module.project_q._is_hf_initialized = True elif isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() The _is_hf_initialized flag is internally used to make sure we only initialize a submodule once. By setting it to True for module.project_q and module.project_hid, we make sure the custom initialization we did is not overridden later on, the _init_weights function won't be applied to them. 6. Write a conversion script Next, you should write a conversion script that lets you convert the checkpoint you used to debug brand_new_bert in the original repository to a checkpoint compatible with your just created πŸ€— Transformers implementation of brand_new_bert. It is not advised to write the conversion script from scratch, but rather to look through already existing conversion scripts in πŸ€— Transformers for one that has been used to convert a similar model that was written in the same framework as brand_new_bert. Usually, it is enough to copy an already existing conversion script and slightly adapt it for your use case. Don't hesitate to ask the Hugging Face team to point you to a similar already existing conversion script for your model.
If you are porting a model from TensorFlow to PyTorch, a good starting point might be BERT's conversion script here If you are porting a model from PyTorch to PyTorch, a good starting point might be BART's conversion script here
In the following, we'll quickly explain how PyTorch models store layer weights and define layer names. In PyTorch, the name of a layer is defined by the name of the class attribute you give the layer. Let's define a dummy model in PyTorch, called SimpleModel as follows: thon from torch import nn class SimpleModel(nn.Module): def init(self): super().init() self.dense = nn.Linear(10, 10) self.intermediate = nn.Linear(10, 10) self.layer_norm = nn.LayerNorm(10)
Now we can create an instance of this model definition which will fill all weights: dense, intermediate, layer_norm with random weights. We can print the model to see its architecture thon model = SimpleModel() print(model)
This will print out the following: SimpleModel( (dense): Linear(in_features=10, out_features=10, bias=True) (intermediate): Linear(in_features=10, out_features=10, bias=True) (layer_norm): LayerNorm((10,), eps=1e-05, elementwise_affine=True) ) We can see that the layer names are defined by the name of the class attribute in PyTorch. You can print out the weight values of a specific layer: python print(model.dense.weight.data) to see that the weights were randomly initialized tensor([[-0.0818, 0.2207, -0.0749, -0.0030, 0.0045, -0.1569, -0.1598, 0.0212, -0.2077, 0.2157], [ 0.1044, 0.0201, 0.0990, 0.2482, 0.3116, 0.2509, 0.2866, -0.2190, 0.2166, -0.0212], [-0.2000, 0.1107, -0.1999, -0.3119, 0.1559, 0.0993, 0.1776, -0.1950, -0.1023, -0.0447], [-0.0888, -0.1092, 0.2281, 0.0336, 0.1817, -0.0115, 0.2096, 0.1415, -0.1876, -0.2467], [ 0.2208, -0.2352, -0.1426, -0.2636, -0.2889, -0.2061, -0.2849, -0.0465, 0.2577, 0.0402], [ 0.1502, 0.2465, 0.2566, 0.0693, 0.2352, -0.0530, 0.1859, -0.0604, 0.2132, 0.1680], [ 0.1733, -0.2407, -0.1721, 0.1484, 0.0358, -0.0633, -0.0721, -0.0090, 0.2707, -0.2509], [-0.1173, 0.1561, 0.2945, 0.0595, -0.1996, 0.2988, -0.0802, 0.0407, 0.1829, -0.1568], [-0.1164, -0.2228, -0.0403, 0.0428, 0.1339, 0.0047, 0.1967, 0.2923, 0.0333, -0.0536], [-0.1492, -0.1616, 0.1057, 0.1950, -0.2807, -0.2710, -0.1586, 0.0739, 0.2220, 0.2358]]). In the conversion script, you should fill those randomly initialized weights with the exact weights of the corresponding layer in the checkpoint. E.g. thon retrieve matching layer weights, e.g. by recursive algorithm layer_name = "dense" pretrained_weight = array_of_dense_layer model_pointer = getattr(model, "dense") model_pointer.weight.data = torch.from_numpy(pretrained_weight)
While doing so, you must verify that each randomly initialized weight of your PyTorch model and its corresponding pretrained checkpoint weight exactly match in both shape and name. To do so, it is necessary to add assert statements for the shape and print out the names of the checkpoints weights. E.g. you should add statements like: python assert ( model_pointer.weight.shape == pretrained_weight.shape ), f"Pointer shape of random weight {model_pointer.shape} and array shape of checkpoint weight {pretrained_weight.shape} mismatched" Besides, you should also print out the names of both weights to make sure they match, e.g. python logger.info(f"Initialize PyTorch weight {layer_name} from {pretrained_weight.name}") If either the shape or the name doesn't match, you probably assigned the wrong checkpoint weight to a randomly initialized layer of the πŸ€— Transformers implementation. An incorrect shape is most likely due to an incorrect setting of the config parameters in BrandNewBertConfig() that do not exactly match those that were used for the checkpoint you want to convert. However, it could also be that PyTorch's implementation of a layer requires the weight to be transposed beforehand. Finally, you should also check that all required weights are initialized and print out all checkpoint weights that were not used for initialization to make sure the model is correctly converted. It is completely normal, that the conversion trials fail with either a wrong shape statement or a wrong name assignment. This is most likely because either you used incorrect parameters in BrandNewBertConfig(), have a wrong architecture in the πŸ€— Transformers implementation, you have a bug in the init() functions of one of the components of the πŸ€— Transformers implementation or you need to transpose one of the checkpoint weights. This step should be iterated with the previous step until all weights of the checkpoint are correctly loaded in the Transformers model. Having correctly loaded the checkpoint into the πŸ€— Transformers implementation, you can then save the model under a folder of your choice /path/to/converted/checkpoint/folder that should then contain both a pytorch_model.bin file and a config.json file: python model.save_pretrained("/path/to/converted/checkpoint/folder") 7. Implement the forward pass Having managed to correctly load the pretrained weights into the πŸ€— Transformers implementation, you should now make sure that the forward pass is correctly implemented. In Get familiar with the original repository, you have already created a script that runs a forward pass of the model using the original repository. Now you should write an analogous script using the πŸ€— Transformers implementation instead of the original one. It should look as follows: python model = BrandNewBertModel.from_pretrained("/path/to/converted/checkpoint/folder") input_ids = [0, 4, 4, 3, 2, 4, 1, 7, 19] output = model(input_ids).last_hidden_states It is very likely that the πŸ€— Transformers implementation and the original model implementation don't give the exact same output the very first time or that the forward pass throws an error. Don't be disappointed - it's expected! First, you should make sure that the forward pass doesn't throw any errors. It often happens that the wrong dimensions are used leading to a Dimensionality mismatch error or that the wrong data type object is used, e.g. torch.long instead of torch.float32. Don't hesitate to ask the Hugging Face team for help, if you don't manage to solve certain errors. The final part to make sure the πŸ€— Transformers implementation works correctly is to ensure that the outputs are equivalent to a precision of 1e-3. First, you should ensure that the output shapes are identical, i.e. outputs.shape should yield the same value for the script of the πŸ€— Transformers implementation and the original implementation. Next, you should make sure that the output values are identical as well. This one of the most difficult parts of adding a new model. Common mistakes why the outputs are not identical are:
Some layers were not added, i.e. an activation layer was not added, or the residual connection was forgotten The word embedding matrix was not tied The wrong positional embeddings are used because the original implementation uses on offset Dropout is applied during the forward pass. To fix this make sure model.training is False and that no dropout layer is falsely activated during the forward pass, i.e. pass self.training to PyTorch's functional dropout
The best way to fix the problem is usually to look at the forward pass of the original implementation and the πŸ€— Transformers implementation side-by-side and check if there are any differences. Ideally, you should debug/print out intermediate outputs of both implementations of the forward pass to find the exact position in the network where the πŸ€— Transformers implementation shows a different output than the original implementation. First, make sure that the hard-coded input_ids in both scripts are identical. Next, verify that the outputs of the first transformation of the input_ids (usually the word embeddings) are identical. And then work your way up to the very last layer of the network. At some point, you will notice a difference between the two implementations, which should point you to the bug in the πŸ€— Transformers implementation. From our experience, a simple and efficient way is to add many print statements in both the original implementation and πŸ€— Transformers implementation, at the same positions in the network respectively, and to successively remove print statements showing the same values for intermediate presentations. When you're confident that both implementations yield the same output, verify the outputs with torch.allclose(original_output, output, atol=1e-3), you're done with the most difficult part! Congratulations - the work left to be done should be a cakewalk 😊. 8. Adding all necessary model tests At this point, you have successfully added a new model. However, it is very much possible that the model does not yet fully comply with the required design. To make sure, the implementation is fully compatible with πŸ€— Transformers, all common tests should pass. The Cookiecutter should have automatically added a test file for your model, probably under the same tests/models/brand_new_bert/test_modeling_brand_new_bert.py. Run this test file to verify that all common tests pass:
pytest tests/models/brand_new_bert/test_modeling_brand_new_bert.py Having fixed all common tests, it is now crucial to ensure that all the nice work you have done is well tested, so that a) The community can easily understand your work by looking at specific tests of brand_new_bert b) Future changes to your model will not break any important feature of the model.
At first, integration tests should be added. Those integration tests essentially do the same as the debugging scripts you used earlier to implement the model to πŸ€— Transformers. A template of those model tests has already added by the Cookiecutter, called BrandNewBertModelIntegrationTests and only has to be filled out by you. To ensure that those tests are passing, run RUN_SLOW=1 pytest -sv tests/models/brand_new_bert/test_modeling_brand_new_bert.py::BrandNewBertModelIntegrationTests
RUN_SLOW=1 pytest -sv tests/models/brand_new_bert/test_modeling_brand_new_bert.py::BrandNewBertModelIntegrationTests In case you are using Windows, you should replace RUN_SLOW=1 with SET RUN_SLOW=1 Second, all features that are special to brand_new_bert should be tested additionally in a separate test under BrandNewBertModelTester/`BrandNewBertModelTest. This part is often forgotten but is extremely useful in two ways:
It helps to transfer the knowledge you have acquired during the model addition to the community by showing how the special features of brand_new_bert should work. Future contributors can quickly test changes to the model by running those special tests.
9. Implement the tokenizer Next, we should add the tokenizer of brand_new_bert. Usually, the tokenizer is equivalent to or very similar to an already existing tokenizer of πŸ€— Transformers. It is very important to find/extract the original tokenizer file and to manage to load this file into the πŸ€— Transformers' implementation of the tokenizer. To ensure that the tokenizer works correctly, it is recommended to first create a script in the original repository that inputs a string and returns the `input_ids``. It could look similar to this (in pseudo-code): python input_str = "This is a long example input string containing special characters .$?-, numbers 2872 234 12 and words." model = BrandNewBertModel.load_pretrained_checkpoint("/path/to/checkpoint/") input_ids = model.tokenize(input_str) You might have to take a deeper look again into the original repository to find the correct tokenizer function or you might even have to do changes to your clone of the original repository to only output the input_ids. Having written a functional tokenization script that uses the original repository, an analogous script for πŸ€— Transformers should be created. It should look similar to this: thon from transformers import BrandNewBertTokenizer input_str = "This is a long example input string containing special characters .$?-, numbers 2872 234 12 and words." tokenizer = BrandNewBertTokenizer.from_pretrained("/path/to/tokenizer/folder/") input_ids = tokenizer(input_str).input_ids
When both input_ids yield the same values, as a final step a tokenizer test file should also be added. Analogous to the modeling test files of brand_new_bert, the tokenization test files of brand_new_bert should contain a couple of hard-coded integration tests. 10. Run End-to-end integration tests Having added the tokenizer, you should also add a couple of end-to-end integration tests using both the model and the tokenizer to tests/models/brand_new_bert/test_modeling_brand_new_bert.py in πŸ€— Transformers. Such a test should show on a meaningful text-to-text sample that the πŸ€— Transformers implementation works as expected. A meaningful text-to-text sample can include e.g. a source-to-target-translation pair, an article-to-summary pair, a question-to-answer pair, etc… If none of the ported checkpoints has been fine-tuned on a downstream task it is enough to simply rely on the model tests. In a final step to ensure that the model is fully functional, it is advised that you also run all tests on GPU. It can happen that you forgot to add some .to(self.device) statements to internal tensors of the model, which in such a test would show in an error. In case you have no access to a GPU, the Hugging Face team can take care of running those tests for you. 11. Add Docstring Now, all the necessary functionality for brand_new_bert is added - you're almost done! The only thing left to add is a nice docstring and a doc page. The Cookiecutter should have added a template file called docs/source/model_doc/brand_new_bert.md that you should fill out. Users of your model will usually first look at this page before using your model. Hence, the documentation must be understandable and concise. It is very useful for the community to add some Tips to show how the model should be used. Don't hesitate to ping the Hugging Face team regarding the docstrings. Next, make sure that the docstring added to src/transformers/models/brand_new_bert/modeling_brand_new_bert.py is correct and included all necessary inputs and outputs. We have a detailed guide about writing documentation and our docstring format here. It is always to good to remind oneself that documentation should be treated at least as carefully as the code in πŸ€— Transformers since the documentation is usually the first contact point of the community with the model. Code refactor Great, now you have added all the necessary code for brand_new_bert. At this point, you should correct some potential incorrect code style by running:
make style and verify that your coding style passes the quality check:
make quality There are a couple of other very strict design tests in πŸ€— Transformers that might still be failing, which shows up in the tests of your pull request. This is often because of some missing information in the docstring or some incorrect naming. The Hugging Face team will surely help you if you're stuck here. Lastly, it is always a good idea to refactor one's code after having ensured that the code works correctly. With all tests passing, now it's a good time to go over the added code again and do some refactoring. You have now finished the coding part, congratulation! πŸŽ‰ You are Awesome! 😎 12. Upload the models to the model hub In this final part, you should convert and upload all checkpoints to the model hub and add a model card for each uploaded model checkpoint. You can get familiar with the hub functionalities by reading our Model sharing and uploading Page. You should work alongside the Hugging Face team here to decide on a fitting name for each checkpoint and to get the required access rights to be able to upload the model under the author's organization of brand_new_bert. The push_to_hub method, present in all models in transformers, is a quick and efficient way to push your checkpoint to the hub. A little snippet is pasted below: thon brand_new_bert.push_to_hub("brand_new_bert") Uncomment the following line to push to an organization. brand_new_bert.push_to_hub("/brand_new_bert")
It is worth spending some time to create fitting model cards for each checkpoint. The model cards should highlight the specific characteristics of this particular checkpoint, e.g. On which dataset was the checkpoint pretrained/fine-tuned on? On what down-stream task should the model be used? And also include some code on how to correctly use the model. 13. (Optional) Add notebook It is very helpful to add a notebook that showcases in-detail how brand_new_bert can be used for inference and/or fine-tuned on a downstream task. This is not mandatory to merge your PR, but very useful for the community. 14. Submit your finished PR You're done programming now and can move to the last step, which is getting your PR merged into main. Usually, the Hugging Face team should have helped you already at this point, but it is worth taking some time to give your finished PR a nice description and eventually add comments to your code, if you want to point out certain design choices to your reviewer. Share your work!! Now, it's time to get some credit from the community for your work! Having completed a model addition is a major contribution to Transformers and the whole NLP community. Your code and the ported pre-trained models will certainly be used by hundreds and possibly even thousands of developers and researchers. You should be proud of your work and share your achievements with the community. You have made another model that is super easy to access for everyone in the community! 🀯
Using pipelines for a webserver Creating an inference engine is a complex topic, and the "best" solution will most likely depend on your problem space. Are you on CPU or GPU? Do you want the lowest latency, the highest throughput, support for many models, or just highly optimize 1 specific model? There are many ways to tackle this topic, so what we are going to present is a good default to get started which may not necessarily be the most optimal solution for you.
The key thing to understand is that we can use an iterator, just like you would on a dataset, since a webserver is basically a system that waits for requests and treats them as they come in. Usually webservers are multiplexed (multithreaded, async, etc..) to handle various requests concurrently. Pipelines on the other hand (and mostly the underlying models) are not really great for parallelism; they take up a lot of RAM, so it's best to give them all the available resources when they are running or it's a compute-intensive job. We are going to solve that by having the webserver handle the light load of receiving and sending requests, and having a single thread handling the actual work. This example is going to use starlette. The actual framework is not really important, but you might have to tune or change the code if you are using another one to achieve the same effect. Create server.py:
from starlette.applications import Starlette from starlette.responses import JSONResponse from starlette.routing import Route from transformers import pipeline import asyncio async def homepage(request): payload = await request.body() string = payload.decode("utf-8") response_q = asyncio.Queue() await request.app.model_queue.put((string, response_q)) output = await response_q.get() return JSONResponse(output) async def server_loop(q): pipe = pipeline(model="google-bert/bert-base-uncased") while True: (string, response_q) = await q.get() out = pipe(string) await response_q.put(out) app = Starlette( routes=[ Route("/", homepage, methods=["POST"]), ], ) @app.on_event("startup") async def startup_event(): q = asyncio.Queue() app.model_queue = q asyncio.create_task(server_loop(q))
Now you can start it with: uvicorn server:app And you can query it: ```bash curl -X POST -d "test [MASK]" http://localhost:8000/ [{"score":0.7742936015129089,"token":1012,"token_str":".","sequence":"test."},]
And there you go, now you have a good idea of how to create a webserver! What is really important is that we load the model only once, so there are no copies of the model on the webserver. This way, no unnecessary RAM is being used. Then the queuing mechanism allows you to do fancy stuff like maybe accumulating a few items before inferring to use dynamic batching:
The code sample below is intentionally written like pseudo-code for readability. Do not run this without checking if it makes sense for your system resources!
py (string, rq) = await q.get() strings = [] queues = [] while True: try: (string, rq) = await asyncio.wait_for(q.get(), timeout=0.001) # 1ms except asyncio.exceptions.TimeoutError: break strings.append(string) queues.append(rq) strings outs = pipe(strings, batch_size=len(strings)) for rq, out in zip(queues, outs): await rq.put(out) Again, the proposed code is optimized for readability, not for being the best code. First of all, there's no batch size limit which is usually not a great idea. Next, the timeout is reset on every queue fetch, meaning you could wait much more than 1ms before running the inference (delaying the first request by that much). It would be better to have a single 1ms deadline. This will always wait for 1ms even if the queue is empty, which might not be the best since you probably want to start doing inference if there's nothing in the queue. But maybe it does make sense if batching is really crucial for your use case. Again, there's really no one best solution. Few things you might want to consider Error checking There's a lot that can go wrong in production: out of memory, out of space, loading the model might fail, the query might be wrong, the query might be correct but still fail to run because of a model misconfiguration, and so on. Generally, it's good if the server outputs the errors to the user, so adding a lot of try..except statements to show those errors is a good idea. But keep in mind it may also be a security risk to reveal all those errors depending on your security context. Circuit breaking Webservers usually look better when they do circuit breaking. It means they return proper errors when they're overloaded instead of just waiting for the query indefinitely. Return a 503 error instead of waiting for a super long time or a 504 after a long time. This is relatively easy to implement in the proposed code since there is a single queue. Looking at the queue size is a basic way to start returning errors before your webserver fails under load. Blocking the main thread Currently PyTorch is not async aware, and computation will block the main thread while running. That means it would be better if PyTorch was forced to run on its own thread/process. This wasn't done here because the code is a lot more complex (mostly because threads and async and queues don't play nice together). But ultimately it does the same thing. This would be important if the inference of single items were long (> 1s) because in this case, it means every query during inference would have to wait for 1s before even receiving an error. Dynamic batching In general, batching is not necessarily an improvement over passing 1 item at a time (see batching details for more information). But it can be very effective when used in the correct setting. In the API, there is no dynamic batching by default (too much opportunity for a slowdown). But for BLOOM inference - which is a very large model - dynamic batching is essential to provide a decent experience for everyone.
Summary of the tokenizers [[open-in-colab]] On this page, we will have a closer look at tokenization.
As we saw in the preprocessing tutorial, tokenizing a text is splitting it into words or subwords, which then are converted to ids through a look-up table. Converting words or subwords to ids is straightforward, so in this summary, we will focus on splitting a text into words or subwords (i.e. tokenizing a text). More specifically, we will look at the three main types of tokenizers used in πŸ€— Transformers: Byte-Pair Encoding (BPE), WordPiece, and SentencePiece, and show examples of which tokenizer type is used by which model. Note that on each model page, you can look at the documentation of the associated tokenizer to know which tokenizer type was used by the pretrained model. For instance, if we look at [BertTokenizer], we can see that the model uses WordPiece. Introduction Splitting a text into smaller chunks is a task that is harder than it looks, and there are multiple ways of doing so. For instance, let's look at the sentence "Don't you love πŸ€— Transformers? We sure do."
A simple way of tokenizing this text is to split it by spaces, which would give: ["Don't", "you", "love", "πŸ€—", "Transformers?", "We", "sure", "do."] This is a sensible first step, but if we look at the tokens "Transformers?" and "do.", we notice that the punctuation is attached to the words "Transformer" and "do", which is suboptimal. We should take the punctuation into account so that a model does not have to learn a different representation of a word and every possible punctuation symbol that could follow it, which would explode the number of representations the model has to learn. Taking punctuation into account, tokenizing our exemplary text would give: ["Don", "'", "t", "you", "love", "πŸ€—", "Transformers", "?", "We", "sure", "do", "."] Better. However, it is disadvantageous, how the tokenization dealt with the word "Don't". "Don't" stands for "do not", so it would be better tokenized as ["Do", "n't"]. This is where things start getting complicated, and part of the reason each model has its own tokenizer type. Depending on the rules we apply for tokenizing a text, a different tokenized output is generated for the same text. A pretrained model only performs properly if you feed it an input that was tokenized with the same rules that were used to tokenize its training data. spaCy and Moses are two popular rule-based tokenizers. Applying them on our example, spaCy and Moses would output something like: ["Do", "n't", "you", "love", "πŸ€—", "Transformers", "?", "We", "sure", "do", "."] As can be seen space and punctuation tokenization, as well as rule-based tokenization, is used here. Space and punctuation tokenization and rule-based tokenization are both examples of word tokenization, which is loosely defined as splitting sentences into words. While it's the most intuitive way to split texts into smaller chunks, this tokenization method can lead to problems for massive text corpora. In this case, space and punctuation tokenization usually generates a very big vocabulary (the set of all unique words and tokens used). E.g., Transformer XL uses space and punctuation tokenization, resulting in a vocabulary size of 267,735! Such a big vocabulary size forces the model to have an enormous embedding matrix as the input and output layer, which causes both an increased memory and time complexity. In general, transformers models rarely have a vocabulary size greater than 50,000, especially if they are pretrained only on a single language. So if simple space and punctuation tokenization is unsatisfactory, why not simply tokenize on characters?
While character tokenization is very simple and would greatly reduce memory and time complexity it makes it much harder for the model to learn meaningful input representations. E.g. learning a meaningful context-independent representation for the letter "t" is much harder than learning a context-independent representation for the word "today". Therefore, character tokenization is often accompanied by a loss of performance. So to get the best of both worlds, transformers models use a hybrid between word-level and character-level tokenization called subword tokenization. Subword tokenization
Subword tokenization algorithms rely on the principle that frequently used words should not be split into smaller subwords, but rare words should be decomposed into meaningful subwords. For instance "annoyingly" might be considered a rare word and could be decomposed into "annoying" and "ly". Both "annoying" and "ly" as stand-alone subwords would appear more frequently while at the same time the meaning of "annoyingly" is kept by the composite meaning of "annoying" and "ly". This is especially useful in agglutinative languages such as Turkish, where you can form (almost) arbitrarily long complex words by stringing together subwords. Subword tokenization allows the model to have a reasonable vocabulary size while being able to learn meaningful context-independent representations. In addition, subword tokenization enables the model to process words it has never seen before, by decomposing them into known subwords. For instance, the [~transformers.BertTokenizer] tokenizes "I have a new GPU!" as follows:
from transformers import BertTokenizer tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased") tokenizer.tokenize("I have a new GPU!") ["i", "have", "a", "new", "gp", "##u", "!"]
Because we are considering the uncased model, the sentence was lowercased first. We can see that the words ["i", "have", "a", "new"] are present in the tokenizer's vocabulary, but the word "gpu" is not. Consequently, the tokenizer splits "gpu" into known subwords: ["gp" and "##u"]. "##" means that the rest of the token should be attached to the previous one, without space (for decoding or reversal of the tokenization). As another example, [~transformers.XLNetTokenizer] tokenizes our previously exemplary text as follows:
from transformers import XLNetTokenizer tokenizer = XLNetTokenizer.from_pretrained("xlnet/xlnet-base-cased") tokenizer.tokenize("Don't you love πŸ€— Transformers? We sure do.") ["▁Don", "'", "t", "▁you", "▁love", "▁", "πŸ€—", "▁", "Transform", "ers", "?", "▁We", "▁sure", "▁do", "."]
We'll get back to the meaning of those "▁" when we look at SentencePiece. As one can see, the rare word "Transformers" has been split into the more frequent subwords "Transform" and "ers". Let's now look at how the different subword tokenization algorithms work. Note that all of those tokenization algorithms rely on some form of training which is usually done on the corpus the corresponding model will be trained on.
Byte-Pair Encoding (BPE) Byte-Pair Encoding (BPE) was introduced in Neural Machine Translation of Rare Words with Subword Units (Sennrich et al., 2015). BPE relies on a pre-tokenizer that splits the training data into words. Pretokenization can be as simple as space tokenization, e.g. GPT-2, RoBERTa. More advanced pre-tokenization include rule-based tokenization, e.g. XLM, FlauBERT which uses Moses for most languages, or GPT which uses spaCy and ftfy, to count the frequency of each word in the training corpus. After pre-tokenization, a set of unique words has been created and the frequency with which each word occurred in the training data has been determined. Next, BPE creates a base vocabulary consisting of all symbols that occur in the set of unique words and learns merge rules to form a new symbol from two symbols of the base vocabulary. It does so until the vocabulary has attained the desired vocabulary size. Note that the desired vocabulary size is a hyperparameter to define before training the tokenizer. As an example, let's assume that after pre-tokenization, the following set of words including their frequency has been determined: ("hug", 10), ("pug", 5), ("pun", 12), ("bun", 4), ("hugs", 5) Consequently, the base vocabulary is ["b", "g", "h", "n", "p", "s", "u"]. Splitting all words into symbols of the base vocabulary, we obtain: ("h" "u" "g", 10), ("p" "u" "g", 5), ("p" "u" "n", 12), ("b" "u" "n", 4), ("h" "u" "g" "s", 5) BPE then counts the frequency of each possible symbol pair and picks the symbol pair that occurs most frequently. In the example above "h" followed by "u" is present 10 + 5 = 15 times (10 times in the 10 occurrences of "hug", 5 times in the 5 occurrences of "hugs"). However, the most frequent symbol pair is "u" followed by "g", occurring 10 + 5 + 5 = 20 times in total. Thus, the first merge rule the tokenizer learns is to group all "u" symbols followed by a "g" symbol together. Next, "ug" is added to the vocabulary. The set of words then becomes ("h" "ug", 10), ("p" "ug", 5), ("p" "u" "n", 12), ("b" "u" "n", 4), ("h" "ug" "s", 5) BPE then identifies the next most common symbol pair. It's "u" followed by "n", which occurs 16 times. "u", "n" is merged to "un" and added to the vocabulary. The next most frequent symbol pair is "h" followed by "ug", occurring 15 times. Again the pair is merged and "hug" can be added to the vocabulary. At this stage, the vocabulary is ["b", "g", "h", "n", "p", "s", "u", "ug", "un", "hug"] and our set of unique words is represented as ("hug", 10), ("p" "ug", 5), ("p" "un", 12), ("b" "un", 4), ("hug" "s", 5) Assuming, that the Byte-Pair Encoding training would stop at this point, the learned merge rules would then be applied to new words (as long as those new words do not include symbols that were not in the base vocabulary). For instance, the word "bug" would be tokenized to ["b", "ug"] but "mug" would be tokenized as ["<unk>", "ug"] since the symbol "m" is not in the base vocabulary. In general, single letters such as "m" are not replaced by the "<unk>" symbol because the training data usually includes at least one occurrence of each letter, but it is likely to happen for very special characters like emojis. As mentioned earlier, the vocabulary size, i.e. the base vocabulary size + the number of merges, is a hyperparameter to choose. For instance GPT has a vocabulary size of 40,478 since they have 478 base characters and chose to stop training after 40,000 merges. Byte-level BPE A base vocabulary that includes all possible base characters can be quite large if e.g. all unicode characters are considered as base characters. To have a better base vocabulary, GPT-2 uses bytes as the base vocabulary, which is a clever trick to force the base vocabulary to be of size 256 while ensuring that every base character is included in the vocabulary. With some additional rules to deal with punctuation, the GPT2's tokenizer can tokenize every text without the need for the symbol. GPT-2 has a vocabulary size of 50,257, which corresponds to the 256 bytes base tokens, a special end-of-text token and the symbols learned with 50,000 merges.
WordPiece WordPiece is the subword tokenization algorithm used for BERT, DistilBERT, and Electra. The algorithm was outlined in Japanese and Korean Voice Search (Schuster et al., 2012) and is very similar to BPE. WordPiece first initializes the vocabulary to include every character present in the training data and progressively learns a given number of merge rules. In contrast to BPE, WordPiece does not choose the most frequent symbol pair, but the one that maximizes the likelihood of the training data once added to the vocabulary. So what does this mean exactly? Referring to the previous example, maximizing the likelihood of the training data is equivalent to finding the symbol pair, whose probability divided by the probabilities of its first symbol followed by its second symbol is the greatest among all symbol pairs. E.g. "u", followed by "g" would have only been merged if the probability of "ug" divided by "u", "g" would have been greater than for any other symbol pair. Intuitively, WordPiece is slightly different to BPE in that it evaluates what it loses by merging two symbols to ensure it's worth it.
Unigram Unigram is a subword tokenization algorithm introduced in Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates (Kudo, 2018). In contrast to BPE or WordPiece, Unigram initializes its base vocabulary to a large number of symbols and progressively trims down each symbol to obtain a smaller vocabulary. The base vocabulary could for instance correspond to all pre-tokenized words and the most common substrings. Unigram is not used directly for any of the models in the transformers, but it's used in conjunction with SentencePiece. At each training step, the Unigram algorithm defines a loss (often defined as the log-likelihood) over the training data given the current vocabulary and a unigram language model. Then, for each symbol in the vocabulary, the algorithm computes how much the overall loss would increase if the symbol was to be removed from the vocabulary. Unigram then removes p (with p usually being 10% or 20%) percent of the symbols whose loss increase is the lowest, i.e. those symbols that least affect the overall loss over the training data. This process is repeated until the vocabulary has reached the desired size. The Unigram algorithm always keeps the base characters so that any word can be tokenized. Because Unigram is not based on merge rules (in contrast to BPE and WordPiece), the algorithm has several ways of tokenizing new text after training. As an example, if a trained Unigram tokenizer exhibits the vocabulary: ["b", "g", "h", "n", "p", "s", "u", "ug", "un", "hug"], "hugs" could be tokenized both as ["hug", "s"], ["h", "ug", "s"] or ["h", "u", "g", "s"]. So which one to choose? Unigram saves the probability of each token in the training corpus on top of saving the vocabulary so that the probability of each possible tokenization can be computed after training. The algorithm simply picks the most likely tokenization in practice, but also offers the possibility to sample a possible tokenization according to their probabilities. Those probabilities are defined by the loss the tokenizer is trained on. Assuming that the training data consists of the words \(x_{1}, \dots, x_{N}\) and that the set of all possible tokenizations for a word \(x_{i}\) is defined as \(S(x_{i})\), then the overall loss is defined as $$\mathcal{L} = -\sum_{i=1}^{N} \log \left ( \sum_{x \in S(x_{i})} p(x) \right )$$
SentencePiece All tokenization algorithms described so far have the same problem: It is assumed that the input text uses spaces to separate words. However, not all languages use spaces to separate words. One possible solution is to use language specific pre-tokenizers, e.g. XLM uses a specific Chinese, Japanese, and Thai pre-tokenizer). To solve this problem more generally, SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text Processing (Kudo et al., 2018) treats the input as a raw input stream, thus including the space in the set of characters to use. It then uses the BPE or unigram algorithm to construct the appropriate vocabulary. The [XLNetTokenizer] uses SentencePiece for example, which is also why in the example earlier the "▁" character was included in the vocabulary. Decoding with SentencePiece is very easy since all tokens can just be concatenated and "▁" is replaced by a space. All transformers models in the library that use SentencePiece use it in combination with unigram. Examples of models using SentencePiece are ALBERT, XLNet, Marian, and T5.
DeepSpeed DeepSpeed is a PyTorch optimization library that makes distributed training memory-efficient and fast. At it's core is the Zero Redundancy Optimizer (ZeRO) which enables training large models at scale. ZeRO works in several stages: ZeRO-1, optimizer state partioning across GPUs ZeRO-2, gradient partitioning across GPUs ZeRO-3, parameteter partitioning across GPUs