Search is not available for this dataset
Models The base classes [PreTrainedModel], [TFPreTrainedModel], and [FlaxPreTrainedModel] implement the common methods for loading/saving a model either from a local file or directory, or from a pretrained model configuration provided by the library (downloaded from HuggingFace's AWS S3 repository). [PreTrainedModel] and [TFPreTrainedModel] also implement a few methods which are common among all the models to: resize the input token embeddings when new tokens are added to the vocabulary prune the attention heads of the model. The other methods that are common to each model are defined in [~modeling_utils.ModuleUtilsMixin] (for the PyTorch models) and [~modeling_tf_utils.TFModuleUtilsMixin] (for the TensorFlow models) or for text generation, [~generation.GenerationMixin] (for the PyTorch models), [~generation.TFGenerationMixin] (for the TensorFlow models) and [~generation.FlaxGenerationMixin] (for the Flax/JAX models). PreTrainedModel [[autodoc]] PreTrainedModel - push_to_hub - all Large model loading In Transformers 4.20.0, the [~PreTrainedModel.from_pretrained] method has been reworked to accommodate large models using Accelerate. This requires Accelerate >= 0.9.0 and PyTorch >= 1.9.0. Instead of creating the full model, then loading the pretrained weights inside it (which takes twice the size of the model in RAM, one for the randomly initialized model, one for the weights), there is an option to create the model as an empty shell, then only materialize its parameters when the pretrained weights are loaded. This option can be activated with low_cpu_mem_usage=True. The model is first created on the Meta device (with empty weights) and the state dict is then loaded inside it (shard by shard in the case of a sharded checkpoint). This way the maximum RAM used is the full size of the model only. from transformers import AutoModelForSeq2SeqLM t0pp = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0pp", low_cpu_mem_usage=True) Moreover, you can directly place the model on different devices if it doesn't fully fit in RAM (only works for inference for now). With device_map="auto", Accelerate will determine where to put each layer to maximize the use of your fastest devices (GPUs) and offload the rest on the CPU, or even the hard drive if you don't have enough GPU RAM (or CPU RAM). Even if the model is split across several devices, it will run as you would normally expect. When passing a device_map, low_cpu_mem_usage is automatically set to True, so you don't need to specify it: from transformers import AutoModelForSeq2SeqLM t0pp = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0pp", device_map="auto") You can inspect how the model was split across devices by looking at its hf_device_map attribute: py t0pp.hf_device_map python out {'shared': 0, 'decoder.embed_tokens': 0, 'encoder': 0, 'decoder.block.0': 0, 'decoder.block.1': 1, 'decoder.block.2': 1, 'decoder.block.3': 1, 'decoder.block.4': 1, 'decoder.block.5': 1, 'decoder.block.6': 1, 'decoder.block.7': 1, 'decoder.block.8': 1, 'decoder.block.9': 1, 'decoder.block.10': 1, 'decoder.block.11': 1, 'decoder.block.12': 1, 'decoder.block.13': 1, 'decoder.block.14': 1, 'decoder.block.15': 1, 'decoder.block.16': 1, 'decoder.block.17': 1, 'decoder.block.18': 1, 'decoder.block.19': 1, 'decoder.block.20': 1, 'decoder.block.21': 1, 'decoder.block.22': 'cpu', 'decoder.block.23': 'cpu', 'decoder.final_layer_norm': 'cpu', 'decoder.dropout': 'cpu', 'lm_head': 'cpu'} You can also write your own device map following the same format (a dictionary layer name to device). It should map all parameters of the model to a given device, but you don't have to detail where all the submodules of one layer go if that layer is entirely on the same device. For instance, the following device map would work properly for T0pp (as long as you have the GPU memory): python device_map = {"shared": 0, "encoder": 0, "decoder": 1, "lm_head": 1} Another way to minimize the memory impact of your model is to instantiate it at a lower precision dtype (like torch.float16) or use direct quantization techniques as described below. Model Instantiation dtype Under Pytorch a model normally gets instantiated with torch.float32 format. This can be an issue if one tries to load a model whose weights are in fp16, since it'd require twice as much memory. To overcome this limitation, you can either explicitly pass the desired dtype using torch_dtype argument: python model = T5ForConditionalGeneration.from_pretrained("t5", torch_dtype=torch.float16) or, if you want the model to always load in the most optimal memory pattern, you can use the special value "auto", and then dtype will be automatically derived from the model's weights: python model = T5ForConditionalGeneration.from_pretrained("t5", torch_dtype="auto") Models instantiated from scratch can also be told which dtype to use with: python config = T5Config.from_pretrained("t5") model = AutoModel.from_config(config) Due to Pytorch design, this functionality is only available for floating dtypes. ModuleUtilsMixin [[autodoc]] modeling_utils.ModuleUtilsMixin TFPreTrainedModel [[autodoc]] TFPreTrainedModel - push_to_hub - all TFModelUtilsMixin [[autodoc]] modeling_tf_utils.TFModelUtilsMixin FlaxPreTrainedModel [[autodoc]] FlaxPreTrainedModel - push_to_hub - all Pushing to the Hub [[autodoc]] utils.PushToHubMixin Sharded checkpoints [[autodoc]] modeling_utils.load_sharded_checkpoint
stringlengths
161
226k
Before you begin, make sure you have all the necessary libraries installed: pip install transformers datasets evaluate We encourage you to log in to your Hugging Face account so you can upload and share your model with the community. When prompted, enter your token to log in: from huggingface_hub import notebook_lo...
Efficient Inference on CPU This guide focuses on inferencing large models efficiently on CPU. BetterTransformer for faster inference We have recently integrated BetterTransformer for faster inference on CPU for text, image and audio models. Check the documentation about this integration here for more details. PyTorch ...
Attention mechanisms Most transformer models use full attention in the sense that the attention matrix is square. It can be a big computational bottleneck when you have long texts. Longformer and reformer are models that try to be more efficient and use a sparse version of the attention matrix to speed up training. LS...
How to convert a 🤗 Transformers model to TensorFlow? Having multiple frameworks available to use with 🤗 Transformers gives you flexibility to play their strengths when designing your application, but it implies that compatibility must be added on a per-model basis. The good news is that adding TensorFlow compatibili...
Installation Install 🤗 Transformers for whichever deep learning library you're working with, setup your cache, and optionally configure 🤗 Transformers to run offline. 🤗 Transformers is tested on Python 3.6+, PyTorch 1.1.0+, TensorFlow 2.0+, and Flax. Follow the installation instructions below for the deep learning ...
The Transformer model family Since its introduction in 2017, the original Transformer model has inspired many new and exciting models that extend beyond natural language processing (NLP) tasks. There are models for predicting the folded structure of proteins, training a cheetah to run, and time series forecasting. Wit...
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 i...
Custom Tools and Prompts If you are not aware of what tools and agents are in the context of transformers, we recommend you read the Transformers Agents page first. Transformers Agent is an experimental API that is subject to change at any time. Results returned by the agents can vary as the APIs or underlying model...
Custom hardware for training The hardware you use to run model training and inference can have a big effect on performance. For a deep dive into GPUs make sure to check out Tim Dettmer's excellent blog post. Let's have a look at some practical advice for GPU setups. GPU When you train bigger models you have essentiall...
Multilingual models for inference [[open-in-colab]] There are several multilingual models in 🤗 Transformers, and their inference usage differs from monolingual models. Not all multilingual model usage is different though. Some models, like bert-base-multilingual-uncased, can be used just like a monolingual model. Thi...
What 🤗 Transformers can do 🤗 Transformers is a library of pretrained state-of-the-art models for natural language processing (NLP), computer vision, and audio and speech processing tasks. Not only does the library contain Transformer models, but it also has non-Transformer models like modern convolutional networks f...
Model outputs All models have outputs that are instances of subclasses of [~utils.ModelOutput]. Those are data structures containing all the information returned by the model, but that can also be used as tuples or dictionaries. Let's see how this looks in an example: thon from transformers import BertTokenizer, BertF...
General Utilities This page lists all of Transformers general utility functions that are found in the file utils.py. Most of those are only useful if you are studying the general code in the library. Enums and namedtuples [[autodoc]] utils.ExplicitEnum [[autodoc]] utils.PaddingStrategy [[autodoc]] utils.TensorType Spe...
docstyle-ignore INSTALL_CONTENT = """ Transformers installation ! pip install transformers datasets To install from source instead of the last release, comment the command above and uncomment the following one. ! pip install git+https://github.com/huggingface/transformers.git """ notebook_first_cells = [{"type": "code"...
Share a model The last two tutorials showed how you can fine-tune a model with PyTorch, Keras, and 🤗 Accelerate for distributed setups. The next step is to share your model with the community! At Hugging Face, we believe in openly sharing knowledge and resources to democratize artificial intelligence for everyone. We...
Text generation strategies Text generation is essential to many NLP tasks, such as open-ended text generation, summarization, translation, and more. It also plays a role in a variety of mixed-modality applications that have text as an output like speech-to-text and vision-to-text. Some of the models that can generate ...
Logging 🤗 Transformers has a centralized logging system, so that you can setup the verbosity of the library easily. Currently the default verbosity of the library is WARNING. To change the level of verbosity, just use one of the direct setters. For instance, here is how to change the verbosity to the INFO level. thon...
Load pretrained instances with an AutoClass With so many different Transformer architectures, it can be challenging to create one for your checkpoint. As a part of 🤗 Transformers core philosophy to make the library easy, simple and flexible to use, an AutoClass automatically infer and load the correct architecture fr...
Utilities for Image Processors This page lists all the utility functions used by the image processors, mainly the functional transformations used to process the images. Most of those are only useful if you are studying the code of the image processors in the library. Image Transformations [[autodoc]] image_transforms....
Philosophy 🤗 Transformers is an opinionated library built for: machine learning researchers and educators seeking to use, study or extend large-scale Transformers models. hands-on practitioners who want to fine-tune those models or serve them in production, or both. engineers who just want to download a pretrained m...
Benchmarks Hugging Face's Benchmarking tools are deprecated and it is advised to use external Benchmarking libraries to measure the speed and memory complexity of Transformer models. [[open-in-colab]] Let's take a look at how 🤗 Transformers models can be benchmarked, best practices, and already available benchmark...
Distributed training with 🤗 Accelerate As models get bigger, parallelism has emerged as a strategy for training larger models on limited hardware and accelerating training speed by several orders of magnitude. At Hugging Face, we created the 🤗 Accelerate library to help users easily train a 🤗 Transformers model on ...
Image captioning [[open-in-colab]] Image captioning is the task of predicting a caption for a given image. Common real world applications of it include aiding visually impaired people that can help them navigate through different situations. Therefore, image captioning helps to improve content accessibility for people...
Model training anatomy To understand performance optimization techniques that one can apply to improve efficiency of model training speed and memory utilization, it's helpful to get familiar with how GPU is utilized during training, and how compute intensity varies depending on an operation performed. Let's start by...
Run training on Amazon SageMaker The documentation has been moved to hf.co/docs/sagemaker. This page will be removed in transformers 5.0. Table of Content Train Hugging Face models on Amazon SageMaker with the SageMaker Python SDK Deploy Hugging Face models to Amazon SageMaker with the SageMaker Python SDK Frequentl...
Performance and Scalability Training large transformer models and deploying them to production present various challenges. During training, the model may require more GPU memory than available or exhibit slow training speed. In the deployment phase, the model can struggle to handle the required throughput in a produc...
Tokenizer A tokenizer is in charge of preparing the inputs for a model. The library contains tokenizers for all the models. Most of the tokenizers are available in two flavors: a full python implementation and a "Fast" implementation based on the Rust library 🤗 Tokenizers. The "Fast" implementations allows: a signif...
Text to speech [[open-in-colab]] Text-to-speech (TTS) is the task of creating natural-sounding speech from text, where the speech can be generated in multiple languages and for multiple speakers. The only text-to-speech model currently available in 🤗 Transformers is SpeechT5, though more will be added in the future...
Inference on Specialized Hardware This document will be completed soon with information on how to infer on specialized hardware. In the meantime you can check out the guide for inference on CPUs.
Exporting 🤗 Transformers models to ONNX 🤗 Transformers provides a transformers.onnx package that enables you to convert model checkpoints to an ONNX graph by leveraging configuration objects. See the guide on exporting 🤗 Transformers models for more details. ONNX Configurations We provide three abstract classes tha...
Instantiating a big model When you want to use a very big pretrained model, one challenge is to minimize the use of the RAM. The usual workflow from PyTorch is: Create your model with random weights. Load your pretrained weights. Put those pretrained weights in your random model. Step 1 and 2 both require a full ver...
Time Series Utilities This page lists all the utility functions and classes that can be used for Time Series based models. Most of those are only useful if you are studying the code of the time series models or you wish to add to the collection of distributional output classes. Distributional Output [[autodoc]] time_s...
Trainer The [Trainer] class provides an API for feature-complete training in PyTorch for most standard use cases. It's used in most of the example scripts. Before instantiating your [Trainer], create a [TrainingArguments] to access all the points of customization during training. The API supports distributed training ...
Export to ONNX Deploying 🤗 Transformers models in production environments often requires, or can benefit from exporting the models into a serialized format that can be loaded and executed on specialized runtimes and hardware. 🤗 Optimum is an extension of Transformers that enables exporting models from PyTorch or Te...
🤗 Transformers Notebooks You can find here a list of the official notebooks provided by Hugging Face. Also, we would like to list here interesting content created by the community. If you wrote some notebook(s) leveraging 🤗 Transformers and would like be listed here, please open a Pull Request so it can be included ...
Before you begin, make sure you have all the necessary libraries installed: pip install transformers datasets evaluate We encourage you to login to your Hugging Face account so you can upload and share your model with the community. When prompted, enter your token to login: from huggingface_hub import notebook_logi...
How 🤗 Transformers solve tasks In What 🤗 Transformers can do, you learned about natural language processing (NLP), speech and audio, computer vision tasks, and some important applications of them. This page will look closely at how models solve these tasks and explain what's happening under the hood. There are many ...
How to create a custom pipeline? In this guide, we will see how to create a custom pipeline and share it on the Hub or add it to the 🤗 Transformers library. First and foremost, you need to decide the raw entries the pipeline will be able to take. It can be strings, raw bytes, dictionaries or whatever seems to be the ...
Agents & Tools Transformers Agent is an experimental API which is subject to change at any time. Results returned by the agents can vary as the APIs or underlying models are prone to change. To learn more about agents and tools make sure to read the introductory guide. This page contains the API docs for the underly...
Before you begin, make sure you have all the necessary libraries installed: pip install transformers datasets evaluate We encourage you to log in to your Hugging Face account so you can upload and share your model with the community. When prompted, enter your token to log in: from huggingface_hub import notebook_lo...
Export to TorchScript This is the very beginning of our experiments with TorchScript and we are still exploring its capabilities with variable-input-size models. It is a focus of interest to us and we will deepen our analysis in upcoming releases, with more code examples, a more flexible implementation, and benchmark...
Methods and tools for efficient training on a single GPU This guide demonstrates practical techniques that you can use to increase the efficiency of your model's training by optimizing memory utilization, speeding up the training, or both. If you'd like to understand how GPU is utilized during training, please refer...
Before you begin, make sure you have all the necessary libraries installed: pip install transformers datasets evaluate jiwer We encourage you to login to your Hugging Face account so you can upload and share your model with the community. When prompted, enter your token to login: from huggingface_hub import noteboo...
Efficient Training on Multiple CPUs When training on a single CPU is too slow, we can use multiple CPUs. This guide focuses on PyTorch-based DDP enabling distributed CPU training efficiently. Intel® oneCCL Bindings for PyTorch Intel® oneCCL (collective communications library) is a library for efficient distributed dee...
Community This page regroups resources around 🤗 Transformers developed by the community. Community resources: | Resource | Description | Author | |:----------|:-------------|------:| | Hugging Face Transformers Glossary Flashcards | A set of flashcards based on the Transformers Docs Glossary t...
Before you begin, make sure you have all the necessary libraries installed: pip install transformers datasets evaluate seqeval We encourage you to login to your Hugging Face account so you can upload and share your model with the community. When prompted, enter your token to login: from huggingface_hub import noteb...
Efficient Inference on a Multiple GPUs This document contains information on how to efficiently infer on a multiple GPUs. Note: A multi GPU setup can use the majority of the strategies described in the single GPU section. You must be aware of simple techniques, though, that can be used for a better usage. BetterTra...
BERTology There is a growing field of study concerned with investigating the inner working of large-scale transformers like BERT (that some call "BERTology"). Some good examples of this field are: BERT Rediscovers the Classical NLP Pipeline by Ian Tenney, Dipanjan Das, Ellie Pavlick: https://arxiv.org/abs/1905.0595...
Pipelines The pipelines are a great and easy way to use models for inference. These pipelines are objects that abstract most of the complex code from the library, offering a simple API dedicated to several tasks, including Named Entity Recognition, Masked Language Modeling, Sentiment Analysis, Feature Extraction and Q...
Testing Let's take a look at how 🤗 Transformers models are tested and how you can write new tests and improve the existing ones. There are 2 test suites in the repository: tests -- tests for the general API examples -- tests primarily for various applications that aren't part of the API How transformers are tested ...
Configuration The base class [PretrainedConfig] implements the common methods for loading/saving a configuration either from a local file or directory, or from a pretrained model configuration provided by the library (downloaded from HuggingFace's AWS S3 repository). Each derived config class implements model specific...
null
Utilities for Tokenizers This page lists all the utility functions used by the tokenizers, mainly the class [~tokenization_utils_base.PreTrainedTokenizerBase] that implements the common methods between [PreTrainedTokenizer] and [PreTrainedTokenizerFast] and the mixin [~tokenization_utils_base.SpecialTokensMixin]. Most...
Create a custom architecture An AutoClass automatically infers the model architecture and downloads pretrained configuration and weights. Generally, we recommend using an AutoClass to produce checkpoint-agnostic code. But users who want more control over specific model parameters can create a custom 🤗 Transformers mo...
Debugging Multi-GPU Network Issues Debug When training or inferencing with DistributedDataParallel and multiple GPU, if you run into issue of inter-communication between processes and/or nodes, you can use the following script to diagnose network issues. wget https://raw.githubusercontent.com/huggingface/transformers...
Custom Layers and Utilities This page lists all the custom layers used by the library, as well as the utility functions it provides for modeling. Most of those are only useful if you are studying the code of the models in the library. Pytorch custom modules [[autodoc]] pytorch_utils.Conv1D [[autodoc]] modeling_utils.P...
Training on TPUs Note: Most of the strategies introduced in the single GPU section (such as mixed precision training or gradient accumulation) and multi-GPU section are generic and apply to training models in general so make sure to have a look at it before diving into this section. This document will be completed s...
Notes: if you need to run on a specific GPU, which is different from GPU 0, you can't use CUDA_VISIBLE_DEVICES to limit the visible scope of available GPUs. Instead, you have to use the following syntax: deepspeed --include localhost:1 examples/pytorch/translation/run_translation.py In this example, we tell Dee...
Image Processor An image processor is in charge of preparing input features for vision models and post processing their outputs. This includes transformations such as resizing, normalization, and conversion to PyTorch, TensorFlow, Flax and Numpy tensors. It may also include model specific post-processing such as conve...
Sharing custom models The 🤗 Transformers library is designed to be easily extensible. Every model is fully coded in a given subfolder of the repository with no abstraction, so you can easily copy a modeling file and tweak it to your needs. If you are writing a brand new model, it might be easier to start from scratch...
Training on TPU with TensorFlow If you don't need long explanations and just want TPU code samples to get started with, check out our TPU example notebook! What is a TPU? A TPU is a Tensor Processing Unit. They are hardware designed by Google, which are used to greatly speed up the tensor computations within neural ...
Quick tour [[open-in-colab]] Get up and running with 🤗 Transformers! Whether you're a developer or an everyday user, this quick tour will help you get started and show you how to use the [pipeline] for inference, load a pretrained model and preprocessor with an AutoClass, and quickly train a model with PyTorch or Ten...
Before you begin, make sure you have all the necessary libraries installed: pip install transformers datasets evaluate rouge_score We encourage you to login to your Hugging Face account so you can upload and share your model with the community. When prompted, enter your token to login: from huggingface_hub import n...
Efficient Training on CPU This guide focuses on training large models efficiently on CPU. Mixed precision with IPEX IPEX is optimized for CPUs with AVX-512 or above, and functionally works for CPUs with only AVX2. So, it is expected to bring performance benefit for Intel CPU generations with AVX-512 or above while CPU...
Quantize 🤗 Transformers models bitsandbytes Integration 🤗 Transformers is closely integrated with most used modules on bitsandbytes. You can load your model in 8-bit precision with few lines of code. This is supported by most of the GPU hardwares since the 0.37.0 release of bitsandbytes. Learn more about the quantiz...
Hyperparameter Search using Trainer API 🤗 Transformers provides a [Trainer] class optimized for training 🤗 Transformers models, making it easier to start training without manually writing your own training loop. The [Trainer] provides API for hyperparameter search. This doc shows how to enable it in example. Hyperp...
Before you begin, make sure you have all the necessary libraries installed: pip install transformers datasets evaluate We encourage you to login to your Hugging Face account so you can upload and share your model with the community. When prompted, enter your token to login: from huggingface_hub import notebook_logi...
Callbacks Callbacks are objects that can customize the behavior of the training loop in the PyTorch [Trainer] (this feature is not yet implemented in TensorFlow) that can inspect the training loop state (for progress reporting, logging on TensorBoard or other ML platforms) and take decisions (like early stopping). Cal...
Zero-shot object detection [[open-in-colab]] Traditionally, models used for object detection require labeled image datasets for training, and are limited to detecting the set of classes from the training data. Zero-shot object detection is supported by the OWL-ViT model which uses a different approach. OWL-ViT is an o...
Before you begin, make sure you have all the necessary libraries installed: pip install transformers datasets evaluate sacrebleu We encourage you to login to your Hugging Face account so you can upload and share your model with the community. When prompted, enter your token to login: from huggingface_hub import not...
LayoutLMv2 solves the document question-answering task by adding a question-answering head on top of the final hidden states of the tokens, to predict the positions of the start and end tokens of the answer. In other words, the problem is treated as extractive question answering: given the context, extract which piec...
Utilities for Generation This page lists all the utility functions used by [~generation.GenerationMixin.generate], [~generation.GenerationMixin.greedy_search], [~generation.GenerationMixin.contrastive_search], [~generation.GenerationMixin.sample], [~generation.GenerationMixin.beam_search], [~generation.GenerationMixin...
Contribute to 🤗 Transformers Everyone is welcome to contribute, and we value everybody's contribution. Code contributions are not the only way to help the community. Answering questions, helping others, and improving the documentation are also immensely valuable. It also helps us if you spread the word! Reference the...
Before you begin, make sure you have all the necessary libraries installed: pip install transformers datasets evaluate We encourage you to login to your Hugging Face account so you can upload and share your model with the community. When prompted, enter your token to login: from huggingface_hub import notebook_logi...
Before you begin, make sure you have all the necessary libraries installed: pip install -q datasets transformers evaluate timm albumentations You'll use 🤗 Datasets to load a dataset from the Hugging Face Hub, 🤗 Transformers to train your model, and albumentations to augment the data. timm is currently required to ...
In this guide you'll learn how to: create a depth estimation pipeline run depth estimation inference by hand Before you begin, make sure you have all the necessary libraries installed: pip install -q transformers Depth estimation pipeline The simplest way to try out inference with a model supporting depth estimati...
Troubleshoot Sometimes errors occur, but we are here to help! This guide covers some of the most common issues we've seen and how you can resolve them. However, this guide isn't meant to be a comprehensive collection of every 🤗 Transformers issue. For more help with troubleshooting your issue, try: Asking for help o...
null
Generation Each framework has a generate method for text generation implemented in their respective GenerationMixin class: PyTorch [~generation.GenerationMixin.generate] is implemented in [~generation.GenerationMixin]. TensorFlow [~generation.TFGenerationMixin.generate] is implemented in [~generation.TFGenerationMixi...
Efficient Inference on a Single GPU In addition to this guide, relevant information can be found as well in the guide for training on a single GPU and the guide for inference on CPUs. Better Transformer: PyTorch-native transformer fastpath PyTorch-native nn.MultiHeadAttention attention fastpath, called BetterTransform...
Before you begin, make sure you have all the necessary libraries installed: pip install -q pytorchvideo transformers evaluate You will use PyTorchVideo (dubbed pytorchvideo) to process and prepare the videos. We encourage you to log in to your Hugging Face account so you can upload and share your model with the comm...
Export to TFLite TensorFlow Lite is a lightweight framework for deploying machine learning models on resource-constrained devices, such as mobile phones, embedded systems, and Internet of Things (IoT) devices. TFLite is designed to optimize and run models efficiently on these devices with limited computational power...
sections: local: index title: 🤗 Transformers local: quicktour title: Quick tour local: installation title: Installation title: Get started sections: local: pipeline_tutorial title: Run inference with pipelines local: autoclass_tutorial title: Write portable code with AutoClass local: preprocessi...
Optimization The .optimization module provides: an optimizer with weight decay fixed that can be used to fine-tuned models, and several schedules in the form of schedule objects that inherit from _LRSchedule: a gradient accumulation class to accumulate the gradients of multiple batches AdamW (PyTorch) [[autodoc]] Ad...
Before you begin, make sure you have all the necessary libraries installed: pip install transformers datasets evaluate We encourage you to log in to your Hugging Face account to upload and share your model with the community. When prompted, enter your token to log in: from huggingface_hub import notebook_login note...
Keras callbacks When training a Transformers model with Keras, there are some library-specific callbacks available to automate common tasks: KerasMetricCallback [[autodoc]] KerasMetricCallback PushToHubCallback [[autodoc]] PushToHubCallback
XLA Integration for TensorFlow Models [[open-in-colab]] Accelerated Linear Algebra, dubbed XLA, is a compiler for accelerating the runtime of TensorFlow Models. From the official documentation: XLA (Accelerated Linear Algebra) is a domain-specific compiler for linear algebra that can accelerate TensorFlow models with ...
Data Collator Data collators are objects that will form a batch by using a list of dataset elements as input. These elements are of the same type as the elements of train_dataset or eval_dataset. To be able to build batches, data collators may apply some processing (like padding). Some of them (like [DataCollatorForLa...
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...
Glossary This glossary defines general machine learning and 🤗 Transformers terms to help you better understand the documentation. A attention mask The attention mask is an optional argument used when batching sequences together. This argument indicates to the model which tokens should be attended to, and which shoul...
Utilities for Trainer This page lists all the utility functions used by [Trainer]. Most of those are only useful if you are studying the code of the Trainer in the library. Utilities [[autodoc]] EvalPrediction [[autodoc]] IntervalStrategy [[autodoc]] enable_full_determinism [[autodoc]] set_seed [[autodoc]] torch_distr...
Efficient Training on Multiple GPUs When training on a single GPU is too slow or the model weights don't fit in a single GPUs memory we use a multi-GPU setup. Switching from a single GPU to multiple requires some form of parallelism as the work needs to be distributed. There are several techniques to achieve parallism...
Processors Processors can mean two different things in the Transformers library: - the objects that pre-process inputs for multi-modal models such as Wav2Vec2 (speech and text) or CLIP (text and vision) - deprecated objects that were used in older versions of the library to preprocess data for GLUE or SQUAD. Multi-m...
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...
Fine-tune a pretrained model [[open-in-colab]] There are significant benefits to using a pretrained model. It reduces computation costs, your carbon footprint, and allows you to use state-of-the-art models without having to train one from scratch. 🤗 Transformers provides access to thousands of pretrained models for a...
Pipelines for inference The [pipeline] makes it simple to use any model from the Hub for inference on any language, computer vision, speech, and multimodal tasks. Even if you don't have experience with a specific modality or aren't familiar with the underlying code behind the models, you can still use them for inferen...
Zero-shot image classification [[open-in-colab]] Zero-shot image classification is a task that involves classifying images into different categories using a model that was not explicitly trained on data containing labeled examples from those specific categories. Traditionally, image classification requires training a ...
Utilities for FeatureExtractors This page lists all the utility functions that can be used by the audio [FeatureExtractor] in order to compute special features from a raw audio using common algorithms such as Short Time Fourier Transform or log mel spectrogram. Most of those are only useful if you are studying the cod...
Transformers Agent Transformers Agent is an experimental API which is subject to change at any time. Results returned by the agents can vary as the APIs or underlying models are prone to change. Transformers version v4.29.0, building on the concept of tools and agents. You can play with in this colab. In short, it p...
Use tokenizers from 🤗 Tokenizers The [PreTrainedTokenizerFast] depends on the 🤗 Tokenizers library. The tokenizers obtained from the 🤗 Tokenizers library can be loaded very simply into 🤗 Transformers. Before getting in the specifics, let's first start by creating a dummy tokenizer in a few lines: thon from tokeni...