[ { "chunk_id": 0, "text": "# Transformers\n\nTransformers acts as the model-definition framework for state-of-the-art machine learning models in text, computer\nvision, audio, video, and multimodal models, for both inference and training.\n\nIt centralizes the model definition so that this definition is agreed upon across the ecosystem. `transformers` is the\npivot across frameworks: if a model definition is supported, it will be compatible with the majority of training\nframeworks (Axolotl, Unsloth, DeepSpeed, FSDP, PyTorch-Lightning, ...), inference engines (vLLM, SGLang, TGI, ...),\nand adjacent modeling libraries (llama.cpp, mlx, ...) which leverage the model definition from `transformers`.\n\nWe pledge to help support new state-of-the-art models and democratize their usage by having their model definition be\nsimple, customizable, and efficient.\n\nThere are over 1M+ Transformers [model checkpoints](https://huggingface.co/models?library=transformers&sort=trending) on the [Hugging Face Hub](https://hf-cn0.pages.devm/models) you can use.", "source_file": "transformers/index.md", "section_heading": "Transformers", "char_start": 0, "char_end": 1014, "token_estimate": 253, "prev_chunk_id": null, "next_chunk_id": 1, "url": "https://huggingface.co/docs/transformers/index", "doc_title": "Transformers" }, { "chunk_id": 1, "text": "Explore the [Hub](https://hf-cn0.pages.devm/) today to find a model and use Transformers to help you get started right away.\n\nExplore the [Models Timeline](./models_timeline) to discover the latest text, vision, audio and multimodal model architectures in Transformers.", "source_file": "transformers/index.md", "section_heading": "Transformers", "char_start": 1022, "char_end": 1289, "token_estimate": 66, "prev_chunk_id": 0, "next_chunk_id": 2, "url": "https://huggingface.co/docs/transformers/index", "doc_title": "Transformers" }, { "chunk_id": 2, "text": "## Features\n\nTransformers provides everything you need for inference or training with state-of-the-art pretrained models. Some of the main features include:\n\n- [Pipeline](./pipeline_tutorial): Simple and optimized inference class for many machine learning tasks like text generation, image segmentation, automatic speech recognition, document question answering, and more.\n- [Trainer](./trainer): A comprehensive trainer that supports features such as mixed precision, torch.compile, and FlashAttention for training and distributed training for PyTorch models.\n- [generate](./llm_tutorial): Fast text generation with large language models (LLMs) and vision language models (VLMs), including support for streaming and multiple decoding strategies.", "source_file": "transformers/index.md", "section_heading": "Features", "char_start": 1291, "char_end": 2037, "token_estimate": 186, "prev_chunk_id": 1, "next_chunk_id": 3, "url": "https://huggingface.co/docs/transformers/index", "doc_title": "Transformers" }, { "chunk_id": 3, "text": "## Design\n\n> [!TIP]\n> Read our [Philosophy](./philosophy) to learn more about Transformers' design principles.\n\nTransformers is designed for developers and machine learning engineers and researchers. Its main design principles are:\n\n1. Fast and easy to use: Every model is implemented from only three main classes (configuration, model, and preprocessor) and can be quickly used for inference or training with [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) or [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer).\n2. Pretrained models: Reduce your carbon footprint, compute cost and time by using a pretrained model instead of training an entirely new one. Each pretrained model is reproduced as closely as possible to the original model and offers state-of-the-art performance.", "source_file": "transformers/index.md", "section_heading": "Design", "char_start": 2039, "char_end": 2885, "token_estimate": 211, "prev_chunk_id": 2, "next_chunk_id": 4, "url": "https://huggingface.co/docs/transformers/index", "doc_title": "Transformers" }, { "chunk_id": 4, "text": "## Learn\n\nIf you're new to Transformers or want to learn more about transformer models, we recommend starting with the [LLM course](https://huggingface.co/learn/llm-course/chapter1/1?fw=pt). This comprehensive course covers everything from the fundamentals of how transformer models work to practical applications across various tasks. You'll learn the complete workflow, from curating high-quality datasets to fine-tuning large language models and implementing reasoning capabilities. The course contains both theoretical and hands-on exercises to build a solid foundational knowledge of transformer models as you learn.", "source_file": "transformers/index.md", "section_heading": "Learn", "char_start": 2901, "char_end": 3522, "token_estimate": 155, "prev_chunk_id": 3, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/index", "doc_title": "Transformers" }, { "chunk_id": 5, "text": "# Installation\n\nTransformers works with [PyTorch](https://pytorch.org/get-started/locally/). It has been tested on Python 3.10+ and PyTorch 2.4+.", "source_file": "transformers/installation.md", "section_heading": "Installation", "char_start": 0, "char_end": 145, "token_estimate": 36, "prev_chunk_id": null, "next_chunk_id": 6, "url": "https://huggingface.co/docs/transformers/installation", "doc_title": "Installation" }, { "chunk_id": 6, "text": "## Virtual environment\n\n[uv](https://docs.astral.sh/uv/) is an extremely fast Rust-based Python package and project manager and requires a [virtual environment](https://docs.astral.sh/uv/pip/environments/) by default to manage different projects and avoids compatibility issues between dependencies.\n\nIt can be used as a drop-in replacement for [pip](https://pip.pypa.io/en/stable/), but if you prefer to use pip, remove `uv` from the commands below.\n\n> [!TIP]\n> Refer to the uv [installation](https://docs.astral.sh/uv/guides/install-python/) docs to install uv.\n\nCreate a virtual environment to install Transformers in.\n\n```bash\nuv venv .env\nsource .env/bin/activate\n```", "source_file": "transformers/installation.md", "section_heading": "Virtual environment", "char_start": 147, "char_end": 819, "token_estimate": 168, "prev_chunk_id": 5, "next_chunk_id": 7, "url": "https://huggingface.co/docs/transformers/installation", "doc_title": "Installation" }, { "chunk_id": 7, "text": "## Python\n\nInstall Transformers with the following command.\n\n[uv](https://docs.astral.sh/uv/) is a fast Rust-based Python package and project manager.\n\n```bash\nuv pip install transformers\n```\n\nFor GPU acceleration, install the appropriate CUDA drivers for [PyTorch](https://pytorch.org/get-started/locally).\n\nRun the command below to check if your system detects an NVIDIA GPU.\n\n```bash\nnvidia-smi\n```\n\nTo install a CPU-only version of Transformers, run the following command.\n\n```bash\nuv pip install torch --index-url https://download.pytorch.org/whl/cpu\nuv pip install transformers\n```\n\nTest whether the install was successful with the following command. It should return a label and score for the provided text.\n\n```bash\npython -c \"from transformers import pipeline; print(pipeline('sentiment-analysis')('hugging face is the best'))\"\n[{'label': 'POSITIVE', 'score': 0.9998704791069031}]\n```", "source_file": "transformers/installation.md", "section_heading": "Python", "char_start": 821, "char_end": 1714, "token_estimate": 223, "prev_chunk_id": 6, "next_chunk_id": 8, "url": "https://huggingface.co/docs/transformers/installation", "doc_title": "Installation" }, { "chunk_id": 8, "text": "### Source install\n\nInstalling from source installs the *latest* version rather than the *stable* version of the library. It ensures you have the most up-to-date changes in Transformers and it's useful for experimenting with the latest features or fixing a bug that hasn't been officially released in the stable version yet.\n\nThe downside is that the latest version may not always be stable. If you encounter any problems, please open a [GitHub Issue](https://github.com/huggingface/transformers/issues) so we can fix it as soon as possible.\n\nInstall from source with the following command.\n\n```bash\nuv pip install git+https://github.com/huggingface/transformers\n```\n\nCheck if the install was successful with the command below. It should return a label and score for the provided text.\n\n```bash\npython -c \"from transformers import pipeline; print(pipeline('sentiment-analysis')('hugging face is the best'))\"\n[{'label': 'POSITIVE', 'score': 0.9998704791069031}]\n```", "source_file": "transformers/installation.md", "section_heading": "Source install", "char_start": 1716, "char_end": 2680, "token_estimate": 241, "prev_chunk_id": 7, "next_chunk_id": 9, "url": "https://huggingface.co/docs/transformers/installation", "doc_title": "Installation" }, { "chunk_id": 9, "text": "### Editable install\n\nAn [editable install](https://pip.pypa.io/en/stable/topics/local-project-installs/#editable-installs) is useful if you're developing locally with Transformers. It links your local copy of Transformers to the Transformers [repository](https://github.com/huggingface/transformers) instead of copying the files. The files are added to Python's import path.\n\n```bash\ngit clone https://github.com/huggingface/transformers.git\ncd transformers\nuv pip install -e .\n```\n\n> [!WARNING]\n> You must keep the local Transformers folder to keep using it.\n\nUpdate your local version of Transformers with the latest changes in the main repository with the following command.\n\n```bash\ncd ~/transformers/\ngit pull\n```", "source_file": "transformers/installation.md", "section_heading": "Editable install", "char_start": 2682, "char_end": 3401, "token_estimate": 179, "prev_chunk_id": 8, "next_chunk_id": 10, "url": "https://huggingface.co/docs/transformers/installation", "doc_title": "Installation" }, { "chunk_id": 10, "text": "## conda\n\n[conda](https://docs.conda.io/projects/conda/en/stable/#) is a language-agnostic package manager. Install Transformers from the [conda-forge](https://anaconda.org/conda-forge/transformers) channel in your newly created virtual environment.\n\n```bash\nconda install conda-forge::transformers\n```", "source_file": "transformers/installation.md", "section_heading": "conda", "char_start": 3403, "char_end": 3705, "token_estimate": 75, "prev_chunk_id": 9, "next_chunk_id": 11, "url": "https://huggingface.co/docs/transformers/installation", "doc_title": "Installation" }, { "chunk_id": 11, "text": "## Set up\n\nAfter installation, you can configure the Transformers cache location or set up the library for offline usage.", "source_file": "transformers/installation.md", "section_heading": "Set up", "char_start": 3707, "char_end": 3828, "token_estimate": 30, "prev_chunk_id": 10, "next_chunk_id": 12, "url": "https://huggingface.co/docs/transformers/installation", "doc_title": "Installation" }, { "chunk_id": 12, "text": "### Cache directory\n\nWhen you load a pretrained model with [from_pretrained()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel.from_pretrained), the model is downloaded from the Hub and locally cached.\n\nEvery time you load a model, it checks whether the cached model is up-to-date. If it's the same, then the local model is loaded. If it's not the same, the newer model is downloaded and cached.\n\nThe default directory given by the shell environment variable `HF_HUB_CACHE` is `~/.cache/huggingface/hub`. On Windows, the default directory is `C:\\Users\\username\\.cache\\huggingface\\hub`.\n\nCache a model in a different directory by changing the path in the following shell environment variables (listed by priority).", "source_file": "transformers/installation.md", "section_heading": "Cache directory", "char_start": 3830, "char_end": 4572, "token_estimate": 185, "prev_chunk_id": 11, "next_chunk_id": 13, "url": "https://huggingface.co/docs/transformers/installation", "doc_title": "Installation" }, { "chunk_id": 13, "text": "1. [HF_HUB_CACHE](https://hf.co/docs/huggingface_hub/package_reference/environment_variables#hfhubcache) (default)\n2. [HF_HOME](https://hf.co/docs/huggingface_hub/package_reference/environment_variables#hfhome)\n3. [XDG_CACHE_HOME](https://hf.co/docs/huggingface_hub/package_reference/environment_variables#xdgcachehome) + `/huggingface` (only if `HF_HOME` is not set)", "source_file": "transformers/installation.md", "section_heading": "Cache directory", "char_start": 4574, "char_end": 4941, "token_estimate": 91, "prev_chunk_id": 12, "next_chunk_id": 14, "url": "https://huggingface.co/docs/transformers/installation", "doc_title": "Installation" }, { "chunk_id": 14, "text": "### Offline mode\n\nTo use Transformers in an offline or firewalled environment requires the downloaded and cached files ahead of time. Download a model repository from the Hub with the `snapshot_download` method.\n\n> [!TIP]\n> Refer to the [Download files from the Hub](https://hf.co/docs/huggingface_hub/guides/download) guide for more options for downloading files from the Hub. You can download files from specific revisions, download from the CLI, and even filter which files to download from a repository.\n\n```py\nfrom huggingface_hub import snapshot_download\n\nsnapshot_download(repo_id=\"meta-llama/Llama-2-7b-hf\", repo_type=\"model\")\n```\n\nSet the environment variable `HF_HUB_OFFLINE=1` to prevent HTTP calls to the Hub when loading a model.\n\n```bash\nHF_HUB_OFFLINE=1 \\\npython examples/pytorch/language-modeling/run_clm.py --model_name_or_path meta-llama/Llama-2-7b-hf --dataset_name wikitext ...\n```", "source_file": "transformers/installation.md", "section_heading": "Offline mode", "char_start": 4943, "char_end": 5844, "token_estimate": 225, "prev_chunk_id": 13, "next_chunk_id": 15, "url": "https://huggingface.co/docs/transformers/installation", "doc_title": "Installation" }, { "chunk_id": 15, "text": "Another option for only loading cached files is to set `local_files_only=True` in [from_pretrained()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel.from_pretrained).\n\n```py\nfrom transformers import LlamaForCausalLM\n\nmodel = LlamaForCausalLM.from_pretrained(\"./path/to/local/directory\", local_files_only=True)\n```", "source_file": "transformers/installation.md", "section_heading": "Offline mode", "char_start": 5846, "char_end": 6189, "token_estimate": 85, "prev_chunk_id": 14, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/installation", "doc_title": "Installation" }, { "chunk_id": 16, "text": "# Quickstart\n\nTransformers is designed to be fast and easy to use so that everyone can start learning or building with transformer models.\n\nThe number of user-facing abstractions is limited to only three classes for instantiating a model, and two APIs for inference or training. This quickstart introduces you to Transformers' key features and shows you how to:\n\n- load a pretrained model\n- run inference with [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline)\n- fine-tune a model with [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer)", "source_file": "transformers/quicktour.md", "section_heading": "Quickstart", "char_start": 0, "char_end": 602, "token_estimate": 150, "prev_chunk_id": null, "next_chunk_id": 17, "url": "https://huggingface.co/docs/transformers/quicktour", "doc_title": "Quickstart" }, { "chunk_id": 17, "text": "## Set up\n\nTo start, we recommend creating a Hugging Face [account](https://hf.co/join). An account lets you host and access version controlled models, datasets, and [Spaces](https://hf.co/spaces) on the Hugging Face [Hub](https://hf.co/docs/hub/index), a collaborative platform for discovery and building.\n\nCreate a [User Access Token](https://hf.co/docs/hub/security-tokens#user-access-tokens) and log in to your account.\n\nPaste your User Access Token into `notebook_login` when prompted to log in.\n\n```py\nfrom huggingface_hub import notebook_login\n\nnotebook_login()\n```\n\nMake sure the [huggingface_hub[cli]](https://huggingface.co/docs/huggingface_hub/guides/cli#getting-started) package is installed and run the command below. Paste your User Access Token when prompted to log in.\n\n```bash\nhf auth login\n```\n\nInstall PyTorch.\n\n```bash\n!pip install torch\n```", "source_file": "transformers/quicktour.md", "section_heading": "Set up", "char_start": 604, "char_end": 1465, "token_estimate": 215, "prev_chunk_id": 16, "next_chunk_id": 18, "url": "https://huggingface.co/docs/transformers/quicktour", "doc_title": "Quickstart" }, { "chunk_id": 18, "text": "Then install an up-to-date version of Transformers and some additional libraries from the Hugging Face ecosystem for accessing datasets and vision models, evaluating training, and optimizing training for large models.\n\n```bash\n!pip install -U transformers datasets evaluate accelerate timm\n```", "source_file": "transformers/quicktour.md", "section_heading": "Set up", "char_start": 1467, "char_end": 1760, "token_estimate": 73, "prev_chunk_id": 17, "next_chunk_id": 19, "url": "https://huggingface.co/docs/transformers/quicktour", "doc_title": "Quickstart" }, { "chunk_id": 19, "text": "## Pretrained models\n\nEach pretrained model inherits from three base classes.", "source_file": "transformers/quicktour.md", "section_heading": "Pretrained models", "char_start": 1762, "char_end": 1839, "token_estimate": 19, "prev_chunk_id": 18, "next_chunk_id": 20, "url": "https://huggingface.co/docs/transformers/quicktour", "doc_title": "Quickstart" }, { "chunk_id": 20, "text": "| **Class** | **Description** |\n|---|---|\n| [PreTrainedConfig](/docs/transformers/v5.6.2/en/main_classes/configuration#transformers.PreTrainedConfig) | A file that specifies a models attributes such as the number of attention heads or vocabulary size. |\n| [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel) | A model (or architecture) defined by the model attributes from the configuration file. A pretrained model only returns the raw hidden states. For a specific task, use the appropriate model head to convert the raw hidden states into a meaningful result (for example, [LlamaModel](/docs/transformers/v5.6.2/en/model_doc/llama2#transformers.LlamaModel) versus [LlamaForCausalLM](/docs/transformers/v5.6.2/en/model_doc/llama2#transformers.LlamaForCausalLM)). |\n| Preprocessor | A class for converting raw inputs (text, images, audio, multimodal) into numerical inputs to the model. For example, [PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend) converts text into tensors and [ImageProcessingMixin](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.ImageProcessingMixin) converts pixels into tensors. |", "source_file": "transformers/quicktour.md", "section_heading": "Pretrained models", "char_start": 1841, "char_end": 3066, "token_estimate": 306, "prev_chunk_id": 19, "next_chunk_id": 21, "url": "https://huggingface.co/docs/transformers/quicktour", "doc_title": "Quickstart" }, { "chunk_id": 21, "text": "We recommend using the [AutoClass](./model_doc/auto) API to load models and preprocessors because it automatically infers the appropriate architecture for each task and machine learning framework based on the name or path to the pretrained weights and configuration file.\n\nUse [from_pretrained()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) to load the weights and configuration file from the Hub into the model and preprocessor class.\n\nWhen you load a model, configure the following parameters to ensure the model is optimally loaded.\n\n- `device_map=\"auto\"` automatically allocates the model weights to your fastest device first.\n- `dtype=\"auto\"` directly initializes the model weights in the data type they're stored in, which can help avoid loading the weights twice (PyTorch loads weights in `torch.float32` by default).", "source_file": "transformers/quicktour.md", "section_heading": "Pretrained models", "char_start": 3068, "char_end": 3942, "token_estimate": 218, "prev_chunk_id": 20, "next_chunk_id": 22, "url": "https://huggingface.co/docs/transformers/quicktour", "doc_title": "Quickstart" }, { "chunk_id": 22, "text": "```py\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\nmodel = AutoModelForCausalLM.from_pretrained(\"meta-llama/Llama-2-7b-hf\", dtype=\"auto\", device_map=\"auto\")\ntokenizer = AutoTokenizer.from_pretrained(\"meta-llama/Llama-2-7b-hf\")\n```\n\nTokenize the text and return PyTorch tensors with the tokenizer. Move the model to an accelerator if it's available to accelerate inference.\n\n```py\nmodel_inputs = tokenizer([\"The secret to baking a good cake is \"], return_tensors=\"pt\").to(model.device)\n```\n\nThe model is now ready for inference or training.\n\nFor inference, pass the tokenized inputs to [generate()](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationMixin.generate) to generate text. Decode the token ids back into text with [batch_decode()](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.batch_decode).", "source_file": "transformers/quicktour.md", "section_heading": "Pretrained models", "char_start": 3944, "char_end": 4840, "token_estimate": 224, "prev_chunk_id": 21, "next_chunk_id": 23, "url": "https://huggingface.co/docs/transformers/quicktour", "doc_title": "Quickstart" }, { "chunk_id": 23, "text": "```py\ngenerated_ids = model.generate(**model_inputs, max_length=30)\ntokenizer.batch_decode(generated_ids)[0]\n' The secret to baking a good cake is 100% in the preparation. There are so many recipes out there,'\n```\n\n> [!TIP]\n> Skip ahead to the [Trainer](#trainer-api) section to learn how to fine-tune a model.", "source_file": "transformers/quicktour.md", "section_heading": "Pretrained models", "char_start": 4842, "char_end": 5152, "token_estimate": 77, "prev_chunk_id": 22, "next_chunk_id": 24, "url": "https://huggingface.co/docs/transformers/quicktour", "doc_title": "Quickstart" }, { "chunk_id": 24, "text": "## Pipeline\n\nThe [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) class is the most convenient way to inference with a pretrained model. It supports many tasks such as text generation, image segmentation, automatic speech recognition, document question answering, and more.\n\n> [!TIP]\n> Refer to the [Pipeline](./main_classes/pipelines) API reference for a complete list of available tasks.\n\nCreate a [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) object and select a task. By default, [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) downloads and caches a default pretrained model for a given task. Pass the model name to the `model` parameter to choose a specific model.\n\nUse `Accelerator` to automatically detect an available accelerator for inference.", "source_file": "transformers/quicktour.md", "section_heading": "Pipeline", "char_start": 5154, "char_end": 6022, "token_estimate": 217, "prev_chunk_id": 23, "next_chunk_id": 25, "url": "https://huggingface.co/docs/transformers/quicktour", "doc_title": "Quickstart" }, { "chunk_id": 25, "text": "```py\nfrom transformers import pipeline\nfrom accelerate import Accelerator\n\ndevice = Accelerator().device\n\npipeline = pipeline(\"text-generation\", model=\"meta-llama/Llama-2-7b-hf\", device=device)\n```\n\nPrompt [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) with some initial text to generate more text.\n\n```py\npipeline(\"The secret to baking a good cake is \", max_length=50)\n[{'generated_text': 'The secret to baking a good cake is 100% in the batter. The secret to a great cake is the icing.\\nThis is why we\u2019ve created the best buttercream frosting reci'}]\n```\n\nUse `Accelerator` to automatically detect an available accelerator for inference.\n\n```py\nfrom transformers import pipeline\nfrom accelerate import Accelerator\n\ndevice = Accelerator().device\n\npipeline = pipeline(\"image-segmentation\", model=\"facebook/detr-resnet-50-panoptic\", device=device)\n```", "source_file": "transformers/quicktour.md", "section_heading": "Pipeline", "char_start": 6024, "char_end": 6914, "token_estimate": 222, "prev_chunk_id": 24, "next_chunk_id": 26, "url": "https://huggingface.co/docs/transformers/quicktour", "doc_title": "Quickstart" }, { "chunk_id": 26, "text": "Pass an image - a URL or local path to the image - to [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline).\n\n```py\nsegments = pipeline(\"https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png\")\nsegments[0][\"label\"]\n'bird'\nsegments[1][\"label\"]\n'bird'\n```\n\nUse `Accelerator` to automatically detect an available accelerator for inference.\n\n```py\nfrom transformers import pipeline\nfrom accelerate import Accelerator\n\ndevice = Accelerator().device\n\npipeline = pipeline(\"automatic-speech-recognition\", model=\"openai/whisper-large-v3\", device=device)\n```\n\nPass an audio file to [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline).\n\n```py\npipeline(\"https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac\")\n{'text': ' He hoped there would be stew for dinner, turnips and carrots and bruised potatoes and fat mutton pieces to be ladled out in thick, peppered flour-fatten sauce.'}\n```", "source_file": "transformers/quicktour.md", "section_heading": "Pipeline", "char_start": 0, "char_end": 972, "token_estimate": 243, "prev_chunk_id": 25, "next_chunk_id": 27, "url": "https://huggingface.co/docs/transformers/quicktour", "doc_title": "Quickstart" }, { "chunk_id": 27, "text": "## Trainer\n\n[Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) is a complete training and evaluation loop for PyTorch models. It abstracts away a lot of the boilerplate usually involved in manually writing a training loop, so you can start training faster and focus on training design choices. You only need a model, dataset, a preprocessor, and a data collator to build batches of data from the dataset.\n\nUse the [TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments) class to customize the training process. It provides many options for training, evaluation, and more. Experiment with training hyperparameters and features like batch size, learning rate, mixed precision, torch.compile, and more to meet your training needs. You could also use the default training parameters to quickly produce a baseline.\n\nLoad a model, tokenizer, and dataset for training.", "source_file": "transformers/quicktour.md", "section_heading": "Trainer", "char_start": 7895, "char_end": 8833, "token_estimate": 234, "prev_chunk_id": 26, "next_chunk_id": 28, "url": "https://huggingface.co/docs/transformers/quicktour", "doc_title": "Quickstart" }, { "chunk_id": 28, "text": "```py\nfrom transformers import AutoModelForSequenceClassification, AutoTokenizer\nfrom datasets import load_dataset\n\nmodel = AutoModelForSequenceClassification.from_pretrained(\"distilbert/distilbert-base-uncased\")\ntokenizer = AutoTokenizer.from_pretrained(\"distilbert/distilbert-base-uncased\")\ndataset = load_dataset(\"rotten_tomatoes\")\n```\n\nCreate a function to tokenize the text and convert it into PyTorch tensors. Apply this function to the whole dataset with the [map](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) method.\n\n```py\ndef tokenize_dataset(dataset):\n return tokenizer(dataset[\"text\"])\ndataset = dataset.map(tokenize_dataset, batched=True)\n```\n\nLoad a data collator to create batches of data and pass the tokenizer to it.\n\n```py\nfrom transformers import DataCollatorWithPadding\n\ndata_collator = DataCollatorWithPadding(tokenizer=tokenizer)\n```", "source_file": "transformers/quicktour.md", "section_heading": "Trainer", "char_start": 8835, "char_end": 9748, "token_estimate": 228, "prev_chunk_id": 27, "next_chunk_id": 29, "url": "https://huggingface.co/docs/transformers/quicktour", "doc_title": "Quickstart" }, { "chunk_id": 29, "text": "Next, set up [TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments) with the training features and hyperparameters.\n\n```py\nfrom transformers import TrainingArguments\n\ntraining_args = TrainingArguments(\n output_dir=\"distilbert-rotten-tomatoes\",\n learning_rate=2e-5,\n per_device_train_batch_size=8,\n per_device_eval_batch_size=8,\n num_train_epochs=2,\n push_to_hub=True,\n)\n```\n\nFinally, pass all these separate components to [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) and call [train()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.train) to start.\n\n```py\nfrom transformers import Trainer\n\ntrainer = Trainer(\n model=model,\n args=training_args,\n train_dataset=dataset[\"train\"],\n eval_dataset=dataset[\"test\"],\n processing_class=tokenizer,\n data_collator=data_collator,\n)\n\ntrainer.train()\n```", "source_file": "transformers/quicktour.md", "section_heading": "Trainer", "char_start": 9750, "char_end": 10684, "token_estimate": 233, "prev_chunk_id": 28, "next_chunk_id": 30, "url": "https://huggingface.co/docs/transformers/quicktour", "doc_title": "Quickstart" }, { "chunk_id": 30, "text": "Share your model and tokenizer to the Hub with [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.push_to_hub).\n\n```py\ntrainer.push_to_hub()\n```\n\nCongratulations, you just trained your first model with Transformers!", "source_file": "transformers/quicktour.md", "section_heading": "Trainer", "char_start": 10686, "char_end": 10937, "token_estimate": 62, "prev_chunk_id": 29, "next_chunk_id": 31, "url": "https://huggingface.co/docs/transformers/quicktour", "doc_title": "Quickstart" }, { "chunk_id": 31, "text": "## Next steps\n\nNow that you have a better understanding of Transformers and what it offers, it's time to keep exploring and learning what interests you the most.", "source_file": "transformers/quicktour.md", "section_heading": "Next steps", "char_start": 10939, "char_end": 11100, "token_estimate": 40, "prev_chunk_id": 30, "next_chunk_id": 32, "url": "https://huggingface.co/docs/transformers/quicktour", "doc_title": "Quickstart" }, { "chunk_id": 32, "text": "- **Base classes**: Learn more about the configuration, model and processor classes. This will help you understand how to create and customize models, preprocess different types of inputs (audio, images, multimodal), and how to share your model.\n- **Inference**: Explore the [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) further, inference and chatting with LLMs, agents, and how to optimize inference with your machine learning framework and hardware.\n- **Training**: Study the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) in more detail, as well as distributed training and optimizing training on specific hardware.\n- **Quantization**: Reduce memory and storage requirements with quantization and speed up inference by representing weights with fewer bits.\n- **Resources**: Looking for end-to-end recipes for how to train and inference with a model for a specific task? Check out the task recipes!", "source_file": "transformers/quicktour.md", "section_heading": "Next steps", "char_start": 11102, "char_end": 12078, "token_estimate": 244, "prev_chunk_id": 31, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/quicktour", "doc_title": "Quickstart" }, { "chunk_id": 33, "text": "# Philosophy\n\nTransformers is a PyTorch-first library. It provides models that are faithful to their papers, easy to use, and easy to hack.\n\nA longer, in-depth article with examples, visualizations and timelines is available [here](https://huggingface.co/spaces/transformers-community/Transformers-tenets) as our canonical reference.\n\n> [!NOTE]\n> Our philosophy evolves through practice. What follows are our current, stable principles.", "source_file": "transformers/philosophy.md", "section_heading": "Philosophy", "char_start": 0, "char_end": 436, "token_estimate": 109, "prev_chunk_id": null, "next_chunk_id": 34, "url": "https://huggingface.co/docs/transformers/philosophy", "doc_title": "Philosophy" }, { "chunk_id": 34, "text": "## Who this library is for\n\n- Researchers and educators exploring or extending model architectures.\n- Practitioners fine-tuning, evaluating, or serving models.\n- Engineers who want a pretrained model that \u201cjust works\u201d with a predictable API.", "source_file": "transformers/philosophy.md", "section_heading": "Who this library is for", "char_start": 438, "char_end": 679, "token_estimate": 60, "prev_chunk_id": 33, "next_chunk_id": 35, "url": "https://huggingface.co/docs/transformers/philosophy", "doc_title": "Philosophy" }, { "chunk_id": 35, "text": "## What you can expect\n\n- Three core classes are required for each model: [configuration](main_classes/configuration),\n [models](main_classes/model), and a preprocessing class. [Tokenizers](main_classes/tokenizer) handle NLP, [image processors](main_classes/image_processor) handle images, [video processors](main_classes/video_processor) handle videos, [feature extractors](main_classes/feature_extractor) handle audio, and [processors](main_classes/processors) handle multimodal inputs.", "source_file": "transformers/philosophy.md", "section_heading": "What you can expect", "char_start": 681, "char_end": 1172, "token_estimate": 122, "prev_chunk_id": 34, "next_chunk_id": 36, "url": "https://huggingface.co/docs/transformers/philosophy", "doc_title": "Philosophy" }, { "chunk_id": 36, "text": "- All of these classes can be initialized in a simple and unified way from pretrained instances by using a common\n `from_pretrained()` method which downloads (if needed), caches and\n loads the related class instance and associated data (configurations' hyperparameters, tokenizers' vocabulary, processors' parameters\n and models' weights) from a pretrained checkpoint provided on [Hugging Face Hub](https://huggingface.co/models) or your own saved checkpoint.\n- On top of those three base classes, the library provides two APIs: [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline) for quickly\n using a model for inference on a given task and [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) to quickly train or fine-tune a PyTorch model.", "source_file": "transformers/philosophy.md", "section_heading": "What you can expect", "char_start": 1174, "char_end": 1992, "token_estimate": 204, "prev_chunk_id": 35, "next_chunk_id": 37, "url": "https://huggingface.co/docs/transformers/philosophy", "doc_title": "Philosophy" }, { "chunk_id": 37, "text": "## Core tenets\n\nThe following tenets solidified over time, and they're detailed in our new philosophy [blog post](https://huggingface.co/spaces/transformers-community/Transformers-tenets). They guide maintainer decisions when reviewing PRs and contributions.", "source_file": "transformers/philosophy.md", "section_heading": "Core tenets", "char_start": 1994, "char_end": 2252, "token_estimate": 64, "prev_chunk_id": 36, "next_chunk_id": 38, "url": "https://huggingface.co/docs/transformers/philosophy", "doc_title": "Philosophy" }, { "chunk_id": 38, "text": "> - **Source of Truth.** Implementations must be faithful to official results and intended behavior.\n> - **One Model, One File.** Core inference/training logic is visible top-to-bottom in the model file users read.\n> - **Code is the Product.** Optimize for reading and diff-ing. Prefer explicit names over clever indirection.\n> - **Standardize, Don\u2019t Abstract.** Keep model-specific behavior in the model. Use shared interfaces only for generic infra.\n> - **DRY\\*** (Repeat when it helps users). End-user modeling files remain self-contained. Infra is factored out.\n> - **Minimal User API.** Few codepaths, predictable kwargs, stable methods.\n> - **Backwards Compatibility.** Public surfaces should not break. Old Hub artifacts have to keep working..\n> - **Consistent Public Surface.** Naming, outputs, and optional diagnostics are aligned and tested.", "source_file": "transformers/philosophy.md", "section_heading": "Core tenets", "char_start": 2254, "char_end": 3105, "token_estimate": 212, "prev_chunk_id": 37, "next_chunk_id": 39, "url": "https://huggingface.co/docs/transformers/philosophy", "doc_title": "Philosophy" }, { "chunk_id": 39, "text": "## Main classes\n\n- [**Configuration classes**](main_classes/configuration) store the hyperparameters required to build a model. These include the number of layers and hidden size. You don't always need to instantiate these yourself. When using a pretrained model without modification, creating the model automatically instantiates the configuration.\n- **Model classes** are PyTorch models ([torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)), wrapped by at least a [PreTrainedModel](https://huggingface.co/docs/transformers/v4.57.0/en/main_classes/model#transformers.PreTrainedModel).", "source_file": "transformers/philosophy.md", "section_heading": "Main classes", "char_start": 3107, "char_end": 3715, "token_estimate": 152, "prev_chunk_id": 38, "next_chunk_id": 40, "url": "https://huggingface.co/docs/transformers/philosophy", "doc_title": "Philosophy" }, { "chunk_id": 40, "text": "- **Modular transformers.** Contributors write a small `modular_*.py` shard that declares reuse from existing components. The library auto-expands this into the visible `modeling_*.py` file that users read/debug. Maintainers review the shard; users hack the expanded file. This preserves \u201cOne Model, One File\u201d without boilerplate drift. See [the contributing documentation](https://huggingface.co/docs/transformers/en/modular_transformers) for more information.", "source_file": "transformers/philosophy.md", "section_heading": "Main classes", "char_start": 3717, "char_end": 4178, "token_estimate": 115, "prev_chunk_id": 39, "next_chunk_id": 41, "url": "https://huggingface.co/docs/transformers/philosophy", "doc_title": "Philosophy" }, { "chunk_id": 41, "text": "- **Preprocessing classes** convert the raw data into a format accepted by the model. A [tokenizer](main_classes/tokenizer) stores the vocabulary for each model and provides methods for encoding and decoding strings in a list of token embedding indices. [Image processors](main_classes/image_processor) preprocess vision inputs, [video processors](https://huggingface.co/docs/transformers/en/main_classes/video_processor) preprocess videos inputs, [feature extractors](main_classes/feature_extractor) preprocess audio inputs, and [processors](main_classes/processors) preprocess multimodal inputs.\n\nAll these classes can be instantiated from pretrained instances, saved locally, and shared on the Hub with three methods:", "source_file": "transformers/philosophy.md", "section_heading": "Main classes", "char_start": 4180, "char_end": 4900, "token_estimate": 180, "prev_chunk_id": 40, "next_chunk_id": 42, "url": "https://huggingface.co/docs/transformers/philosophy", "doc_title": "Philosophy" }, { "chunk_id": 42, "text": "- `from_pretrained()` lets you instantiate a model, configuration, and preprocessing class from a pretrained version either\n provided by the library itself (the supported models can be found on the [Model Hub](https://huggingface.co/models)) or\n stored locally (or on a server) by the user.\n- `save_pretrained()` lets you save a model, configuration, and preprocessing class locally so that it can be reloaded using\n `from_pretrained()`.\n- `push_to_hub()` lets you share a model, configuration, and a preprocessing class to the Hub, so it is easily accessible to everyone.", "source_file": "transformers/philosophy.md", "section_heading": "Main classes", "char_start": 4902, "char_end": 5477, "token_estimate": 143, "prev_chunk_id": 41, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/philosophy", "doc_title": "Philosophy" }, { "chunk_id": 43, "text": "# Pipeline\n\nThe [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) is a simple but powerful inference API that is readily available for a variety of machine learning tasks with any model from the Hugging Face [Hub](https://hf.co/models).\n\nTailor the [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) to your task with task specific parameters such as adding timestamps to an automatic speech recognition (ASR) pipeline for transcribing meeting notes. [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) supports GPUs, Apple Silicon, and half-precision weights to accelerate inference and save memory.", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "Pipeline", "char_start": 0, "char_end": 705, "token_estimate": 176, "prev_chunk_id": null, "next_chunk_id": 44, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 44, "text": "Transformers has two pipeline classes, a generic [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) and many individual task-specific pipelines like [TextGenerationPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.TextGenerationPipeline). Load these individual pipelines by setting the task identifier in the `task` parameter in [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline). You can find the task identifier for each pipeline in their API documentation.\n\nEach task is configured to use a default pretrained model and preprocessor, but this can be overridden with the `model` parameter if you want to use a different model.\n\nFor example, to use the [TextGenerationPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.TextGenerationPipeline) with [Gemma 2](./model_doc/gemma2), set `task=\"text-generation\"` and `model=\"google/gemma-2-2b\"`.", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "Pipeline", "char_start": 707, "char_end": 1667, "token_estimate": 240, "prev_chunk_id": 43, "next_chunk_id": 45, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 45, "text": "```py\nfrom transformers import pipeline\n\npipeline = pipeline(task=\"text-generation\", model=\"google/gemma-2-2b\")\npipeline(\"the secret to baking a really good cake is \")\n[{'generated_text': 'the secret to baking a really good cake is 1. the right ingredients 2. the'}]\n```\n\nWhen you have more than one input, pass them as a list.\n\n```py\nfrom transformers import pipeline\nfrom accelerate import Accelerator\n\ndevice = Accelerator().device\n\npipeline = pipeline(task=\"text-generation\", model=\"google/gemma-2-2b\", device=device)\npipeline([\"the secret to baking a really good cake is \", \"a baguette is \"])\n[[{'generated_text': 'the secret to baking a really good cake is 1. the right ingredients 2. the'}],\n [{'generated_text': 'a baguette is 100% bread.\\n\\na baguette is 100%'}]]\n```\n\nThis guide will introduce you to the [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline), demonstrate its features, and show how to configure its various parameters.", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "Pipeline", "char_start": 1669, "char_end": 2646, "token_estimate": 244, "prev_chunk_id": 44, "next_chunk_id": 46, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 46, "text": "## Tasks\n\n[Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) is compatible with many machine learning tasks across different modalities. Pass an appropriate input to the pipeline and it will handle the rest.\n\nHere are some examples of how to use [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) for different tasks and modalities.\n\n```py\nfrom transformers import pipeline\n\npipeline = pipeline(task=\"automatic-speech-recognition\", model=\"openai/whisper-large-v3\")\npipeline(\"https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac\")\n{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'}\n```", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "Tasks", "char_start": 2648, "char_end": 3379, "token_estimate": 182, "prev_chunk_id": 45, "next_chunk_id": 47, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 47, "text": "```py\nfrom transformers import pipeline\n\npipeline = pipeline(task=\"image-classification\", model=\"google/vit-base-patch16-224\")\npipeline(images=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg\")\n[{'label': 'lynx, catamount', 'score': 0.43350091576576233},\n {'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor',\n 'score': 0.034796204417943954},\n {'label': 'snow leopard, ounce, Panthera uncia',\n 'score': 0.03240183740854263},\n {'label': 'Egyptian cat', 'score': 0.02394474856555462},\n {'label': 'tiger cat', 'score': 0.02288915030658245}]\n```\n\n```py\nfrom transformers import pipeline\n\npipeline = pipeline(task=\"visual-question-answering\", model=\"Salesforce/blip-vqa-base\")\npipeline(\n image=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg\",\n question=\"What is in the image?\",\n)\n[{'answer': 'statue of liberty'}]\n```", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "Tasks", "char_start": 3381, "char_end": 4359, "token_estimate": 244, "prev_chunk_id": 46, "next_chunk_id": 48, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 48, "text": "## Parameters\n\nAt a minimum, [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) only requires a task identifier, model, and the appropriate input. But there are many parameters available to configure the pipeline with, from task-specific parameters to optimizing performance.\n\nThis section introduces you to some of the more important parameters.", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "Parameters", "char_start": 4361, "char_end": 4742, "token_estimate": 95, "prev_chunk_id": 47, "next_chunk_id": 49, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 49, "text": "### Device\n\n[Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) is compatible with many hardware types, including GPUs, CPUs, Apple Silicon, and more. Configure the hardware type with the `device` parameter. By default, [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) runs on a CPU which is given by `device=-1`.\n\nTo run [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) on a GPU, set `device` to the associated CUDA device id. For example, `device=0` runs on the first GPU.\n\n```py\nfrom transformers import pipeline\n\npipeline = pipeline(task=\"text-generation\", model=\"google/gemma-2-2b\", device=0)\npipeline(\"the secret to baking a really good cake is \")\n```", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "Device", "char_start": 4744, "char_end": 5509, "token_estimate": 191, "prev_chunk_id": 48, "next_chunk_id": 50, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 50, "text": "You could also let [Accelerate](https://hf.co/docs/accelerate/index), a library for distributed training, automatically choose how to load and store the model weights on the appropriate device. This is especially useful if you have multiple devices. Accelerate loads and stores the model weights on the fastest device first, and then moves the weights to other devices (CPU, hard drive) as needed. Set `device_map=\"auto\"` to let Accelerate choose the device.\n\n> [!TIP]\n> Make sure have [Accelerate](https://hf.co/docs/accelerate/basic_tutorials/install) is installed.\n>\n> ```py\n> !pip install -U accelerate\n> ```\n\n```py\nfrom transformers import pipeline\n\npipeline = pipeline(task=\"text-generation\", model=\"google/gemma-2-2b\", device_map=\"auto\")\npipeline(\"the secret to baking a really good cake is \")\n```\n\nTo run [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) on Apple silicon, set `device=\"mps\"`.", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "Device", "char_start": 5511, "char_end": 6447, "token_estimate": 234, "prev_chunk_id": 49, "next_chunk_id": 51, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 51, "text": "```py\nfrom transformers import pipeline\n\npipeline = pipeline(task=\"text-generation\", model=\"google/gemma-2-2b\", device=\"mps\")\npipeline(\"the secret to baking a really good cake is \")\n```", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "Device", "char_start": 6449, "char_end": 6634, "token_estimate": 46, "prev_chunk_id": 50, "next_chunk_id": 52, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 52, "text": "### Batch inference\n\n[Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) can also process batches of inputs with the `batch_size` parameter. Batch inference may improve speed, especially on a GPU, but it isn't guaranteed. Other variables such as hardware, data, and the model itself can affect whether batch inference improves speed. For this reason, batch inference is disabled by default.\n\nIn the example below, when there are 4 inputs and `batch_size` is set to 2, [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) passes a batch of 2 inputs to the model at a time.", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "Batch inference", "char_start": 6636, "char_end": 7274, "token_estimate": 159, "prev_chunk_id": 51, "next_chunk_id": 53, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 53, "text": "```py\nfrom transformers import pipeline\nfrom accelerate import Accelerator\n\ndevice = Accelerator().device\n\npipeline = pipeline(task=\"text-generation\", model=\"google/gemma-2-2b\", device=device, batch_size=2)\npipeline([\"the secret to baking a really good cake is\", \"a baguette is\", \"paris is the\", \"hotdogs are\"])\n[[{'generated_text': 'the secret to baking a really good cake is to use a good cake mix.\\n\\ni\u2019'}],\n [{'generated_text': 'a baguette is'}],\n [{'generated_text': 'paris is the most beautiful city in the world.\\n\\ni\u2019ve been to paris 3'}],\n [{'generated_text': 'hotdogs are a staple of the american diet. they are a great source of protein and can'}]]\n```\n\nAnother good use case for batch inference is for streaming data in [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline).\n\n```py\nfrom transformers import pipeline\nfrom accelerate import Accelerator\nfrom transformers.pipelines.pt_utils import KeyDataset\nimport datasets\n\ndevice = Accelerator().device", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "Batch inference", "char_start": 7276, "char_end": 8272, "token_estimate": 249, "prev_chunk_id": 52, "next_chunk_id": 54, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 54, "text": "# KeyDataset is a utility that returns the item in the dict returned by the dataset\ndataset = datasets.load_dataset(\"imdb\", name=\"plain_text\", split=\"unsupervised\")\npipeline = pipeline(task=\"text-classification\", model=\"distilbert/distilbert-base-uncased-finetuned-sst-2-english\", device=device)\nfor out in pipeline(KeyDataset(dataset, \"text\"), batch_size=8, truncation=\"only_first\"):\n print(out)\n```\n\nKeep the following general rules of thumb in mind for determining whether batch inference can help improve performance.", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "KeyDataset is a utility that returns the item in the dict returned by the dataset", "char_start": 8274, "char_end": 8798, "token_estimate": 131, "prev_chunk_id": 53, "next_chunk_id": 55, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 55, "text": "1. The only way to know for sure is to measure performance on your model, data, and hardware.\n2. Don't batch inference if you're constrained by latency (a live inference product for example).\n3. Don't batch inference if you're using a CPU.\n4. Don't batch inference if you don't know the `sequence_length` of your data. Measure performance, iteratively add to `sequence_length`, and include out-of-memory (OOM) checks to recover from failures.\n5. Do batch inference if your `sequence_length` is regular, and keep pushing it until you reach an OOM error. The larger the GPU, the more helpful batch inference is.\n6. Do make sure you can handle OOM errors if you decide to do batch inference.", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "KeyDataset is a utility that returns the item in the dict returned by the dataset", "char_start": 8800, "char_end": 9488, "token_estimate": 172, "prev_chunk_id": 54, "next_chunk_id": 56, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 56, "text": "### Task-specific parameters\n\n[Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) accepts any parameters that are supported by each individual task pipeline. Make sure to check out each individual task pipeline to see what type of parameters are available. If you can't find a parameter that is useful for your use case, please feel free to open a GitHub [issue](https://github.com/huggingface/transformers/issues/new?assignees=&labels=feature&template=feature-request.yml) to request it!\n\nThe examples below demonstrate some of the task-specific parameters available.\n\nPass the `return_timestamps=\"word\"` parameter to [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) to return when each word was spoken.", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "Task-specific parameters", "char_start": 9490, "char_end": 10265, "token_estimate": 193, "prev_chunk_id": 55, "next_chunk_id": 57, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 57, "text": "```py\nfrom transformers import pipeline\n\npipeline = pipeline(task=\"automatic-speech-recognition\", model=\"openai/whisper-large-v3\")\npipeline(audio=\"https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac\", return_timestamp=\"word\")\n{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.',\n 'chunks': [{'text': ' I', 'timestamp': (0.0, 1.1)},\n {'text': ' have', 'timestamp': (1.1, 1.44)},\n {'text': ' a', 'timestamp': (1.44, 1.62)},\n {'text': ' dream', 'timestamp': (1.62, 1.92)},\n {'text': ' that', 'timestamp': (1.92, 3.7)},\n {'text': ' one', 'timestamp': (3.7, 3.88)},\n {'text': ' day', 'timestamp': (3.88, 4.24)},\n {'text': ' this', 'timestamp': (4.24, 5.82)},\n {'text': ' nation', 'timestamp': (5.82, 6.78)},\n {'text': ' will', 'timestamp': (6.78, 7.36)},\n {'text': ' rise', 'timestamp': (7.36, 7.88)},\n {'text': ' up', 'timestamp': (7.88, 8.46)},\n {'text': ' and', 'timestamp': (8.46, 9.2)},\n {'text': ' live', 'timestamp': (9.2, 10.34)},\n {'text': ' out', 'timestamp': (10.34, 10.58)},\n {'text': ' the', 'timestamp': (10.58, 10.8)},\n {'text': ' true', 'timestamp': (10.8, 11.04)},\n {'text': ' meaning', 'timestamp': (11.04, 11.4)},\n {'text': ' of', 'timestamp': (11.4, 11.64)},\n {'text': ' its', 'timestamp': (11.64, 11.8)},\n {'text': ' creed.', 'timestamp': (11.8, 12.3)}]}\n```", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "Task-specific parameters", "char_start": 10267, "char_end": 11637, "token_estimate": 342, "prev_chunk_id": 56, "next_chunk_id": 58, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 58, "text": "Pass `return_full_text=False` to [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) to only return the generated text instead of the full text (prompt and generated text).\n\n[__call__()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.TextGenerationPipeline.__call__) also supports additional keyword arguments from the [generate()](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationMixin.generate) method. To return more than one generated sequence, set `num_return_sequences` to a value greater than 1.", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "Task-specific parameters", "char_start": 11639, "char_end": 12225, "token_estimate": 146, "prev_chunk_id": 57, "next_chunk_id": 59, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 59, "text": "```py\nfrom transformers import pipeline\n\npipeline = pipeline(task=\"text-generation\", model=\"openai-community/gpt2\")\npipeline(\"the secret to baking a good cake is\", num_return_sequences=4, return_full_text=False)\n[{'generated_text': ' how easy it is for me to do it with my hands. You must not go nuts, or the cake is going to fall out.'},\n {'generated_text': ' to prepare the cake before baking. The key is to find the right type of icing to use and that icing makes an amazing frosting cake.\\n\\nFor a good icing cake, we give you the basics'},\n {'generated_text': \" to remember to soak it in enough water and don't worry about it sticking to the wall. In the meantime, you could remove the top of the cake and let it dry out with a paper towel.\\n\"},\n {'generated_text': ' the best time to turn off the oven and let it stand 30 minutes. After 30 minutes, stir and bake a cake in a pan until fully moist.\\n\\nRemove the cake from the heat for about 12'}]\n```", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "Task-specific parameters", "char_start": 12227, "char_end": 13183, "token_estimate": 239, "prev_chunk_id": 58, "next_chunk_id": 60, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 60, "text": "## Chunk batching\n\nThere are some instances where you need to process data in chunks.\n\n- for some data types, a single input (for example, a really long audio file) may need to be chunked into multiple parts before it can be processed\n- for some tasks, like zero-shot classification or question answering, a single input may need multiple forward passes which can cause issues with the `batch_size` parameter\n\nThe [ChunkPipeline](https://github.com/huggingface/transformers/blob/99e0ab6ed888136ea4877c6d8ab03690a1478363/src/transformers/pipelines/base.py#L1387) class is designed to handle these use cases. Both pipeline classes are used in the same way, but since [ChunkPipeline](https://github.com/huggingface/transformers/blob/99e0ab6ed888136ea4877c6d8ab03690a1478363/src/transformers/pipelines/base.py#L1387) can automatically handle batching, you don't need to worry about the number of forward passes your inputs trigger. Instead, you can optimize `batch_size` independently of the inputs.", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "Chunk batching", "char_start": 13185, "char_end": 14180, "token_estimate": 248, "prev_chunk_id": 59, "next_chunk_id": 61, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 61, "text": "The example below shows how it differs from [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline).\n\n```py", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "Chunk batching", "char_start": 14182, "char_end": 14319, "token_estimate": 34, "prev_chunk_id": 60, "next_chunk_id": 62, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 62, "text": "# ChunkPipeline\nall_model_outputs = []\nfor preprocessed in pipeline.preprocess(inputs):\n model_outputs = pipeline.model_forward(preprocessed)\n all_model_outputs.append(model_outputs)\noutputs =pipeline.postprocess(all_model_outputs)", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "ChunkPipeline", "char_start": 14320, "char_end": 14557, "token_estimate": 59, "prev_chunk_id": 61, "next_chunk_id": 63, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 63, "text": "# Pipeline\npreprocessed = pipeline.preprocess(inputs)\nmodel_outputs = pipeline.forward(preprocessed)\noutputs = pipeline.postprocess(model_outputs)\n```", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "Pipeline", "char_start": 14559, "char_end": 14709, "token_estimate": 37, "prev_chunk_id": 62, "next_chunk_id": 64, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 64, "text": "## Large datasets\n\nFor inference with large datasets, you can iterate directly over the dataset itself. This avoids immediately allocating memory for the entire dataset, and you don't need to worry about creating batches yourself. Try [Batch inference](#batch-inference) with the `batch_size` parameter to see if it improves performance.\n\n```py\nfrom transformers.pipelines.pt_utils import KeyDataset\nfrom transformers import pipeline\nfrom accelerate import Accelerator\nfrom datasets import load_dataset\n\ndevice = Accelerator().device\n\ndataset = datasets.load_dataset(\"imdb\", name=\"plain_text\", split=\"unsupervised\")\npipeline = pipeline(task=\"text-classification\", model=\"distilbert/distilbert-base-uncased-finetuned-sst-2-english\", device=device)\nfor out in pipeline(KeyDataset(dataset, \"text\"), batch_size=8, truncation=\"only_first\"):\n print(out)\n```", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "Large datasets", "char_start": 14711, "char_end": 15565, "token_estimate": 213, "prev_chunk_id": 63, "next_chunk_id": 65, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 65, "text": "Other ways to run inference on large datasets with [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) include using an iterator or generator.\n\n```py\ndef data():\n for i in range(1000):\n yield f\"My example {i}\"\n\npipeline = pipeline(model=\"openai-community/gpt2\", device=0)\ngenerated_characters = 0\nfor out in pipeline(data()):\n generated_characters += len(out[0][\"generated_text\"])\n```", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "Large datasets", "char_start": 15567, "char_end": 15998, "token_estimate": 107, "prev_chunk_id": 64, "next_chunk_id": 66, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 66, "text": "## Large models\n\n[Accelerate](https://hf.co/docs/accelerate/index) enables a couple of optimizations for running large models with [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline). Make sure Accelerate is installed first.\n\n```py\n!pip install -U accelerate\n```\n\nThe `device_map=\"auto\"` setting is useful for automatically distributing the model across the fastest devices (GPUs) first before dispatching to other slower devices if available (CPU, hard drive).\n\n[Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) supports half-precision weights (torch.float16), which can be significantly faster and save memory. Performance loss is negligible for most models, especially for larger ones. If your hardware supports it, you can enable torch.bfloat16 instead for more range.\n\n> [!TIP]\n> Inputs are internally converted to torch.float16 and it only works for models with a PyTorch backend.", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "Large models", "char_start": 16000, "char_end": 16956, "token_estimate": 239, "prev_chunk_id": 65, "next_chunk_id": 67, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 67, "text": "Lastly, [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline) also accepts quantized models to reduce memory usage even further. Make sure you have the [bitsandbytes](https://hf.co/docs/bitsandbytes/installation) library installed first, and then add `quantization_config` to `model_kwargs` in the pipeline.\n\n```py\nimport torch\nfrom transformers import pipeline, BitsAndBytesConfig\n\npipeline = pipeline(model=\"google/gemma-7b\", dtype=torch.bfloat16, device_map=\"auto\", model_kwargs={\"quantization_config\": BitsAndBytesConfig(load_in_8bit=True)})\npipeline(\"the secret to baking a good cake is \")\n[{'generated_text': 'the secret to baking a good cake is 1. the right ingredients 2. the right'}]\n```", "source_file": "transformers/pipeline_tutorial.md", "section_heading": "Large models", "char_start": 16958, "char_end": 17686, "token_estimate": 182, "prev_chunk_id": 66, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "doc_title": "Pipeline" }, { "chunk_id": 68, "text": "# Fine-tuning\n\nFine-tuning continues training a large pretrained model on a smaller dataset specific to a task or domain. For example, fine-tuning on a dataset of coding examples helps the model get better at coding. Fine-tuning is identical to pretraining except you don't start with random weights. It also requires far less compute, data, and time.\n\nThe tutorial below walks through fine-tuning a large language model with [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer).\n\nLog in to your Hugging Face account with your user token to push your fine-tuned model to the Hub.\n\n```py\nfrom huggingface_hub import login\n\nlogin()\n```", "source_file": "transformers/training.md", "section_heading": "Fine-tuning", "char_start": 0, "char_end": 662, "token_estimate": 165, "prev_chunk_id": null, "next_chunk_id": 69, "url": "https://huggingface.co/docs/transformers/training", "doc_title": "Fine-tuning" }, { "chunk_id": 69, "text": "## Tokenization\n\nLoad a dataset and [tokenize](./fast_tokenizers) the text column the model trains on (`horoscope` in the dataset below).\n\nThe tokenizer creates the model inputs, `input_ids` and `attention_mask`. The model's forward method only accepts `input_ids` and `attention_mask`, so set `remove_columns` to drop columns like `horoscope` after tokenization.\n\n- Set `truncation=True` and a `max_length` to truncate longer sequences to a specified maximum length.\n- Use the `train_test_split` method to create a test split for evaluating the model.", "source_file": "transformers/training.md", "section_heading": "Tokenization", "char_start": 664, "char_end": 1216, "token_estimate": 138, "prev_chunk_id": 68, "next_chunk_id": 70, "url": "https://huggingface.co/docs/transformers/training", "doc_title": "Fine-tuning" }, { "chunk_id": 70, "text": "```py\nfrom datasets import load_dataset\nfrom transformers import AutoTokenizer, DataCollatorForLanguageModeling\n\nmodel_name = \"Qwen/Qwen3-0.6B\"\ntokenizer = AutoTokenizer.from_pretrained(model_name)\ndataset = load_dataset(\"karthiksagarn/astro_horoscope\", split=\"train\")\n\ndef tokenize(batch):\n return tokenizer(\n batch[\"horoscope\"],\n truncation=True,\n max_length=512,\n )\n\ndataset = dataset.map(tokenize, batched=True, remove_columns=dataset.column_names)\ndataset = dataset.train_test_split(test_size=0.1)\n```\n\nA data collator assembles dataset samples into batches for the model to process. [DataCollatorForLanguageModeling](/docs/transformers/v5.6.2/en/main_classes/data_collator#transformers.DataCollatorForLanguageModeling) *dynamically* pads each batch to the longest sequence in that batch rather than padding every sequence in the dataset to the same length. This saves compute and memory by avoiding computing unnecessary padding tokens.\n\n- Set `mlm=False` to avoid randomly masking tokens.", "source_file": "transformers/training.md", "section_heading": "Tokenization", "char_start": 1218, "char_end": 2240, "token_estimate": 255, "prev_chunk_id": 69, "next_chunk_id": 71, "url": "https://huggingface.co/docs/transformers/training", "doc_title": "Fine-tuning" }, { "chunk_id": 71, "text": "```py\ndata_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False),\n```", "source_file": "transformers/training.md", "section_heading": "Tokenization", "char_start": 2242, "char_end": 2322, "token_estimate": 20, "prev_chunk_id": 70, "next_chunk_id": 72, "url": "https://huggingface.co/docs/transformers/training", "doc_title": "Fine-tuning" }, { "chunk_id": 72, "text": "## Loading a model\n\nLoad a pretrained checkpoint to fine-tune (see the [Loading models](./models) guide for more details about loading models).\n\n- Set `dtype=\"auto\"` to load the weights in their saved dtype. Without it, PyTorch loads weights in `torch.float32`, which doubles memory usage if the weights are originally `torch.bfloat16`.\n\n```py\nfrom transformers import AutoModelForCausalLM, TrainingArguments, Trainer\n\nmodel_name = \"Qwen/Qwen3-0.6B\"\nmodel = AutoModelForCausalLM.from_pretrained(model_name, dtype=\"auto\")\n```", "source_file": "transformers/training.md", "section_heading": "Loading a model", "char_start": 2324, "char_end": 2848, "token_estimate": 131, "prev_chunk_id": 71, "next_chunk_id": 73, "url": "https://huggingface.co/docs/transformers/training", "doc_title": "Fine-tuning" }, { "chunk_id": 73, "text": "## Training configuration\n\n[TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments) provides all the options for customizing a training run. Only the most common arguments are covered here. Everything else has reasonable defaults or is only relevant to specific scenarios like distributed training. See the [TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments) API docs for a complete list of arguments.\n\n- `num_train_epochs` and `per_device_train_batch_size` control training duration and batch size. `learning_rate` sets the initial learning rate for the optimizer.", "source_file": "transformers/training.md", "section_heading": "Training configuration", "char_start": 2850, "char_end": 3510, "token_estimate": 165, "prev_chunk_id": 72, "next_chunk_id": 74, "url": "https://huggingface.co/docs/transformers/training", "doc_title": "Fine-tuning" }, { "chunk_id": 74, "text": "- Set `bf16=True` for fast mixed precision training if your hardware supports it (Ampere+ GPUs). Otherwise, fall back to `fp16=True` on older hardware.\n- `gradient_accumulation_steps` simulates a larger effective batch size by accumulating gradients over multiple forward passes before updating weights.\n- `gradient_checkpointing` trades compute for memory by recomputing intermediate activations during the backward pass instead of storing them.\n\n- `eval_strategy` and `save_strategy` determine when to evaluate a model during training and when to save a checkpoint.\n- `load_best_model_at_end` loads the best checkpoint when training finishes. It requires `eval_strategy` to be set.\n\n- `logging_steps` controls how frequently to update and return loss during training.", "source_file": "transformers/training.md", "section_heading": "Training configuration", "char_start": 3512, "char_end": 4281, "token_estimate": 192, "prev_chunk_id": 73, "next_chunk_id": 75, "url": "https://huggingface.co/docs/transformers/training", "doc_title": "Fine-tuning" }, { "chunk_id": 75, "text": "```py\ntraining_args = TrainingArguments(\n output_dir=\"qwen3-finetuned\",\n num_train_epochs=3,\n per_device_train_batch_size=2,\n gradient_accumulation_steps=8,\n gradient_checkpointing=True,\n bf16=True,\n learning_rate=2e-5,\n logging_steps=10,\n eval_strategy=\"epoch\",\n save_strategy=\"epoch\",\n load_best_model_at_end=True,\n)\n```", "source_file": "transformers/training.md", "section_heading": "Training configuration", "char_start": 4283, "char_end": 4638, "token_estimate": 88, "prev_chunk_id": 74, "next_chunk_id": 76, "url": "https://huggingface.co/docs/transformers/training", "doc_title": "Fine-tuning" }, { "chunk_id": 76, "text": "## Training\n\nCreate a [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) instance with all the necessary components, then call [train()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.train) to begin.\n\n```py\ntrainer = Trainer(\n model=model,\n args=training_args,\n train_dataset=dataset[\"train\"],\n eval_dataset=dataset[\"test\"],\n processing_class=tokenizer,\n data_collator=DataCollatorForLanguageModeling(tokenizer, mlm=False),\n)\n\ntrainer.train()\ntrainer.push_to_hub()\n```\n\n[push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.push_to_hub) uploads the fine-tuned weights, generation config, tokenizer, and model config to the Hub.", "source_file": "transformers/training.md", "section_heading": "Training", "char_start": 4640, "char_end": 5374, "token_estimate": 183, "prev_chunk_id": 75, "next_chunk_id": 77, "url": "https://huggingface.co/docs/transformers/training", "doc_title": "Fine-tuning" }, { "chunk_id": 77, "text": "## Next steps\n\n- Read the [Trainer features](./trainer_recipes) guide for minimal working examples of common Trainer features like custom loss functions, memory-efficient evaluation, checkpointing, and more.\n- Read the [Subclassing Trainer methods](./trainer_customize) guide to learn how to subclass [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) methods to support new and custom functionalities.\n- Read the [Callbacks](./trainer_callbacks) guide to learn how to hook into training events for logging, early stopping, and other custom behavior.\n- Read the [Data collators](./data_collators) guide to learn how to customize how samples are assembled into batches.\n- Browse [transformers/examples/pytorch](https://github.com/huggingface/transformers/tree/main/examples/pytorch), [notebooks](./notebooks), or the **Resources > Task Recipes** section for additional training examples on different text, audio, vision, and multimodal tasks.", "source_file": "transformers/training.md", "section_heading": "Next steps", "char_start": 5376, "char_end": 6348, "token_estimate": 243, "prev_chunk_id": 76, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/training", "doc_title": "Fine-tuning" }, { "chunk_id": 78, "text": "# Accelerate\n\n[Accelerate](https://hf.co/docs/accelerate/index) is a library designed to simplify distributed training on any type of setup with PyTorch by uniting the most common frameworks ([Fully Sharded Data Parallel (FSDP)](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/) and [DeepSpeed](https://www.deepspeed.ai/)) for it into a single interface. [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) is powered by Accelerate under the hood, enabling loading big models and distributed training.\n\nThis guide will show you two ways to use Accelerate with Transformers, using FSDP as the backend. The first method demonstrates distributed training with [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer), and the second method demonstrates adapting a PyTorch training loop. For more detailed information about Accelerate, please refer to the [documentation](https://hf.co/docs/accelerate/index).\n\n```bash\npip install accelerate\n```", "source_file": "transformers/accelerate.md", "section_heading": "Accelerate", "char_start": 0, "char_end": 1025, "token_estimate": 256, "prev_chunk_id": null, "next_chunk_id": 79, "url": "https://huggingface.co/docs/transformers/accelerate", "doc_title": "Accelerate" }, { "chunk_id": 79, "text": "Start by running [accelerate config](https://hf.co/docs/accelerate/main/en/package_reference/cli#accelerate-config) in the command line to answer a series of prompts about your training system. This creates and saves a configuration file to help Accelerate correctly set up training based on your setup.\n\n```bash\naccelerate config\n```\n\nDepending on your setup and the answers you provide, an example configuration file for distributing training with FSDP on one machine with two GPUs may look like the following.", "source_file": "transformers/accelerate.md", "section_heading": "Accelerate", "char_start": 1027, "char_end": 1539, "token_estimate": 128, "prev_chunk_id": 78, "next_chunk_id": 80, "url": "https://huggingface.co/docs/transformers/accelerate", "doc_title": "Accelerate" }, { "chunk_id": 80, "text": "```yaml\ncompute_environment: LOCAL_MACHINE\ndebug: false\ndistributed_type: FSDP\ndowncast_bf16: 'no'\nfsdp_config:\n fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP\n fsdp_backward_prefetch_policy: BACKWARD_PRE\n fsdp_forward_prefetch: false\n fsdp_cpu_ram_efficient_loading: true\n fsdp_offload_params: false\n fsdp_sharding_strategy: FULL_SHARD\n fsdp_state_dict_type: SHARDED_STATE_DICT\n fsdp_sync_module_states: true\n fsdp_transformer_layer_cls_to_wrap: BertLayer\n fsdp_use_orig_params: true\nmachine_rank: 0\nmain_training_function: main\nmixed_precision: bf16\nnum_machines: 1\nnum_processes: 2\nrdzv_backend: static\nsame_network: true\ntpu_env: []\ntpu_use_cluster: false\ntpu_use_sudo: false\nuse_cpu: false\n```", "source_file": "transformers/accelerate.md", "section_heading": "Accelerate", "char_start": 1541, "char_end": 2248, "token_estimate": 176, "prev_chunk_id": 79, "next_chunk_id": 81, "url": "https://huggingface.co/docs/transformers/accelerate", "doc_title": "Accelerate" }, { "chunk_id": 81, "text": "## Trainer\n\nPass the path to the saved configuration file to [TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments), and from there, pass your [TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments) to [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer).", "source_file": "transformers/accelerate.md", "section_heading": "Trainer", "char_start": 2250, "char_end": 2627, "token_estimate": 94, "prev_chunk_id": 80, "next_chunk_id": 82, "url": "https://huggingface.co/docs/transformers/accelerate", "doc_title": "Accelerate" }, { "chunk_id": 82, "text": "```py\nfrom transformers import TrainingArguments, Trainer\n\ntraining_args = TrainingArguments(\n output_dir=\"your-model\",\n learning_rate=2e-5,\n per_device_train_batch_size=16,\n per_device_eval_batch_size=16,\n num_train_epochs=2,\n fsdp_config=\"path/to/fsdp_config\",\n fsdp=\"full_shard\",\n weight_decay=0.01,\n eval_strategy=\"epoch\",\n save_strategy=\"epoch\",\n load_best_model_at_end=True,\n push_to_hub=True,\n)\n\ntrainer = Trainer(\n model=model,\n args=training_args,\n train_dataset=dataset[\"train\"],\n eval_dataset=dataset[\"test\"],\n processing_class=tokenizer,\n data_collator=data_collator,\n compute_metrics=compute_metrics,\n)\n\ntrainer.train()\n```", "source_file": "transformers/accelerate.md", "section_heading": "Trainer", "char_start": 2629, "char_end": 3322, "token_estimate": 173, "prev_chunk_id": 81, "next_chunk_id": 83, "url": "https://huggingface.co/docs/transformers/accelerate", "doc_title": "Accelerate" }, { "chunk_id": 83, "text": "## Native PyTorch\n\nAccelerate can also be added to any PyTorch training loop to enable distributed training. The [Accelerator](https://huggingface.co/docs/accelerate/v1.13.0/en/package_reference/accelerator#accelerate.Accelerator) is the main entry point for adapting your PyTorch code to work with Accelerate. It automatically detects your distributed training setup and initializes all the necessary components for training. You don't need to explicitly place your model on a device because [Accelerator](https://huggingface.co/docs/accelerate/v1.13.0/en/package_reference/accelerator#accelerate.Accelerator) knows which device to move your model to.\n\n```py\nfrom accelerate import Accelerator\n\naccelerator = Accelerator()\ndevice = accelerator.device\n```", "source_file": "transformers/accelerate.md", "section_heading": "Native PyTorch", "char_start": 3324, "char_end": 4079, "token_estimate": 188, "prev_chunk_id": 82, "next_chunk_id": 84, "url": "https://huggingface.co/docs/transformers/accelerate", "doc_title": "Accelerate" }, { "chunk_id": 84, "text": "All PyTorch objects (model, optimizer, scheduler, dataloaders) should be passed to the [prepare](https://huggingface.co/docs/accelerate/v1.13.0/en/package_reference/accelerator#accelerate.Accelerator.prepare) method now. This method moves your model to the appropriate device or devices, adapts the optimizer and scheduler to use [AcceleratedOptimizer](https://huggingface.co/docs/accelerate/v1.13.0/en/package_reference/torch_wrappers#accelerate.optimizer.AcceleratedOptimizer) and [AcceleratedScheduler](https://huggingface.co/docs/accelerate/v1.13.0/en/package_reference/torch_wrappers#accelerate.scheduler.AcceleratedScheduler), and creates a new shardable dataloader.\n\n```py\ntrain_dataloader, eval_dataloader, model, optimizer = accelerator.prepare(\n train_dataloader, eval_dataloader, model, optimizer\n)\n```", "source_file": "transformers/accelerate.md", "section_heading": "Native PyTorch", "char_start": 4081, "char_end": 4897, "token_estimate": 204, "prev_chunk_id": 83, "next_chunk_id": 85, "url": "https://huggingface.co/docs/transformers/accelerate", "doc_title": "Accelerate" }, { "chunk_id": 85, "text": "Replace `loss.backward` in your training loop with Accelerates [backward](https://huggingface.co/docs/accelerate/v1.13.0/en/package_reference/accelerator#accelerate.Accelerator.backward) method to scale the gradients and determine the appropriate `backward` method to use depending on your framework (for example, DeepSpeed or Megatron).\n\n```py\nfor epoch in range(num_epochs):\n for batch in train_dataloader:\n outputs = model(**batch)\n loss = outputs.loss\n accelerator.backward(loss)\n optimizer.step()\n lr_scheduler.step()\n optimizer.zero_grad()\n progress_bar.update(1)\n```\n\nCombine everything into a function and make it callable as a script.", "source_file": "transformers/accelerate.md", "section_heading": "Native PyTorch", "char_start": 4899, "char_end": 5594, "token_estimate": 173, "prev_chunk_id": 84, "next_chunk_id": 86, "url": "https://huggingface.co/docs/transformers/accelerate", "doc_title": "Accelerate" }, { "chunk_id": 86, "text": "```py\nfrom accelerate import Accelerator\n \ndef main():\n accelerator = Accelerator()\n\n model, optimizer, training_dataloader, scheduler = accelerator.prepare(\n model, optimizer, training_dataloader, scheduler\n )\n\n for batch in training_dataloader:\n optimizer.zero_grad()\n inputs, targets = batch\n outputs = model(inputs)\n loss = loss_function(outputs, targets)\n accelerator.backward(loss)\n optimizer.step()\n scheduler.step()\n\nif __name__ == \"__main__\":\n main()\n```\n\nFrom the command line, call [accelerate launch](https://hf.co/docs/accelerate/main/en/package_reference/cli#accelerate-launch) to run your training script. Any additional arguments or parameters can be passed here as well.\n\nTo launch your training script on two GPUs, add the `--num_processes` argument.\n\n```bash\naccelerate launch --num_processes=2 your_script.py\n```\n\nRefer to the [Launching Accelerate scripts](https://hf.co/docs/accelerate/main/en/basic_tutorials/launch) for more details.", "source_file": "transformers/accelerate.md", "section_heading": "Native PyTorch", "char_start": 5596, "char_end": 6601, "token_estimate": 251, "prev_chunk_id": 85, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/accelerate", "doc_title": "Accelerate" }, { "chunk_id": 87, "text": "# Parameter-efficient fine-tuning\n\n[Parameter-efficient fine-tuning (PEFT)](https://huggingface.co/docs/peft/index) methods only fine-tune a small number of extra model parameters (adapters) on top of a pretrained model. Because only adapter parameters are updated, the optimizer tracks far fewer gradients and states, reducing memory usage significantly. Adapters are lightweight, making them convenient to share, store, and load.", "source_file": "transformers/peft.md", "section_heading": "Parameter-efficient fine-tuning", "char_start": 0, "char_end": 431, "token_estimate": 107, "prev_chunk_id": null, "next_chunk_id": 88, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 88, "text": "Transformers integrates directly with the PEFT library through [PeftAdapterMixin](/docs/transformers/v5.6.2/en/main_classes/peft#transformers.integrations.PeftAdapterMixin), added to all [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel) classes. You can load, add, train, switch, and delete adapters without wrapping your model in a separate `PeftModel`. All non-prompt-learning PEFT methods are supported (LoRA, IA3, AdaLoRA). Prompt-based methods like prompt tuning and prefix tuning require using the [PEFT library](https://huggingface.co/docs/peft/index) directly.\n\nInstall PEFT to get started. The integration requires `peft >= 0.18.0`.\n\n```shell\npip install -U peft\n```", "source_file": "transformers/peft.md", "section_heading": "Parameter-efficient fine-tuning", "char_start": 433, "char_end": 1154, "token_estimate": 180, "prev_chunk_id": 87, "next_chunk_id": 89, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 89, "text": "## Add an adapter\n\nCreate a PEFT config, like `LoraConfig` for example, and attach it to a model with [add_adapter()](/docs/transformers/v5.6.2/en/main_classes/peft#transformers.integrations.PeftAdapterMixin.add_adapter).\n\n```py\nfrom peft import LoraConfig, TaskType\nfrom transformers import AutoModelForCausalLM\n\nmodel = AutoModelForCausalLM.from_pretrained(\"google/gemma-2-2b\")\n\nlora_config = LoraConfig(\n task_type=TaskType.CAUSAL_LM,\n inference_mode=False,\n r=8,\n lora_alpha=32,\n lora_dropout=0.1,\n)\n\nmodel.add_adapter(lora_config, adapter_name=\"my_adapter\")\n```", "source_file": "transformers/peft.md", "section_heading": "Add an adapter", "char_start": 1156, "char_end": 1737, "token_estimate": 145, "prev_chunk_id": 88, "next_chunk_id": 90, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 90, "text": "### Fully fine-tuning specific layers\n\nTo train additional modules alongside an adapter (for example, the language model head), specify them in `modules_to_save`. `modules_to_save` specifies layers that are fully fine-tuned alongside the adapter, so *all* of their parameters are updated. This is useful when certain layers need updates, for example the language model head (`lm_head`), when adapting a causal LM for sequence classification.\n\n```py\nlora_config = LoraConfig(\n modules_to_save=[\"lm_head\"],\n ...\n)\nmodel.add_adapter(lora_config)\n```", "source_file": "transformers/peft.md", "section_heading": "Fully fine-tuning specific layers", "char_start": 1739, "char_end": 2291, "token_estimate": 138, "prev_chunk_id": 89, "next_chunk_id": 91, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 91, "text": "### Choosing which layers to adapt\n\nFor common architectures (Llama, Gemma, Qwen, etc.), PEFT has predefined default targets (like `q_proj` and `v_proj`), so you don't need to specify `target_modules`. If you want to target different layers, or the model doesn't have predefined targets, pass `target_modules` explicitly as a list of module names or a regex pattern.\n\n```py\nlora_config = LoraConfig(\n target_modules=[\"q_proj\", \"k_proj\"],\n ...\n)\nmodel.add_adapter(lora_config)\n```", "source_file": "transformers/peft.md", "section_heading": "Choosing which layers to adapt", "char_start": 2293, "char_end": 2778, "token_estimate": 121, "prev_chunk_id": 90, "next_chunk_id": 92, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 92, "text": "## Training\n\nPass the model with an attached adapter to [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) and call [train()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.train). [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) only updates the adapter parameters (those with `requires_grad=True`) because the base model is frozen.\n\n```py\nfrom transformers import Trainer, TrainingArguments\n\ntraining_args = TrainingArguments(\n output_dir=\"./output\",\n num_train_epochs=3,\n per_device_train_batch_size=4,\n)\n\ntrainer = Trainer(\n model=model,\n args=training_args,\n train_dataset=dataset,\n)\n\ntrainer.train()\n```\n\nDuring training, [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) checkpoints contain only the adapter weights (`adapter_model.safetensors`) and configuration (`adapter_config.json`), keeping checkpoints small. The base model isn't included.", "source_file": "transformers/peft.md", "section_heading": "Training", "char_start": 2780, "char_end": 3771, "token_estimate": 247, "prev_chunk_id": 91, "next_chunk_id": 93, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 93, "text": "After training, save the final adapter with [save_pretrained()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel.save_pretrained).\n\n```py\nmodel.save_pretrained(\"./my_adapter\")\n```", "source_file": "transformers/peft.md", "section_heading": "Training", "char_start": 3773, "char_end": 3980, "token_estimate": 51, "prev_chunk_id": 92, "next_chunk_id": 94, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 94, "text": "### Resuming from a checkpoint\n\n[Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) automatically detects adapter checkpoints when resuming. [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) scans the checkpoint directory for subdirectories containing adapter weights and reloads each adapter with the correct trainable state.\n\n```py\ntrainer.train(resume_from_checkpoint=\"./output/checkpoint-1000\")\n```", "source_file": "transformers/peft.md", "section_heading": "Resuming from a checkpoint", "char_start": 3982, "char_end": 4446, "token_estimate": 116, "prev_chunk_id": 93, "next_chunk_id": 95, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 95, "text": "### Distributed training\n\nPEFT adapters work with distributed training out of the box.\n\nFor ZeRO-3, [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) passes `exclude_frozen_parameters=True` when saving checkpoints with a PEFT model. Frozen base model weights are skipped. Only the trainable adapter parameters are saved, reducing checkpoint size and save time.\n\nFor FSDP, [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) updates the FSDP auto-wrap policy to correctly handle LoRA layers. For QLoRA (quantized base model + LoRA), [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) also adjusts the mixed precision policy to match the quantization storage dtype.", "source_file": "transformers/peft.md", "section_heading": "Distributed training", "char_start": 4448, "char_end": 5204, "token_estimate": 189, "prev_chunk_id": 94, "next_chunk_id": 96, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 96, "text": "## Loading an adapter\n\nTo load an adapter, the Hub repository or local directory must contain an `adapter_config.json` file and the adapter weights.\n\n[from_pretrained()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) automatically detects adapters. When it finds an `adapter_config.json`, it reads the `base_model_name_or_path` field to load the correct base model, then loads the adapter on top.\n\n```py\nfrom transformers import AutoModelForCausalLM", "source_file": "transformers/peft.md", "section_heading": "Loading an adapter", "char_start": 5206, "char_end": 5702, "token_estimate": 124, "prev_chunk_id": 95, "next_chunk_id": 97, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 97, "text": "# Automatically loads the base model and attaches the adapter\nmodel = AutoModelForCausalLM.from_pretrained(\"klcsp/gemma7b-lora-alpaca-11-v1\")\n```\n\nTo load an adapter onto an existing model, use [load_adapter()](/docs/transformers/v5.6.2/en/main_classes/peft#transformers.integrations.PeftAdapterMixin.load_adapter).\n\n```py\nfrom transformers import AutoModelForCausalLM\n\nmodel = AutoModelForCausalLM.from_pretrained(\"google/gemma-7b\")\nmodel.load_adapter(\"klcsp/gemma7b-lora-alpaca-11-v1\")\n```\n\nFor large models, load a quantized version in 8-bit or 4-bit precision with [bitsandbytes](./quantization/bitsandbytes) to save memory. Add `device_map=\"auto\"` to distribute the model across available hardware.\n\n```py\nfrom transformers import AutoModelForCausalLM, BitsAndBytesConfig\n\nmodel = AutoModelForCausalLM.from_pretrained(\n \"klcsp/gemma7b-lora-alpaca-11-v1\",\n quantization_config=BitsAndBytesConfig(load_in_8bit=True),\n device_map=\"auto\",\n)\n```", "source_file": "transformers/peft.md", "section_heading": "Automatically loads the base model and attaches the adapter", "char_start": 5704, "char_end": 6658, "token_estimate": 238, "prev_chunk_id": 96, "next_chunk_id": 98, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 98, "text": "## Managing multiple adapters\n\nA model can hold multiple adapters at once. Add adapters with unique names, and switch between them as needed.\n\n```py\nfrom peft import LoraConfig\n\nmodel.add_adapter(LoraConfig(r=8, lora_alpha=32), adapter_name=\"adapter_1\")\nmodel.add_adapter(LoraConfig(r=16, lora_alpha=64), adapter_name=\"adapter_2\")\n```\n\nUse [set_adapter()](/docs/transformers/v5.6.2/en/main_classes/peft#transformers.integrations.PeftAdapterMixin.set_adapter) to activate a specific adapter. The other adapters are disabled but remain in memory.\n\n```py\nmodel.set_adapter(\"adapter_2\")\n```\n\n[enable_adapters()](/docs/transformers/v5.6.2/en/main_classes/peft#transformers.integrations.PeftAdapterMixin.enable_adapters) enables all attached adapters, and [disable_adapters()](/docs/transformers/v5.6.2/en/main_classes/peft#transformers.integrations.PeftAdapterMixin.disable_adapters) disables all of them.\n\n```py", "source_file": "transformers/peft.md", "section_heading": "Managing multiple adapters", "char_start": 6660, "char_end": 7567, "token_estimate": 226, "prev_chunk_id": 97, "next_chunk_id": 99, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 99, "text": "# Disable all adapters for base model inference\nmodel.disable_adapters()", "source_file": "transformers/peft.md", "section_heading": "Disable all adapters for base model inference", "char_start": 7568, "char_end": 7640, "token_estimate": 18, "prev_chunk_id": 98, "next_chunk_id": 100, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 100, "text": "# Re-enable all adapters\nmodel.enable_adapters()\n```\n\nUse [active_adapters()](/docs/transformers/v5.6.2/en/main_classes/peft#transformers.integrations.PeftAdapterMixin.active_adapters) to see which adapters are currently active.\n\n```py\nmodel.active_adapters()", "source_file": "transformers/peft.md", "section_heading": "Re-enable all adapters", "char_start": 7642, "char_end": 7901, "token_estimate": 64, "prev_chunk_id": 99, "next_chunk_id": 101, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 101, "text": "# [\"adapter_1\"]\n```\n\nRemove adapters you no longer need with [delete_adapter()](/docs/transformers/v5.6.2/en/main_classes/peft#transformers.integrations.PeftAdapterMixin.delete_adapter) to free memory.\n\n```py\nmodel.delete_adapter(\"adapter_1\")\n```", "source_file": "transformers/peft.md", "section_heading": "[\"adapter_1\"]", "char_start": 7902, "char_end": 8148, "token_estimate": 61, "prev_chunk_id": 100, "next_chunk_id": 102, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 102, "text": "## Hotswapping adapters\n\nLoading a new adapter each time you serve a request allocates new memory. If the model is compiled with `torch.compile`, each new adapter triggers recompilation. Hotswapping replaces adapter weights in-place, avoiding both issues. Only LoRA adapters are supported.\n\nPass `hotswap=True` when loading a LoRA adapter to swap its weights into an existing adapter slot. Set `adapter_name` to the name of the adapter to replace (`\"default\"` is the default adapter name).\n\n```py\nmodel = AutoModel.from_pretrained(...)", "source_file": "transformers/peft.md", "section_heading": "Hotswapping adapters", "char_start": 8150, "char_end": 8685, "token_estimate": 133, "prev_chunk_id": 101, "next_chunk_id": 103, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 103, "text": "# Load the first adapter normally\nmodel.load_adapter(adapter_path_1)", "source_file": "transformers/peft.md", "section_heading": "Load the first adapter normally", "char_start": 8686, "char_end": 8754, "token_estimate": 17, "prev_chunk_id": 102, "next_chunk_id": 104, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 104, "text": "# Generate outputs with adapter 1\n...", "source_file": "transformers/peft.md", "section_heading": "Generate outputs with adapter 1", "char_start": 8755, "char_end": 8792, "token_estimate": 9, "prev_chunk_id": 103, "next_chunk_id": 105, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 105, "text": "# Hotswap the second adapter in-place\nmodel.load_adapter(adapter_path_2, hotswap=True, adapter_name=\"default\")", "source_file": "transformers/peft.md", "section_heading": "Hotswap the second adapter in-place", "char_start": 8793, "char_end": 8903, "token_estimate": 27, "prev_chunk_id": 104, "next_chunk_id": 106, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 106, "text": "# Generate outputs with adapter 2\n```", "source_file": "transformers/peft.md", "section_heading": "Generate outputs with adapter 2", "char_start": 8904, "char_end": 8941, "token_estimate": 9, "prev_chunk_id": 105, "next_chunk_id": 107, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 107, "text": "### torch.compile\n\nFor compiled models, call [enable_peft_hotswap()](/docs/transformers/v5.6.2/en/main_classes/peft#transformers.integrations.PeftAdapterMixin.enable_peft_hotswap) *before* loading the first adapter and before compiling.\n\n```py\nmodel = AutoModel.from_pretrained(...)\nmax_rank = ... # highest rank among all LoRAs you'll load\nmodel.enable_peft_hotswap(target_rank=max_rank)\nmodel.load_adapter(adapter_path_1, adapter_name=\"default\")\nmodel = torch.compile(model, ...)\noutput_1 = model(...)", "source_file": "transformers/peft.md", "section_heading": "torch.compile", "char_start": 8943, "char_end": 9447, "token_estimate": 126, "prev_chunk_id": 106, "next_chunk_id": 108, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 108, "text": "# Hotswap without recompilation\nmodel.load_adapter(adapter_path_2, adapter_name=\"default\")\noutput_2 = model(...)\n```\n\nThe `target_rank` argument sets the maximum rank among all LoRA adapters you'll load. If you have adapters with rank 8 and rank 16, pass `target_rank=16`. The default is 128.\n\nAfter calling `enable_peft_hotswap`, all subsequent `load_adapter` calls hotswap by default. Pass `hotswap=False` explicitly to disable hotswapping.\n\nRecompilation may still occur if the hotswapped adapter targets more layers than the initial adapter. Load the adapter that targets the most layers first to avoid recompilation.\n\n> [!TIP]\n> Wrap your code in `with torch._dynamo.config.patch(error_on_recompile=True)` to detect unexpected recompilation. If you detect recompilation despite following the steps above, open an issue with [PEFT](https://github.com/huggingface/peft/issues) with a reproducible example.", "source_file": "transformers/peft.md", "section_heading": "Hotswap without recompilation", "char_start": 9449, "char_end": 10357, "token_estimate": 227, "prev_chunk_id": 107, "next_chunk_id": 109, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 109, "text": "## Next steps\n\n- The PEFT [documentation](https://huggingface.co/docs/peft/index) covers the full range of PEFT methods and options.\n- The PEFT [hotswapping reference](https://huggingface.co/docs/peft/main/en/package_reference/hotswap#peft.utils.hotswap.hotswap_adapter) details limitations and edge cases.\n- A [blog post](https://huggingface.co/blog/lora-fast) benchmarks how `torch.compile` with hotswapping improves runtime.", "source_file": "transformers/peft.md", "section_heading": "Next steps", "char_start": 10359, "char_end": 10786, "token_estimate": 106, "prev_chunk_id": 108, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/peft", "doc_title": "Parameter-efficient fine-tuning" }, { "chunk_id": 110, "text": "# Sharing\n\nThe Hugging Face [Hub](https://hf.co/models) is a platform for sharing, discovering, and consuming models of all different types and sizes. We highly recommend sharing your model on the Hub to push open-source machine learning forward for everyone!\n\nThis guide will show you how to share a model to the Hub from Transformers.", "source_file": "transformers/model_sharing.md", "section_heading": "Sharing", "char_start": 0, "char_end": 336, "token_estimate": 84, "prev_chunk_id": null, "next_chunk_id": 111, "url": "https://huggingface.co/docs/transformers/model_sharing", "doc_title": "Sharing" }, { "chunk_id": 111, "text": "## Set up\n\nTo share a model to the Hub, you need a Hugging Face [account](https://hf.co/join). Create a [User Access Token](https://hf.co/docs/hub/security-tokens#user-access-tokens) (stored in the [cache](./installation#cache-directory) by default) and login to your account from either the command line or notebook.\n\n```bash\nhf auth login\n```\n\n```py\nfrom huggingface_hub import notebook_login\n\nnotebook_login()\n```", "source_file": "transformers/model_sharing.md", "section_heading": "Set up", "char_start": 338, "char_end": 754, "token_estimate": 104, "prev_chunk_id": 110, "next_chunk_id": 112, "url": "https://huggingface.co/docs/transformers/model_sharing", "doc_title": "Sharing" }, { "chunk_id": 112, "text": "## Repository features\n\nEach model repository features versioning, commit history, and diff visualization.\n\nVersioning is based on [Git](https://git-scm.com/) and [Git Large File Storage (LFS)](https://git-lfs.github.com/), and it enables revisions, a way to specify a model version with a commit hash, tag or branch.\n\nFor example, use the `revision` parameter in [from_pretrained()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) to load a specific model version from a commit hash.\n\n```py\nmodel = AutoModel.from_pretrained(\n \"julien-c/EsperBERTo-small\", revision=\"4c77982\"\n)\n```\n\nModel repositories also support [gating](https://hf.co/docs/hub/models-gated) to control who can access a model. Gating is common for allowing a select group of users to preview a research model before it's made public.\n\nA model repository also includes an inference [widget](https://hf.co/docs/hub/models-widgets) for users to directly interact with a model on the Hub.", "source_file": "transformers/model_sharing.md", "section_heading": "Repository features", "char_start": 0, "char_end": 1002, "token_estimate": 250, "prev_chunk_id": 111, "next_chunk_id": 113, "url": "https://huggingface.co/docs/transformers/model_sharing", "doc_title": "Sharing" }, { "chunk_id": 113, "text": "Check out the Hub [Models](https://hf.co/docs/hub/models) documentation to for more information.", "source_file": "transformers/model_sharing.md", "section_heading": "Repository features", "char_start": 1772, "char_end": 1868, "token_estimate": 24, "prev_chunk_id": 112, "next_chunk_id": 114, "url": "https://huggingface.co/docs/transformers/model_sharing", "doc_title": "Sharing" }, { "chunk_id": 114, "text": "## Uploading a model\n\nThere are several ways to upload a model to the Hub depending on your workflow preference. You can push a model with [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer), call [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.utils.PushToHubMixin.push_to_hub) directly on a model, or use the Hub web interface.", "source_file": "transformers/model_sharing.md", "section_heading": "Uploading a model", "char_start": 1870, "char_end": 2258, "token_estimate": 97, "prev_chunk_id": 113, "next_chunk_id": 115, "url": "https://huggingface.co/docs/transformers/model_sharing", "doc_title": "Sharing" }, { "chunk_id": 115, "text": "### Trainer\n\n[Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) can push a model directly to the Hub after training. Set `push_to_hub=True` in [TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments) and pass it to [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer). Once training is complete, call [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.push_to_hub) to upload the model.\n\n[push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.push_to_hub) automatically adds useful information like training hyperparameters and results to the model card.", "source_file": "transformers/model_sharing.md", "section_heading": "Trainer", "char_start": 2260, "char_end": 2986, "token_estimate": 181, "prev_chunk_id": 114, "next_chunk_id": 116, "url": "https://huggingface.co/docs/transformers/model_sharing", "doc_title": "Sharing" }, { "chunk_id": 116, "text": "```py\nfrom transformers import TrainingArguments, Trainer\n\ntraining_args = TrainingArguments(output_dir=\"my-awesome-model\", push_to_hub=True)\ntrainer = Trainer(\n model=model,\n args=training_args,\n train_dataset=small_train_dataset,\n eval_dataset=small_eval_dataset,\n compute_metrics=compute_metrics,\n)\ntrainer.push_to_hub()\n```", "source_file": "transformers/model_sharing.md", "section_heading": "Trainer", "char_start": 2988, "char_end": 3330, "token_estimate": 85, "prev_chunk_id": 115, "next_chunk_id": 117, "url": "https://huggingface.co/docs/transformers/model_sharing", "doc_title": "Sharing" }, { "chunk_id": 117, "text": "### PushToHubMixin\n\nThe [PushToHubMixin](/docs/transformers/v5.6.2/en/main_classes/model#transformers.utils.PushToHubMixin) provides functionality for pushing a model or tokenizer to the Hub.\n\nCall [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.utils.PushToHubMixin.push_to_hub) directly on a model to upload it to the Hub. It creates a repository under your namespace with the model name specified in [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.utils.PushToHubMixin.push_to_hub).\n\n```py\nmodel.push_to_hub(\"my-awesome-model\")\n```\n\nOther objects like a tokenizer are also pushed to the Hub in the same way.\n\n```py\ntokenizer.push_to_hub(\"my-awesome-model\")\n```\n\nYour Hugging Face profile should now display the newly created model repository. Navigate to the **Files** tab to see all the uploaded files.\n\nRefer to the [Upload files to the Hub](https://hf.co/docs/hub/how-to-upstream) guide for more information about pushing files to the Hub.", "source_file": "transformers/model_sharing.md", "section_heading": "PushToHubMixin", "char_start": 3332, "char_end": 4335, "token_estimate": 250, "prev_chunk_id": 116, "next_chunk_id": 118, "url": "https://huggingface.co/docs/transformers/model_sharing", "doc_title": "Sharing" }, { "chunk_id": 118, "text": "### Hub web interface\n\nThe Hub web interface is a no-code approach for uploading a model.\n\n1. Create a new repository by selecting [**New Model**](https://huggingface.co/new).\n\n \n\nAdd some information about your model:\n\n- Select the **owner** of the repository. This can be yourself or any of the organizations you belong to.\n- Pick a name for your model, which will also be the repository name.\n- Choose whether your model is public or private.\n- Set the license usage.\n\n2. Click on **Create model** to create the model repository.\n\n3. Select the **Files** tab and click on the **Add file** button to drag-and-drop a file to your repository. Add a commit message and click on **Commit changes to main** to commit the file.", "source_file": "transformers/model_sharing.md", "section_heading": "Hub web interface", "char_start": 4337, "char_end": 5063, "token_estimate": 181, "prev_chunk_id": 117, "next_chunk_id": 119, "url": "https://huggingface.co/docs/transformers/model_sharing", "doc_title": "Sharing" }, { "chunk_id": 119, "text": "## Model card\n\n[Model cards](https://hf.co/docs/hub/model-cards#model-cards) inform users about a models performance, limitations, potential biases, and ethical considerations. It is highly recommended to add a model card to your repository!\n\nA model card is a `README.md` file in your repository. Add this file by:\n\n- manually creating and uploading a `README.md` file\n- clicking on the **Edit model card** button in the repository\n\nTake a look at the Llama 3.1 [model card](https://huggingface.co/meta-llama/Meta-Llama-3.1-8B-Instruct) for an example of what to include on a model card.\n\nLearn more about other model card metadata (carbon emissions, license, link to paper, etc.) available in the [Model Cards](https://hf.co/docs/hub/model-cards#model-cards) guide.", "source_file": "transformers/model_sharing.md", "section_heading": "Model card", "char_start": 5071, "char_end": 5838, "token_estimate": 191, "prev_chunk_id": 118, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/model_sharing", "doc_title": "Sharing" }, { "chunk_id": 120, "text": "# Text generation\n\nText generation is the most popular application for large language models (LLMs). A LLM is trained to generate the next word (token) given some initial text (prompt) along with its own generated outputs up to a predefined length or when it reaches an end-of-sequence (`EOS`) token.\n\nIn Transformers, the [generate()](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationMixin.generate) API handles text generation, and it is available for all models with generative capabilities. This guide will show you the basics of text generation with [generate()](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationMixin.generate) and some common pitfalls to avoid.\n\n> [!TIP]\n> For the following commands, please make sure [`transformers serve` is running](https://huggingface.co/docs/transformers/main/en/serving).\n>\n> ```shell\n> transformers chat Qwen/Qwen2.5-0.5B-Instruct\n> ```", "source_file": "transformers/llm_tutorial.md", "section_heading": "Text generation", "char_start": 0, "char_end": 947, "token_estimate": 236, "prev_chunk_id": null, "next_chunk_id": 121, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 121, "text": "## Default generate\n\nBefore you begin, it's helpful to install [bitsandbytes](https://hf.co/docs/bitsandbytes/index) to quantize really large models to reduce their memory usage.\n\n```bash\n!pip install -U transformers bitsandbytes\n```\n\nBitsandbytes supports multiple backends in addition to CUDA-based GPUs. Refer to the multi-backend installation [guide](https://huggingface.co/docs/bitsandbytes/main/en/installation#multi-backend) to learn more.\n\nLoad a LLM with [from_pretrained()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) and add the following two parameters to reduce the memory requirements.", "source_file": "transformers/llm_tutorial.md", "section_heading": "Default generate", "char_start": 949, "char_end": 1598, "token_estimate": 162, "prev_chunk_id": 120, "next_chunk_id": 122, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 122, "text": "- `device_map=\"auto\"` enables Accelerates' [Big Model Inference](./models#big-model-inference) feature for automatically initiating the model skeleton and loading and dispatching the model weights across all available devices, starting with the fastest device (GPU).\n- `quantization_config` is a configuration object that defines the quantization settings. This examples uses bitsandbytes as the quantization backend (see the [Quantization](./quantization/overview) section for more available backends) and it loads the model in [4-bits](./quantization/bitsandbytes).\n\n```py\nfrom transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig\n\nquantization_config = BitsAndBytesConfig(load_in_4bit=True)\nmodel = AutoModelForCausalLM.from_pretrained(\"mistralai/Mistral-7B-v0.1\", device_map=\"auto\", quantization_config=quantization_config)\n```", "source_file": "transformers/llm_tutorial.md", "section_heading": "Default generate", "char_start": 1600, "char_end": 2454, "token_estimate": 213, "prev_chunk_id": 121, "next_chunk_id": 123, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 123, "text": "Tokenize your input, and set the `padding_side()` parameter to `\"left\"` because a LLM is not trained to continue generation from padding tokens. The tokenizer returns the input ids and attention mask.\n\n> [!TIP]\n> Process more than one prompt at a time by passing a list of strings to the tokenizer. Batch the inputs to improve throughput at a small cost to latency and memory.\n\n```py\ntokenizer = AutoTokenizer.from_pretrained(\"mistralai/Mistral-7B-v0.1\", padding_side=\"left\")\nmodel_inputs = tokenizer([\"A list of colors: red, blue\"], return_tensors=\"pt\").to(model.device)\n```\n\nPass the inputs to [generate()](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationMixin.generate) to generate tokens, and [batch_decode()](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.batch_decode) the generated tokens back to text.", "source_file": "transformers/llm_tutorial.md", "section_heading": "Default generate", "char_start": 2456, "char_end": 3345, "token_estimate": 222, "prev_chunk_id": 122, "next_chunk_id": 124, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 124, "text": "```py\ngenerated_ids = model.generate(**model_inputs)\ntokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]\n\"A list of colors: red, blue, green, yellow, orange, purple, pink,\"\n```", "source_file": "transformers/llm_tutorial.md", "section_heading": "Default generate", "char_start": 3347, "char_end": 3538, "token_estimate": 47, "prev_chunk_id": 123, "next_chunk_id": 125, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 125, "text": "## Generation configuration\n\nAll generation settings are contained in [GenerationConfig](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig). In the example above, the generation settings are derived from the `generation_config.json` file of [mistralai/Mistral-7B-v0.1](https://huggingface.co/mistralai/Mistral-7B-v0.1). A default decoding strategy is used when no configuration is saved with a model.\n\nInspect the configuration through the `generation_config` attribute. It only shows values that are different from the default configuration, in this case, the `bos_token_id` and `eos_token_id`.\n\n```py\nfrom transformers import AutoModelForCausalLM\n\nmodel = AutoModelForCausalLM.from_pretrained(\"mistralai/Mistral-7B-v0.1\", device_map=\"auto\")\nmodel.generation_config\nGenerationConfig {\n \"bos_token_id\": 1,\n \"eos_token_id\": 2\n}\n```", "source_file": "transformers/llm_tutorial.md", "section_heading": "Generation configuration", "char_start": 3540, "char_end": 4410, "token_estimate": 217, "prev_chunk_id": 124, "next_chunk_id": 126, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 126, "text": "You can customize [generate()](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationMixin.generate) by overriding the parameters and values in [GenerationConfig](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig). See [this section below](#common-options) for commonly adjusted parameters.\n\n```py", "source_file": "transformers/llm_tutorial.md", "section_heading": "Generation configuration", "char_start": 4412, "char_end": 4774, "token_estimate": 90, "prev_chunk_id": 125, "next_chunk_id": 127, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 127, "text": "# enable beam search sampling strategy\nmodel.generate(**inputs, num_beams=4, do_sample=True)\n```\n\n[generate()](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationMixin.generate) can also be extended with external libraries or custom code:\n\n1. the `logits_processor` parameter accepts custom [LogitsProcessor](/docs/transformers/v5.6.2/en/internal/generation_utils#transformers.LogitsProcessor) instances for manipulating the next token probability distribution;\n2. the `stopping_criteria` parameters supports custom [StoppingCriteria](/docs/transformers/v5.6.2/en/internal/generation_utils#transformers.StoppingCriteria) to stop text generation;\n3. other custom generation methods can be loaded through the `custom_generate` flag ([docs](generation_strategies.md/#custom-decoding-methods)).\n\nRefer to the [Generation strategies](./generation_strategies) guide to learn more about search, sampling, and decoding strategies.", "source_file": "transformers/llm_tutorial.md", "section_heading": "enable beam search sampling strategy", "char_start": 4775, "char_end": 5727, "token_estimate": 238, "prev_chunk_id": 126, "next_chunk_id": 128, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 128, "text": "### Saving\n\nCreate an instance of [GenerationConfig](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig) and specify the decoding parameters you want.\n\n```py\nfrom transformers import AutoModelForCausalLM, GenerationConfig\n\nmodel = AutoModelForCausalLM.from_pretrained(\"my_account/my_model\")\ngeneration_config = GenerationConfig(\n max_new_tokens=50, do_sample=True, top_k=50, eos_token_id=model.config.eos_token_id\n)\n```\n\nUse [save_pretrained()](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig.save_pretrained) to save a specific generation configuration and set the `push_to_hub` parameter to `True` to upload it to the Hub.\n\n```py\ngeneration_config.save_pretrained(\"my_account/my_model\", push_to_hub=True)\n```", "source_file": "transformers/llm_tutorial.md", "section_heading": "Saving", "char_start": 5729, "char_end": 6519, "token_estimate": 197, "prev_chunk_id": 127, "next_chunk_id": 129, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 129, "text": "Leave the `config_file_name` parameter empty. This parameter should be used when storing multiple generation configurations in a single directory. It gives you a way to specify which generation configuration to load. You can create different configurations for different generative tasks (creative text generation with sampling, summarization with beam search) for use with a single model.", "source_file": "transformers/llm_tutorial.md", "section_heading": "Saving", "char_start": 6521, "char_end": 6910, "token_estimate": 97, "prev_chunk_id": 128, "next_chunk_id": 130, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 130, "text": "```py\nfrom transformers import AutoModelForSeq2SeqLM, AutoTokenizer, GenerationConfig\n\ntokenizer = AutoTokenizer.from_pretrained(\"google-t5/t5-small\")\nmodel = AutoModelForSeq2SeqLM.from_pretrained(\"google-t5/t5-small\")\n\ntranslation_generation_config = GenerationConfig(\n num_beams=4,\n early_stopping=True,\n decoder_start_token_id=0,\n eos_token_id=model.config.eos_token_id,\n pad_token=model.config.pad_token_id,\n)\n\ntranslation_generation_config.save_pretrained(\"/tmp\", config_file_name=\"translation_generation_config.json\", push_to_hub=True)\n\ngeneration_config = GenerationConfig.from_pretrained(\"/tmp\", config_file_name=\"translation_generation_config.json\")\ninputs = tokenizer(\"translate English to French: Configuration files are easy to use!\", return_tensors=\"pt\")\noutputs = model.generate(**inputs, generation_config=generation_config)\nprint(tokenizer.batch_decode(outputs, skip_special_tokens=True))\n```", "source_file": "transformers/llm_tutorial.md", "section_heading": "Saving", "char_start": 6912, "char_end": 7835, "token_estimate": 230, "prev_chunk_id": 129, "next_chunk_id": 131, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 131, "text": "## Common Options\n\n[generate()](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationMixin.generate) is a powerful tool that can be heavily customized. This can be daunting for a new users. This section contains a list of popular generation options that you can define in most text generation tools in Transformers: [generate()](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationMixin.generate), [GenerationConfig](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig), `pipelines`, the `chat` CLI, ...", "source_file": "transformers/llm_tutorial.md", "section_heading": "Common Options", "char_start": 7837, "char_end": 8433, "token_estimate": 149, "prev_chunk_id": 130, "next_chunk_id": 132, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 132, "text": "| Option name | Type | Simplified description |\n|---|---|---|\n| `max_new_tokens` | `int` | Controls the maximum generation length. Be sure to define it, as it usually defaults to a small value. |\n| `do_sample` | `bool` | Defines whether generation will sample the next token (`True`), or is greedy instead (`False`). Most use cases should set this flag to `True`. Check [this guide](./generation_strategies) for more information. |\n| `temperature` | `float` | How unpredictable the next selected token will be. High values (`>0.8`) are good for creative tasks, low values (e.g. `1`, activates the beam search algorithm. Beam search is good on input-grounded tasks. Check [this guide](./generation_strategies) for more information. |\n| `repetition_penalty` | `float` | Set it to `>1.0` if you're seeing the model repeat itself often. Larger values apply a larger penalty. |\n| `eos_token_id` | `list[int]` | The token(s) that will cause generation to stop. The default value is usually good, but you can specify a different token. |", "source_file": "transformers/llm_tutorial.md", "section_heading": "Common Options", "char_start": 8435, "char_end": 9465, "token_estimate": 257, "prev_chunk_id": 131, "next_chunk_id": 133, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 133, "text": "## Pitfalls\n\nThe section below covers some common issues you may encounter during text generation and how to solve them.", "source_file": "transformers/llm_tutorial.md", "section_heading": "Pitfalls", "char_start": 9467, "char_end": 9587, "token_estimate": 30, "prev_chunk_id": 132, "next_chunk_id": 134, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 134, "text": "### Output length\n\n[generate()](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationMixin.generate) returns up to 20 tokens by default unless otherwise specified in a models [GenerationConfig](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig). It is highly recommended to manually set the number of generated tokens with the `max_new_tokens` parameter to control the output length. [Decoder-only](https://hf.co/learn/nlp-course/chapter1/6?fw=pt) models returns the initial prompt along with the generated tokens.\n\n```py\nmodel_inputs = tokenizer([\"A sequence of numbers: 1, 2\"], return_tensors=\"pt\").to(model.device)\n```\n\n```py\ngenerated_ids = model.generate(**model_inputs)\ntokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]\n'A sequence of numbers: 1, 2, 3, 4, 5'\n```", "source_file": "transformers/llm_tutorial.md", "section_heading": "Output length", "char_start": 9589, "char_end": 10440, "token_estimate": 212, "prev_chunk_id": 133, "next_chunk_id": 135, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 135, "text": "```py\ngenerated_ids = model.generate(**model_inputs, max_new_tokens=50)\ntokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]\n'A sequence of numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,'\n```", "source_file": "transformers/llm_tutorial.md", "section_heading": "Output length", "char_start": 10442, "char_end": 10664, "token_estimate": 55, "prev_chunk_id": 134, "next_chunk_id": 136, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 136, "text": "### Decoding strategy\n\nThe default decoding strategy in [generate()](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationMixin.generate) is *greedy search*, which selects the next most likely token, unless otherwise specified in a models [GenerationConfig](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig). While this decoding strategy works well for input-grounded tasks (transcription, translation), it is not optimal for more creative use cases (story writing, chat applications).\n\nFor example, enable a [multinomial sampling](./generation_strategies#multinomial-sampling) strategy to generate more diverse outputs. Refer to the [Generation strategy](./generation_strategies) guide for more decoding strategies.\n\n```py\nmodel_inputs = tokenizer([\"I am a cat.\"], return_tensors=\"pt\").to(model.device)\n```\n\n```py\ngenerated_ids = model.generate(**model_inputs)\ntokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]\n```", "source_file": "transformers/llm_tutorial.md", "section_heading": "Decoding strategy", "char_start": 10666, "char_end": 11665, "token_estimate": 249, "prev_chunk_id": 135, "next_chunk_id": 137, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 137, "text": "```py\ngenerated_ids = model.generate(**model_inputs, do_sample=True)\ntokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]\n```", "source_file": "transformers/llm_tutorial.md", "section_heading": "Decoding strategy", "char_start": 11667, "char_end": 11806, "token_estimate": 34, "prev_chunk_id": 136, "next_chunk_id": 138, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 138, "text": "### Padding side\n\nInputs need to be padded if they don't have the same length. But LLMs aren't trained to continue generation from padding tokens, which means the `padding_side()` parameter needs to be set to the left of the input.\n\n```py\nmodel_inputs = tokenizer(\n [\"1, 2, 3\", \"A, B, C, D, E\"], padding=True, return_tensors=\"pt\"\n).to(model.device)\ngenerated_ids = model.generate(**model_inputs)\ntokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]\n'1, 2, 33333333333'\n```\n\n```py\ntokenizer = AutoTokenizer.from_pretrained(\"mistralai/Mistral-7B-v0.1\", padding_side=\"left\")\ntokenizer.pad_token = tokenizer.eos_token\nmodel_inputs = tokenizer(\n [\"1, 2, 3\", \"A, B, C, D, E\"], padding=True, return_tensors=\"pt\"\n).to(model.device)\ngenerated_ids = model.generate(**model_inputs)\ntokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]\n'1, 2, 3, 4, 5, 6,'\n```", "source_file": "transformers/llm_tutorial.md", "section_heading": "Padding side", "char_start": 11808, "char_end": 12689, "token_estimate": 220, "prev_chunk_id": 137, "next_chunk_id": 139, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 139, "text": "### Prompt format\n\nSome models and tasks expect a certain input prompt format, and if the format is incorrect, the model returns a suboptimal output. You can learn more about prompting in the [prompt engineering](./tasks/prompting) guide.\n\nFor example, a chat model expects the input as a [chat template](./chat_templating). Your prompt should include a `role` and `content` to indicate who is participating in the conversation. If you try to pass your prompt as a single string, the model doesn't always return the expected output.\n\n```py\nfrom transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig\n\ntokenizer = AutoTokenizer.from_pretrained(\"HuggingFaceH4/zephyr-7b-alpha\")\nmodel = AutoModelForCausalLM.from_pretrained(\n \"HuggingFaceH4/zephyr-7b-alpha\", device_map=\"auto\", quantization_config=BitsAndBytesConfig(load_in_4bit=True)\n)\n```", "source_file": "transformers/llm_tutorial.md", "section_heading": "Prompt format", "char_start": 12691, "char_end": 13553, "token_estimate": 215, "prev_chunk_id": 138, "next_chunk_id": 140, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 140, "text": "```py\nprompt = \"\"\"How many cats does it take to change a light bulb? Reply as a pirate.\"\"\"\nmodel_inputs = tokenizer([prompt], return_tensors=\"pt\").to(model.device)\ninput_length = model_inputs.input_ids.shape[1]\ngenerated_ids = model.generate(**model_inputs, max_new_tokens=50)\nprint(tokenizer.batch_decode(generated_ids[:, input_length:], skip_special_tokens=True)[0])\n\"Aye, matey! 'Tis a simple task for a cat with a keen eye and nimble paws. First, the cat will climb up the ladder, carefully avoiding the rickety rungs. Then, with\"\n```", "source_file": "transformers/llm_tutorial.md", "section_heading": "Prompt format", "char_start": 13555, "char_end": 14093, "token_estimate": 134, "prev_chunk_id": 139, "next_chunk_id": 141, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 141, "text": "```py\nmessages = [\n {\n \"role\": \"system\",\n \"content\": \"You are a friendly chatbot who always responds in the style of a pirate\",\n },\n {\"role\": \"user\", \"content\": \"How many cats does it take to change a light bulb?\"},\n]\nmodel_inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors=\"pt\").to(model.device)\ninput_length = model_inputs.shape[1]\ngenerated_ids = model.generate(model_inputs, do_sample=True, max_new_tokens=50)\nprint(tokenizer.batch_decode(generated_ids[:, input_length:], skip_special_tokens=True)[0])\n\"Arr, matey! According to me beliefs, 'twas always one cat to hold the ladder and another to climb up it an\u2019 change the light bulb, but if yer looking to save some catnip, maybe yer can\n```", "source_file": "transformers/llm_tutorial.md", "section_heading": "Prompt format", "char_start": 14095, "char_end": 14855, "token_estimate": 190, "prev_chunk_id": 140, "next_chunk_id": 142, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 142, "text": "## Resources\n\nTake a look below for some more specific and specialized text generation libraries.\n\n- [Optimum](https://github.com/huggingface/optimum): an extension of Transformers focused on optimizing training and inference on specific hardware devices\n- [Outlines](https://github.com/dottxt-ai/outlines): a library for constrained text generation (generate JSON files for example).\n- [SynCode](https://github.com/uiuc-focal-lab/syncode): a library for context-free grammar guided generation (JSON, SQL, Python).\n- [Text Generation Inference](https://github.com/huggingface/text-generation-inference): a production-ready server for LLMs.\n- [Text generation web UI](https://github.com/oobabooga/text-generation-webui): a Gradio web UI for text generation.\n- [logits-processor-zoo](https://github.com/NVIDIA/logits-processor-zoo): additional logits processors for controlling text generation.", "source_file": "transformers/llm_tutorial.md", "section_heading": "Resources", "char_start": 14857, "char_end": 15749, "token_estimate": 223, "prev_chunk_id": 141, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/llm_tutorial", "doc_title": "Text generation" }, { "chunk_id": 143, "text": "# Generation strategies\n\nA decoding strategy informs how a model should select the next generated token. There are many types of decoding strategies, and choosing the appropriate one has a significant impact on the quality of the generated text.\n\nThis guide will help you understand the different decoding strategies available in Transformers and how and when to use them.", "source_file": "transformers/generation_strategies.md", "section_heading": "Generation strategies", "char_start": 0, "char_end": 372, "token_estimate": 93, "prev_chunk_id": null, "next_chunk_id": 144, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 144, "text": "## Basic decoding methods\n\nThese are well established decoding methods, and should be your starting point for text generation tasks.", "source_file": "transformers/generation_strategies.md", "section_heading": "Basic decoding methods", "char_start": 374, "char_end": 506, "token_estimate": 33, "prev_chunk_id": 143, "next_chunk_id": 145, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 145, "text": "### Greedy search\n\nGreedy search is the default decoding strategy. It selects the next most likely token at each step. Unless specified in [GenerationConfig](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig), this strategy generates a maximum of 20 new tokens.\n\nGreedy search works well for tasks with relatively short outputs where creativity is not a priority. However, it breaks down when generating longer sequences because it begins to repeat itself.\n\n```py\nimport torch\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nfrom accelerate import Accelerator\n\ndevice = Accelerator().device\n\ntokenizer = AutoTokenizer.from_pretrained(\"meta-llama/Llama-2-7b-hf\")\ninputs = tokenizer(\"Hugging Face is an open-source company\", return_tensors=\"pt\").to(device)\n\nmodel = AutoModelForCausalLM.from_pretrained(\"meta-llama/Llama-2-7b-hf\", dtype=torch.float16).to(device)", "source_file": "transformers/generation_strategies.md", "section_heading": "Greedy search", "char_start": 508, "char_end": 1419, "token_estimate": 227, "prev_chunk_id": 144, "next_chunk_id": 146, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 146, "text": "# explicitly set to default length because Llama2 generation length is 4096\noutputs = model.generate(**inputs, max_new_tokens=20)\ntokenizer.batch_decode(outputs, skip_special_tokens=True)\n'Hugging Face is an open-source company that provides a suite of tools and services for building, deploying, and maintaining natural language processing'\n```", "source_file": "transformers/generation_strategies.md", "section_heading": "explicitly set to default length because Llama2 generation length is 4096", "char_start": 1420, "char_end": 1765, "token_estimate": 86, "prev_chunk_id": 145, "next_chunk_id": 147, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 147, "text": "### Sampling\n\nSampling, or multinomial sampling, randomly selects a token based on the probability distribution over the entire model's vocabulary (as opposed to the most likely token, as in greedy search). This means every token with a non-zero probability has a chance to be selected. Sampling strategies reduce repetition and can generate more creative and diverse outputs.\n\nEnable multinomial sampling with `do_sample=True` and `num_beams=1`.\n\n```py\nimport torch\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nfrom accelerate import Accelerator\n\ndevice = Accelerator().device\n\ntokenizer = AutoTokenizer.from_pretrained(\"meta-llama/Llama-2-7b-hf\")\ninputs = tokenizer(\"Hugging Face is an open-source company\", return_tensors=\"pt\").to(device)\n\nmodel = AutoModelForCausalLM.from_pretrained(\"meta-llama/Llama-2-7b-hf\", dtype=torch.float16).to(device)", "source_file": "transformers/generation_strategies.md", "section_heading": "Sampling", "char_start": 1767, "char_end": 2630, "token_estimate": 215, "prev_chunk_id": 146, "next_chunk_id": 148, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 148, "text": "# explicitly set to 100 because Llama2 generation length is 4096\noutputs = model.generate(**inputs, max_new_tokens=50, do_sample=True, num_beams=1)\ntokenizer.batch_decode(outputs, skip_special_tokens=True)\n'Hugging Face is an open-source company \ud83e\udd17\\nWe are open-source and believe that open-source is the best way to build technology. Our mission is to make AI accessible to everyone, and we believe that open-source is the best way to achieve that.'\n```", "source_file": "transformers/generation_strategies.md", "section_heading": "explicitly set to 100 because Llama2 generation length is 4096", "char_start": 2631, "char_end": 3084, "token_estimate": 113, "prev_chunk_id": 147, "next_chunk_id": 149, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 149, "text": "### Beam search\n\nBeam search keeps track of several generated sequences (beams) at each time step. After a certain number of steps, it selects the sequence with the highest *overall* probability. Unlike greedy search, this strategy can \"look ahead\" and pick a sequence with a higher probability overall even if the initial tokens have a lower probability. It is best suited for input-grounded tasks, like describing an image or speech recognition. You can also use `do_sample=True` with beam search to sample at each step, but beam search will still greedily prune out low probability sequences between steps.\n\n> [!TIP]\n> Check out the [beam search visualizer](https://huggingface.co/spaces/m-ric/beam_search_visualizer) to see how beam search works.\n\nEnable beam search with the `num_beams` parameter (should be greater than 1 otherwise it's equivalent to greedy search).\n\n```py\nimport torch\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nfrom accelerate import Accelerator\n\ndevice = Accelerator().device", "source_file": "transformers/generation_strategies.md", "section_heading": "Beam search", "char_start": 3086, "char_end": 4105, "token_estimate": 254, "prev_chunk_id": 148, "next_chunk_id": 150, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 150, "text": "tokenizer = AutoTokenizer.from_pretrained(\"meta-llama/Llama-2-7b-hf\")\ninputs = tokenizer(\"Hugging Face is an open-source company\", return_tensors=\"pt\").to(device)\n\nmodel = AutoModelForCausalLM.from_pretrained(\"meta-llama/Llama-2-7b-hf\", dtype=torch.float16).to(device)", "source_file": "transformers/generation_strategies.md", "section_heading": "Beam search", "char_start": 1151, "char_end": 1419, "token_estimate": 67, "prev_chunk_id": 149, "next_chunk_id": 151, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 151, "text": "# explicitly set to 100 because Llama2 generation length is 4096\noutputs = model.generate(**inputs, max_new_tokens=50, num_beams=2)\ntokenizer.batch_decode(outputs, skip_special_tokens=True)\n\"['Hugging Face is an open-source company that develops and maintains the Hugging Face platform, which is a collection of tools and libraries for building and deploying natural language processing (NLP) models. Hugging Face was founded in 2018 by Thomas Wolf']\"\n```", "source_file": "transformers/generation_strategies.md", "section_heading": "explicitly set to 100 because Llama2 generation length is 4096", "char_start": 4376, "char_end": 4831, "token_estimate": 113, "prev_chunk_id": 150, "next_chunk_id": 152, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 152, "text": "## Custom generation methods\n\nCustom generation methods enable specialized behavior such as:\n\n- have the model continue thinking if it is uncertain;\n- roll back generation if the model gets stuck;\n- handle special tokens with custom logic;\n- use specialized KV caches;\n\nWe enable custom generation methods through model repositories, assuming a specific model tag and file structure (see subsection below). This feature is an extension of [custom modeling code](./models#custom-models) and, like such, requires setting `trust_remote_code=True`.\n\nIf a model repository holds a custom generation method, the easiest way to try it out is to load the model and generate with it:\n\n```py\nfrom transformers import AutoModelForCausalLM, AutoTokenizer", "source_file": "transformers/generation_strategies.md", "section_heading": "Custom generation methods", "char_start": 4833, "char_end": 5575, "token_estimate": 185, "prev_chunk_id": 151, "next_chunk_id": 153, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 153, "text": "# `transformers-community/custom_generate_example` holds a copy of `Qwen/Qwen2.5-0.5B-Instruct`, but", "source_file": "transformers/generation_strategies.md", "section_heading": "`transformers-community/custom_generate_example` holds a copy of `Qwen/Qwen2.5-0.5B-Instruct`, but", "char_start": 5577, "char_end": 5677, "token_estimate": 25, "prev_chunk_id": 152, "next_chunk_id": 154, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 154, "text": "# with custom generation code -> calling `generate` uses the custom generation method!\ntokenizer = AutoTokenizer.from_pretrained(\"transformers-community/custom_generate_example\")\nmodel = AutoModelForCausalLM.from_pretrained(\n \"transformers-community/custom_generate_example\", device_map=\"auto\", trust_remote_code=True\n)\n\ninputs = tokenizer([\"The quick brown\"], return_tensors=\"pt\").to(model.device)", "source_file": "transformers/generation_strategies.md", "section_heading": "with custom generation code -> calling `generate` uses the custom generation method!", "char_start": 5678, "char_end": 6079, "token_estimate": 100, "prev_chunk_id": 153, "next_chunk_id": 155, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 155, "text": "# The custom generation method is a minimal greedy decoding implementation. It also prints a custom message at run time.\ngen_out = model.generate(**inputs)", "source_file": "transformers/generation_strategies.md", "section_heading": "The custom generation method is a minimal greedy decoding implementation. It also prints a custom message at run time.", "char_start": 6080, "char_end": 6235, "token_estimate": 38, "prev_chunk_id": 154, "next_chunk_id": 156, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 156, "text": "# you should now see its custom message, \"\u2728 using a custom generation method \u2728\"\nprint(tokenizer.batch_decode(gen_out, skip_special_tokens=True))\n'The quick brown fox jumps over a lazy dog, and the dog is a type of animal. Is'\n```\n\nModel repositories with custom generation methods have a special property: their generation method can be loaded from **any** model through [generate()](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationMixin.generate)'s `custom_generate` argument. This means anyone can create and share their custom generation method to potentially work with any Transformers model, without requiring users to install additional Python packages.\n\n```py\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\ntokenizer = AutoTokenizer.from_pretrained(\"Qwen/Qwen2.5-0.5B-Instruct\")\nmodel = AutoModelForCausalLM.from_pretrained(\"Qwen/Qwen2.5-0.5B-Instruct\", device_map=\"auto\")\n\ninputs = tokenizer([\"The quick brown\"], return_tensors=\"pt\").to(model.device)", "source_file": "transformers/generation_strategies.md", "section_heading": "you should now see its custom message, \"\u2728 using a custom generation method \u2728\"", "char_start": 6236, "char_end": 7242, "token_estimate": 251, "prev_chunk_id": 155, "next_chunk_id": 157, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 157, "text": "# `custom_generate` replaces the original `generate` by the custom generation method defined in", "source_file": "transformers/generation_strategies.md", "section_heading": "`custom_generate` replaces the original `generate` by the custom generation method defined in", "char_start": 7243, "char_end": 7338, "token_estimate": 23, "prev_chunk_id": 156, "next_chunk_id": 158, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 158, "text": "# `transformers-community/custom_generate_example`\ngen_out = model.generate(**inputs, custom_generate=\"transformers-community/custom_generate_example\", trust_remote_code=True)\nprint(tokenizer.batch_decode(gen_out, skip_special_tokens=True)[0])\n'The quick brown fox jumps over a lazy dog, and the dog is a type of animal. Is'\n```\n\nYou should read the `README.md` file of the repository containing the custom generation strategy to see what the new arguments and output type differences are, if they exist. Otherwise, you can assume it works like the base [generate()](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationMixin.generate) method.\n\n> [!TIP]\n> You can find all custom generation methods by [searching for their custom tag.](https://huggingface.co/models?other=custom_generate), `custom_generate`.\n\nConsider the Hub repository [transformers-community/custom_generate_example](https://huggingface.co/transformers-community/custom_generate_example) as an example. The `README.md` states that it has an additional input argument, `left_padding`, which adds a number of padding tokens before the prompt.\n\n```py\ngen_out = model.generate(\n **inputs, custom_generate=\"transformers-community/custom_generate_example\", trust_remote_code=True, left_padding=5\n)\nprint(tokenizer.batch_decode(gen_out)[0])\n'The quick brown fox jumps over the lazy dog.\\n\\nThe sentence \"The quick'\n```\n\nIf the custom method has pinned Python requirements that your environment doesn't meet, you'll get an exception about missing requirements. For instance, [transformers-community/custom_generate_bad_requirements](https://huggingface.co/transformers-community/custom_generate_bad_requirements) has an impossible set of requirements defined in its `custom_generate/requirements.txt` file, and you'll see the error message below if you try to run it.\n\n```text\nImportError: Missing requirements in your local environment for `transformers-community/custom_generate_bad_requirements`:\nfoo (installed: None)\nbar==0.0.0 (installed: None)\ntorch>=99.0 (installed: 2.6.0)\n```", "source_file": "transformers/generation_strategies.md", "section_heading": "`transformers-community/custom_generate_example`", "char_start": 7339, "char_end": 9417, "token_estimate": 519, "prev_chunk_id": 157, "next_chunk_id": 159, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 159, "text": "Updating your Python requirements accordingly will remove this error message.", "source_file": "transformers/generation_strategies.md", "section_heading": "`transformers-community/custom_generate_example`", "char_start": 9419, "char_end": 9496, "token_estimate": 19, "prev_chunk_id": 158, "next_chunk_id": 160, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 160, "text": "### Creating a custom generation method\n\nTo create a new generation method, you need to create a new [**Model**](https://huggingface.co/new) repository and push a few files into it.\n\n1. The model you've designed your generation method with.\n2. `custom_generate/generate.py`, which contains all the logic for your custom generation method.\n3. `custom_generate/requirements.txt`, used to optionally add new Python requirements and/or lock specific versions to correctly use your method.\n4. `README.md`, where you should add the `custom_generate` tag and document any new arguments or output type differences of your custom method here.\n\nAfter you've added all required files, your repository should look like this\n\n```text\nyour_repo/\n\u251c\u2500\u2500 README.md # include the 'custom_generate' tag\n\u251c\u2500\u2500 config.json\n\u251c\u2500\u2500 ...\n\u2514\u2500\u2500 custom_generate/\n \u251c\u2500\u2500 generate.py\n \u2514\u2500\u2500 requirements.txt\n```", "source_file": "transformers/generation_strategies.md", "section_heading": "Creating a custom generation method", "char_start": 9498, "char_end": 10382, "token_estimate": 221, "prev_chunk_id": 159, "next_chunk_id": 161, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 161, "text": "#### Adding the base model\n\nThe starting point for your custom generation method is a model repository just like any other. The model to add to this repository should be the model you've designed your method with, and it is meant to be part of a working self-contained model-generate pair. When the model in this repository is loaded, your custom generation method will override `generate`. Don't worry -- your generation method can still be loaded with any other Transformers model, as explained in the section above.\n\nIf you simply want to copy an existing model, you can do\n\n```py\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\ntokenizer = AutoTokenizer.from_pretrained(\"source/model_repo\")\nmodel = AutoModelForCausalLM.from_pretrained(\"source/model_repo\")\ntokenizer.save_pretrained(\"your/generation_method\", push_to_hub=True)\nmodel.save_pretrained(\"your/generation_method\", push_to_hub=True)\n```", "source_file": "transformers/generation_strategies.md", "section_heading": "Adding the base model", "char_start": 10384, "char_end": 11298, "token_estimate": 228, "prev_chunk_id": 160, "next_chunk_id": 162, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 162, "text": "#### generate.py\n\nThis is the core of your generation method. It *must* contain a method named `generate`, and this method *must* contain a `model` argument as its first argument. `model` is the model instance, which means you have access to all attributes and methods in the model, including the ones defined in [GenerationMixin](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationMixin) (like the base `generate` method).\n\n> [!WARNING]\n> `generate.py` must be placed in a folder named `custom_generate`, and not at the root level of the repository. The file paths for this feature are hardcoded.", "source_file": "transformers/generation_strategies.md", "section_heading": "generate.py", "char_start": 11300, "char_end": 11927, "token_estimate": 156, "prev_chunk_id": 161, "next_chunk_id": 163, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 163, "text": "Under the hood, when the base [generate()](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationMixin.generate) method is called with a `custom_generate` argument, it first checks its Python requirements (if any), then locates the custom `generate` method in `generate.py`, and finally calls the custom `generate`. All received arguments and `model` are forwarded to your custom `generate` method, with the exception of the arguments used to trigger the custom generation (`trust_remote_code` and `custom_generate`).\n\nThis means your `generate` can have a mix of original and custom arguments (as well as a different output type) as shown below.\n\n```py\nimport torch\n\ndef generate(model, input_ids, generation_config=None, left_padding=None, **kwargs):\n generation_config = generation_config or model.generation_config # default to the model generation config\n cur_length = input_ids.shape[1]\n max_length = generation_config.max_length or cur_length + generation_config.max_new_tokens", "source_file": "transformers/generation_strategies.md", "section_heading": "generate.py", "char_start": 11929, "char_end": 12950, "token_estimate": 255, "prev_chunk_id": 162, "next_chunk_id": 164, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 164, "text": "# Example of custom argument: add `left_padding` (integer) pad tokens before the prompt\n if left_padding is not None:\n if not isinstance(left_padding, int) or left_padding [!TIP]\n> If you publish a `custom_generate` repository, your `generate` implementation can itself define a callable and pass it to `model.generate()`. This lets you customize the decoding loop while still benefiting from Transformers' built-in input preparation logic.", "source_file": "transformers/generation_strategies.md", "section_heading": "generate.py", "char_start": 12956, "char_end": 13407, "token_estimate": 113, "prev_chunk_id": 163, "next_chunk_id": 165, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 165, "text": "### Finding custom generation methods\n\nYou can find all custom generation methods by [searching for their custom tag.](https://huggingface.co/models?other=custom_generate), `custom_generate`. In addition to the tag, we curate two collections of `custom_generate` methods:\n\n- [Custom generation methods - Community](https://huggingface.co/collections/transformers-community/custom-generation-methods-community-6888fb1da0efbc592d3a8ab6) -- a collection of powerful methods contributed by the community;\n- [Custom generation methods - Tutorials](https://huggingface.co/collections/transformers-community/custom-generation-methods-tutorials-6823589657a94940ea02cfec) -- a collection of reference implementations for methods that previously were part of `transformers`, as well as tutorials for `custom_generate`.", "source_file": "transformers/generation_strategies.md", "section_heading": "Finding custom generation methods", "char_start": 13409, "char_end": 14217, "token_estimate": 202, "prev_chunk_id": 164, "next_chunk_id": 166, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 166, "text": "## Resources\n\nRead the [How to generate text: using different decoding methods for language generation with Transformers](https://huggingface.co/blog/how-to-generate) blog post for an explanation of how common decoding strategies work.", "source_file": "transformers/generation_strategies.md", "section_heading": "Resources", "char_start": 14219, "char_end": 14454, "token_estimate": 58, "prev_chunk_id": 165, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/generation_strategies", "doc_title": "Generation strategies" }, { "chunk_id": 167, "text": "# Text classification\n\nText classification is a common NLP task that assigns a label or class to text. Some of the largest companies run text classification in production for a wide range of practical applications. One of the most popular forms of text classification is sentiment analysis, which assigns a label like \ud83d\ude42 positive, \ud83d\ude41 negative, or \ud83d\ude10 neutral to a sequence of text.\n\nThis guide will show you how to:\n\n1. Finetune [DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased) on the [IMDb](https://huggingface.co/datasets/imdb) dataset to determine whether a movie review is positive or negative.\n2. Use your finetuned model for inference.\n\nTo see all architectures and checkpoints compatible with this task, we recommend checking the [task-page](https://huggingface.co/tasks/text-classification).\n\nBefore you begin, make sure you have all the necessary libraries installed:\n\n```bash\npip install transformers datasets evaluate accelerate\n```", "source_file": "transformers/tasks/sequence_classification.md", "section_heading": "Text classification", "char_start": 0, "char_end": 962, "token_estimate": 240, "prev_chunk_id": null, "next_chunk_id": 168, "url": "https://huggingface.co/docs/transformers/tasks/sequence_classification", "doc_title": "Text classification" }, { "chunk_id": 168, "text": "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:\n\n```py\n>>> from huggingface_hub import notebook_login\n\n>>> notebook_login()\n```", "source_file": "transformers/tasks/sequence_classification.md", "section_heading": "Text classification", "char_start": 964, "char_end": 1199, "token_estimate": 58, "prev_chunk_id": 167, "next_chunk_id": 169, "url": "https://huggingface.co/docs/transformers/tasks/sequence_classification", "doc_title": "Text classification" }, { "chunk_id": 169, "text": "## Load IMDb dataset\n\nStart by loading the IMDb dataset from the \ud83e\udd17 Datasets library:\n\n```py\n>>> from datasets import load_dataset\n\n>>> imdb = load_dataset(\"imdb\")\n```\n\nThen take a look at an example:", "source_file": "transformers/tasks/sequence_classification.md", "section_heading": "Load IMDb dataset", "char_start": 1201, "char_end": 1400, "token_estimate": 49, "prev_chunk_id": 168, "next_chunk_id": 170, "url": "https://huggingface.co/docs/transformers/tasks/sequence_classification", "doc_title": "Text classification" }, { "chunk_id": 170, "text": "```py\n>>> imdb[\"test\"][0]\n{\n \"label\": 0,\n \"text\": \"I love sci-fi and am willing to put up with a lot. Sci-fi movies/TV are usually underfunded, under-appreciated and misunderstood. I tried to like this, I really did, but it is to good TV sci-fi as Babylon 5 is to Star Trek (the original). Silly prosthetics, cheap cardboard sets, stilted dialogues, CG that doesn't match the background, and painfully one-dimensional characters cannot be overcome with a 'sci-fi' setting. (I'm sure there are those of you out there who think Babylon 5 is good sci-fi TV. It's not. It's clich\u00e9d and uninspiring.) While US viewers might like emotion and character development, sci-fi is a genre that does not take itself seriously (cf. Star Trek). It may treat important issues, yet not as a serious philosophy. It's really difficult to care about the characters here as they are not simply foolish, just missing a spark of life. Their actions and reactions are wooden and predictable, often painful to watch. The makers of Earth KNOW it's rubbish as they have to always say \\\"Gene Roddenberry's Earth...\\\" otherwise people would not continue watching. Roddenberry's ashes must be turning in their orbit as this dull, cheap, poorly edited (watching it without advert breaks really brings this home) trudging Trabant of a show lumbers into space. Spoiler. So, kill off a main character. And then bring him back as another actor. Jeeez! Dallas all over again.\",\n}\n```", "source_file": "transformers/tasks/sequence_classification.md", "section_heading": "Load IMDb dataset", "char_start": 1402, "char_end": 2855, "token_estimate": 363, "prev_chunk_id": 169, "next_chunk_id": 171, "url": "https://huggingface.co/docs/transformers/tasks/sequence_classification", "doc_title": "Text classification" }, { "chunk_id": 171, "text": "There are two fields in this dataset:\n\n- `text`: the movie review text.\n- `label`: a value that is either `0` for a negative review or `1` for a positive review.", "source_file": "transformers/tasks/sequence_classification.md", "section_heading": "Load IMDb dataset", "char_start": 2857, "char_end": 3018, "token_estimate": 40, "prev_chunk_id": 170, "next_chunk_id": 172, "url": "https://huggingface.co/docs/transformers/tasks/sequence_classification", "doc_title": "Text classification" }, { "chunk_id": 172, "text": "## Preprocess\n\nThe next step is to load a DistilBERT tokenizer to preprocess the `text` field:\n\n```py\n>>> from transformers import AutoTokenizer\n\n>>> tokenizer = AutoTokenizer.from_pretrained(\"distilbert/distilbert-base-uncased\")\n```\n\nCreate a preprocessing function to tokenize `text` and truncate sequences to be no longer than DistilBERT's maximum input length:\n\n```py\n>>> def preprocess_function(examples):\n... return tokenizer(examples[\"text\"], truncation=True)\n```\n\nTo apply the preprocessing function over the entire dataset, use \ud83e\udd17 Datasets [map](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) function. You can speed up `map` by setting `batched=True` to process multiple elements of the dataset at once:\n\n```py\ntokenized_imdb = imdb.map(preprocess_function, batched=True)\n```", "source_file": "transformers/tasks/sequence_classification.md", "section_heading": "Preprocess", "char_start": 3020, "char_end": 3861, "token_estimate": 210, "prev_chunk_id": 171, "next_chunk_id": 173, "url": "https://huggingface.co/docs/transformers/tasks/sequence_classification", "doc_title": "Text classification" }, { "chunk_id": 173, "text": "Now create a batch of examples using [DataCollatorWithPadding](/docs/transformers/v5.6.2/en/main_classes/data_collator#transformers.DataCollatorWithPadding). It's more efficient to *dynamically pad* the sentences to the longest length in a batch during collation, instead of padding the whole dataset to the maximum length.\n\n```py\n>>> from transformers import DataCollatorWithPadding\n\n>>> data_collator = DataCollatorWithPadding(tokenizer=tokenizer)\n```", "source_file": "transformers/tasks/sequence_classification.md", "section_heading": "Preprocess", "char_start": 3863, "char_end": 4316, "token_estimate": 113, "prev_chunk_id": 172, "next_chunk_id": 174, "url": "https://huggingface.co/docs/transformers/tasks/sequence_classification", "doc_title": "Text classification" }, { "chunk_id": 174, "text": "## Evaluate\n\nIncluding a metric during training is often helpful for evaluating your model's performance. You can quickly load a evaluation method with the \ud83e\udd17 [Evaluate](https://huggingface.co/docs/evaluate/index) library. For this task, load the [accuracy](https://huggingface.co/spaces/evaluate-metric/accuracy) metric (see the \ud83e\udd17 Evaluate [quick tour](https://huggingface.co/docs/evaluate/a_quick_tour) to learn more about how to load and compute a metric):\n\n```py\n>>> import evaluate\n\n>>> accuracy = evaluate.load(\"accuracy\")\n```\n\nThen create a function that passes your predictions and labels to [compute](https://huggingface.co/docs/evaluate/v0.4.6/en/package_reference/main_classes#evaluate.EvaluationModule.compute) to calculate the accuracy:\n\n```py\n>>> import numpy as np\n\n>>> def compute_metrics(eval_pred):\n... predictions, labels = eval_pred\n... predictions = np.argmax(predictions, axis=1)\n... return accuracy.compute(predictions=predictions, references=labels)\n```", "source_file": "transformers/tasks/sequence_classification.md", "section_heading": "Evaluate", "char_start": 4318, "char_end": 5306, "token_estimate": 247, "prev_chunk_id": 173, "next_chunk_id": 175, "url": "https://huggingface.co/docs/transformers/tasks/sequence_classification", "doc_title": "Text classification" }, { "chunk_id": 175, "text": "Your `compute_metrics` function is ready to go now, and you'll return to it when you setup your training.", "source_file": "transformers/tasks/sequence_classification.md", "section_heading": "Evaluate", "char_start": 5308, "char_end": 5413, "token_estimate": 26, "prev_chunk_id": 174, "next_chunk_id": 176, "url": "https://huggingface.co/docs/transformers/tasks/sequence_classification", "doc_title": "Text classification" }, { "chunk_id": 176, "text": "## Train\n\nBefore you start training your model, create a map of the expected ids to their labels with `id2label` and `label2id`:\n\n```py\n>>> id2label = {0: \"NEGATIVE\", 1: \"POSITIVE\"}\n>>> label2id = {\"NEGATIVE\": 0, \"POSITIVE\": 1}\n```\n\nIf you aren't familiar with finetuning a model with the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer), take a look at the basic tutorial [here](../training#train-with-pytorch-trainer)!\n\nYou're ready to start training your model now! Load DistilBERT with [AutoModelForSequenceClassification](/docs/transformers/v5.6.2/en/model_doc/auto#transformers.AutoModelForSequenceClassification) along with the number of expected labels, and the label mappings:\n\n```py\n>>> from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer\n\n>>> model = AutoModelForSequenceClassification.from_pretrained(\n... \"distilbert/distilbert-base-uncased\", num_labels=2, id2label=id2label, label2id=label2id\n... )\n```", "source_file": "transformers/tasks/sequence_classification.md", "section_heading": "Train", "char_start": 5415, "char_end": 6404, "token_estimate": 247, "prev_chunk_id": 175, "next_chunk_id": 177, "url": "https://huggingface.co/docs/transformers/tasks/sequence_classification", "doc_title": "Text classification" }, { "chunk_id": 177, "text": "At this point, only three steps remain:\n\n1. Define your training hyperparameters in [TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments). The only required parameter is `output_dir` which specifies where to save your model. You'll push this model to the Hub by setting `push_to_hub=True` (you need to be signed in to Hugging Face to upload your model). At the end of each epoch, the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) will evaluate the accuracy and save the training checkpoint.\n2. Pass the training arguments to [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) along with the model, dataset, tokenizer, data collator, and `compute_metrics` function.\n3. Call [train()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.train) to finetune your model.", "source_file": "transformers/tasks/sequence_classification.md", "section_heading": "Train", "char_start": 6406, "char_end": 7305, "token_estimate": 224, "prev_chunk_id": 176, "next_chunk_id": 178, "url": "https://huggingface.co/docs/transformers/tasks/sequence_classification", "doc_title": "Text classification" }, { "chunk_id": 178, "text": "```py\n>>> training_args = TrainingArguments(\n... output_dir=\"my_awesome_model\",\n... learning_rate=2e-5,\n... per_device_train_batch_size=16,\n... per_device_eval_batch_size=16,\n... num_train_epochs=2,\n... weight_decay=0.01,\n... eval_strategy=\"epoch\",\n... save_strategy=\"epoch\",\n... load_best_model_at_end=True,\n... push_to_hub=True,\n... )\n\n>>> trainer = Trainer(\n... model=model,\n... args=training_args,\n... train_dataset=tokenized_imdb[\"train\"],\n... eval_dataset=tokenized_imdb[\"test\"],\n... processing_class=tokenizer,\n... data_collator=data_collator,\n... compute_metrics=compute_metrics,\n... )\n\n>>> trainer.train()\n```\n\n[Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) applies dynamic padding by default when you pass `tokenizer` to it. In this case, you don't need to specify a data collator explicitly.", "source_file": "transformers/tasks/sequence_classification.md", "section_heading": "Train", "char_start": 7307, "char_end": 8212, "token_estimate": 226, "prev_chunk_id": 177, "next_chunk_id": 179, "url": "https://huggingface.co/docs/transformers/tasks/sequence_classification", "doc_title": "Text classification" }, { "chunk_id": 179, "text": "Once training is completed, share your model to the Hub with the [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.push_to_hub) method so everyone can use your model:\n\n```py\n>>> trainer.push_to_hub()\n```\n\nFor a more in-depth example of how to finetune a model for text classification, take a look at the corresponding\n[PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification.ipynb).", "source_file": "transformers/tasks/sequence_classification.md", "section_heading": "Train", "char_start": 8214, "char_end": 8697, "token_estimate": 120, "prev_chunk_id": 178, "next_chunk_id": 180, "url": "https://huggingface.co/docs/transformers/tasks/sequence_classification", "doc_title": "Text classification" }, { "chunk_id": 180, "text": "## Inference\n\nGreat, now that you've finetuned a model, you can use it for inference!\n\nGrab some text you'd like to run inference on:\n\n```py\n>>> text = \"This was a masterpiece. Not completely faithful to the books, but enthralling from beginning to end. Might be my favorite of the three.\"\n```\n\nThe simplest way to try out your finetuned model for inference is to use it in a [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline). Instantiate a `pipeline` for sentiment analysis with your model, and pass your text to it:\n\n```py\n>>> from transformers import pipeline\n\n>>> classifier = pipeline(\"sentiment-analysis\", model=\"stevhliu/my_awesome_model\")\n>>> classifier(text)\n[{'label': 'POSITIVE', 'score': 0.9994940757751465}]\n```\n\nYou can also manually replicate the results of the `pipeline` if you'd like:\n\nTokenize the text and return PyTorch tensors:", "source_file": "transformers/tasks/sequence_classification.md", "section_heading": "Inference", "char_start": 8699, "char_end": 9586, "token_estimate": 221, "prev_chunk_id": 179, "next_chunk_id": 181, "url": "https://huggingface.co/docs/transformers/tasks/sequence_classification", "doc_title": "Text classification" }, { "chunk_id": 181, "text": "```py\n>>> from transformers import AutoTokenizer\n\n>>> tokenizer = AutoTokenizer.from_pretrained(\"stevhliu/my_awesome_model\")\n>>> inputs = tokenizer(text, return_tensors=\"pt\")\n```\n\nPass your inputs to the model and return the `logits`:\n\n```py\n>>> from transformers import AutoModelForSequenceClassification\n\n>>> model = AutoModelForSequenceClassification.from_pretrained(\"stevhliu/my_awesome_model\")\n>>> with torch.no_grad():\n... logits = model(**inputs).logits\n```\n\nGet the class with the highest probability, and use the model's `id2label` mapping to convert it to a text label:\n\n```py\n>>> predicted_class_id = logits.argmax().item()\n>>> model.config.id2label[predicted_class_id]\n'POSITIVE'\n```", "source_file": "transformers/tasks/sequence_classification.md", "section_heading": "Inference", "char_start": 9588, "char_end": 10287, "token_estimate": 174, "prev_chunk_id": 180, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/tasks/sequence_classification", "doc_title": "Text classification" }, { "chunk_id": 182, "text": "# Token classification\n\nToken classification assigns a label to individual tokens in a sentence. One of the most common token classification tasks is Named Entity Recognition (NER). NER attempts to find a label for each entity in a sentence, such as a person, location, or organization.\n\nThis guide will show you how to:\n\n1. Finetune [DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased) on the [WNUT 17](https://huggingface.co/datasets/wnut_17) dataset to detect new entities.\n2. Use your finetuned model for inference.\n\nTo see all architectures and checkpoints compatible with this task, we recommend checking the [task-page](https://huggingface.co/tasks/token-classification).\n\nBefore you begin, make sure you have all the necessary libraries installed:\n\n```bash\npip install transformers datasets evaluate seqeval\n```\n\nWe 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:", "source_file": "transformers/tasks/token_classification.md", "section_heading": "Token classification", "char_start": 0, "char_end": 995, "token_estimate": 248, "prev_chunk_id": null, "next_chunk_id": 183, "url": "https://huggingface.co/docs/transformers/tasks/token_classification", "doc_title": "Token classification" }, { "chunk_id": 183, "text": "```py\n>>> from huggingface_hub import notebook_login\n\n>>> notebook_login()\n```", "source_file": "transformers/tasks/token_classification.md", "section_heading": "Token classification", "char_start": 997, "char_end": 1075, "token_estimate": 19, "prev_chunk_id": 182, "next_chunk_id": 184, "url": "https://huggingface.co/docs/transformers/tasks/token_classification", "doc_title": "Token classification" }, { "chunk_id": 184, "text": "## Load WNUT 17 dataset\n\nStart by loading the WNUT 17 dataset from the \ud83e\udd17 Datasets library:\n\n```py\n>>> from datasets import load_dataset\n\n>>> wnut = load_dataset(\"wnut_17\")\n```\n\nThen take a look at an example:\n\n```py\n>>> wnut[\"train\"][0]\n{'id': '0',\n 'ner_tags': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0],\n 'tokens': ['@paulwalk', 'It', \"'s\", 'the', 'view', 'from', 'where', 'I', \"'m\", 'living', 'for', 'two', 'weeks', '.', 'Empire', 'State', 'Building', '=', 'ESB', '.', 'Pretty', 'bad', 'storm', 'here', 'last', 'evening', '.']\n}\n```\n\nEach number in `ner_tags` represents an entity. Convert the numbers to their label names to find out what the entities are:\n\n```py\n>>> label_list = wnut[\"train\"].features[f\"ner_tags\"].feature.names\n>>> label_list\n[\n \"O\",\n \"B-corporation\",\n \"I-corporation\",\n \"B-creative-work\",\n \"I-creative-work\",\n \"B-group\",\n \"I-group\",\n \"B-location\",\n \"I-location\",\n \"B-person\",\n \"I-person\",\n \"B-product\",\n \"I-product\",\n]\n```", "source_file": "transformers/tasks/token_classification.md", "section_heading": "Load WNUT 17 dataset", "char_start": 1077, "char_end": 2102, "token_estimate": 256, "prev_chunk_id": 183, "next_chunk_id": 185, "url": "https://huggingface.co/docs/transformers/tasks/token_classification", "doc_title": "Token classification" }, { "chunk_id": 185, "text": "The letter that prefixes each `ner_tag` indicates the token position of the entity:\n\n- `B-` indicates the beginning of an entity.\n- `I-` indicates a token is contained inside the same entity (for example, the `State` token is a part of an entity like\n `Empire State Building`).\n- `0` indicates the token doesn't correspond to any entity.", "source_file": "transformers/tasks/token_classification.md", "section_heading": "Load WNUT 17 dataset", "char_start": 2104, "char_end": 2442, "token_estimate": 84, "prev_chunk_id": 184, "next_chunk_id": 186, "url": "https://huggingface.co/docs/transformers/tasks/token_classification", "doc_title": "Token classification" }, { "chunk_id": 186, "text": "## Preprocess\n\nThe next step is to load a DistilBERT tokenizer to preprocess the `tokens` field:\n\n```py\n>>> from transformers import AutoTokenizer\n\n>>> tokenizer = AutoTokenizer.from_pretrained(\"distilbert/distilbert-base-uncased\")\n```\n\nAs you saw in the example `tokens` field above, it looks like the input has already been tokenized. But the input actually hasn't been tokenized yet and you'll need to set `is_split_into_words=True` to tokenize the words into subwords. For example:\n\n```py\n>>> example = wnut[\"train\"][0]\n>>> tokenized_input = tokenizer(example[\"tokens\"], is_split_into_words=True)\n>>> tokens = tokenizer.convert_ids_to_tokens(tokenized_input[\"input_ids\"])\n>>> tokens\n['[CLS]', '@', 'paul', '##walk', 'it', \"'\", 's', 'the', 'view', 'from', 'where', 'i', \"'\", 'm', 'living', 'for', 'two', 'weeks', '.', 'empire', 'state', 'building', '=', 'es', '##b', '.', 'pretty', 'bad', 'storm', 'here', 'last', 'evening', '.', '[SEP]']\n```", "source_file": "transformers/tasks/token_classification.md", "section_heading": "Preprocess", "char_start": 2444, "char_end": 3389, "token_estimate": 236, "prev_chunk_id": 185, "next_chunk_id": 187, "url": "https://huggingface.co/docs/transformers/tasks/token_classification", "doc_title": "Token classification" }, { "chunk_id": 187, "text": "However, this adds some special tokens `[CLS]` and `[SEP]` and the subword tokenization creates a mismatch between the input and labels. A single word corresponding to a single label may now be split into two subwords. You'll need to realign the tokens and labels by:\n\n1. Mapping all tokens to their corresponding word with the [`word_ids`](https://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.BatchEncoding.word_ids) method.\n2. Assigning the label `-100` to the special tokens `[CLS]` and `[SEP]` so they're ignored by the PyTorch loss function (see [CrossEntropyLoss](https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html)).\n3. Only labeling the first token of a given word. Assign `-100` to other subtokens from the same word.\n\nHere is how you can create a function to realign the tokens and labels, and truncate sequences to be no longer than DistilBERT's maximum input length:", "source_file": "transformers/tasks/token_classification.md", "section_heading": "Preprocess", "char_start": 3391, "char_end": 4315, "token_estimate": 231, "prev_chunk_id": 186, "next_chunk_id": 188, "url": "https://huggingface.co/docs/transformers/tasks/token_classification", "doc_title": "Token classification" }, { "chunk_id": 188, "text": "```py\n>>> def tokenize_and_align_labels(examples):\n... tokenized_inputs = tokenizer(examples[\"tokens\"], truncation=True, is_split_into_words=True)\n\n... labels = []\n... for i, label in enumerate(examples[f\"ner_tags\"]):\n... word_ids = tokenized_inputs.word_ids(batch_index=i) # Map tokens to their respective word.\n... previous_word_idx = None\n... label_ids = []\n... for word_idx in word_ids: # Set the special tokens to -100.\n... if word_idx is None:\n... label_ids.append(-100)\n... elif word_idx != previous_word_idx: # Only label the first token of a given word.\n... label_ids.append(label[word_idx])\n... else:\n... label_ids.append(-100)\n... previous_word_idx = word_idx\n... labels.append(label_ids)\n\n... tokenized_inputs[\"labels\"] = labels\n... return tokenized_inputs\n```", "source_file": "transformers/tasks/token_classification.md", "section_heading": "Preprocess", "char_start": 4317, "char_end": 5248, "token_estimate": 232, "prev_chunk_id": 187, "next_chunk_id": 189, "url": "https://huggingface.co/docs/transformers/tasks/token_classification", "doc_title": "Token classification" }, { "chunk_id": 189, "text": "To apply the preprocessing function over the entire dataset, use \ud83e\udd17 Datasets [map](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) function. You can speed up the `map` function by setting `batched=True` to process multiple elements of the dataset at once:\n\n```py\n>>> tokenized_wnut = wnut.map(tokenize_and_align_labels, batched=True)\n```\n\nNow create a batch of examples using [DataCollatorWithPadding](/docs/transformers/v5.6.2/en/main_classes/data_collator#transformers.DataCollatorWithPadding). It's more efficient to *dynamically pad* the sentences to the longest length in a batch during collation, instead of padding the whole dataset to the maximum length.\n\n```py\n>>> from transformers import DataCollatorForTokenClassification\n\n>>> data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer)\n```", "source_file": "transformers/tasks/token_classification.md", "section_heading": "Preprocess", "char_start": 5250, "char_end": 6115, "token_estimate": 216, "prev_chunk_id": 188, "next_chunk_id": 190, "url": "https://huggingface.co/docs/transformers/tasks/token_classification", "doc_title": "Token classification" }, { "chunk_id": 190, "text": "## Evaluate\n\nIncluding a metric during training is often helpful for evaluating your model's performance. You can quickly load a evaluation method with the \ud83e\udd17 [Evaluate](https://huggingface.co/docs/evaluate/index) library. For this task, load the [seqeval](https://huggingface.co/spaces/evaluate-metric/seqeval) framework (see the \ud83e\udd17 Evaluate [quick tour](https://huggingface.co/docs/evaluate/a_quick_tour) to learn more about how to load and compute a metric). Seqeval actually produces several scores: precision, recall, F1, and accuracy.\n\n```py\n>>> import evaluate\n\n>>> seqeval = evaluate.load(\"seqeval\")\n```\n\nGet the NER labels first, and then create a function that passes your true predictions and true labels to [compute](https://huggingface.co/docs/evaluate/v0.4.6/en/package_reference/main_classes#evaluate.EvaluationModule.compute) to calculate the scores:", "source_file": "transformers/tasks/token_classification.md", "section_heading": "Evaluate", "char_start": 6117, "char_end": 6981, "token_estimate": 216, "prev_chunk_id": 189, "next_chunk_id": 191, "url": "https://huggingface.co/docs/transformers/tasks/token_classification", "doc_title": "Token classification" }, { "chunk_id": 191, "text": "```py\n>>> import numpy as np\n\n>>> labels = [label_list[i] for i in example[f\"ner_tags\"]]\n\n>>> def compute_metrics(p):\n... predictions, labels = p\n... predictions = np.argmax(predictions, axis=2)\n\n... true_predictions = [\n... [label_list[p] for (p, l) in zip(prediction, label) if l != -100]\n... for prediction, label in zip(predictions, labels)\n... ]\n... true_labels = [\n... [label_list[l] for (p, l) in zip(prediction, label) if l != -100]\n... for prediction, label in zip(predictions, labels)\n... ]\n\n... results = seqeval.compute(predictions=true_predictions, references=true_labels)\n... return {\n... \"precision\": results[\"overall_precision\"],\n... \"recall\": results[\"overall_recall\"],\n... \"f1\": results[\"overall_f1\"],\n... \"accuracy\": results[\"overall_accuracy\"],\n... }\n```\n\nYour `compute_metrics` function is ready to go now, and you'll return to it when you setup your training.", "source_file": "transformers/tasks/token_classification.md", "section_heading": "Evaluate", "char_start": 6983, "char_end": 7964, "token_estimate": 245, "prev_chunk_id": 190, "next_chunk_id": 192, "url": "https://huggingface.co/docs/transformers/tasks/token_classification", "doc_title": "Token classification" }, { "chunk_id": 192, "text": "## Train\n\nBefore you start training your model, create a map of the expected ids to their labels with `id2label` and `label2id`:\n\n```py\n>>> id2label = {\n... 0: \"O\",\n... 1: \"B-corporation\",\n... 2: \"I-corporation\",\n... 3: \"B-creative-work\",\n... 4: \"I-creative-work\",\n... 5: \"B-group\",\n... 6: \"I-group\",\n... 7: \"B-location\",\n... 8: \"I-location\",\n... 9: \"B-person\",\n... 10: \"I-person\",\n... 11: \"B-product\",\n... 12: \"I-product\",\n... }\n>>> label2id = {\n... \"O\": 0,\n... \"B-corporation\": 1,\n... \"I-corporation\": 2,\n... \"B-creative-work\": 3,\n... \"I-creative-work\": 4,\n... \"B-group\": 5,\n... \"I-group\": 6,\n... \"B-location\": 7,\n... \"I-location\": 8,\n... \"B-person\": 9,\n... \"I-person\": 10,\n... \"B-product\": 11,\n... \"I-product\": 12,\n... }\n```", "source_file": "transformers/tasks/token_classification.md", "section_heading": "Train", "char_start": 7966, "char_end": 8797, "token_estimate": 207, "prev_chunk_id": 191, "next_chunk_id": 193, "url": "https://huggingface.co/docs/transformers/tasks/token_classification", "doc_title": "Token classification" }, { "chunk_id": 193, "text": "If you aren't familiar with finetuning a model with the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer), take a look at the basic tutorial [here](../training#train-with-pytorch-trainer)!\n\nYou're ready to start training your model now! Load DistilBERT with [AutoModelForTokenClassification](/docs/transformers/v5.6.2/en/model_doc/auto#transformers.AutoModelForTokenClassification) along with the number of expected labels, and the label mappings:\n\n```py\n>>> from transformers import AutoModelForTokenClassification, TrainingArguments, Trainer\n\n>>> model = AutoModelForTokenClassification.from_pretrained(\n... \"distilbert/distilbert-base-uncased\", num_labels=13, id2label=id2label, label2id=label2id\n... )\n```\n\nAt this point, only three steps remain:", "source_file": "transformers/tasks/token_classification.md", "section_heading": "Train", "char_start": 8799, "char_end": 9585, "token_estimate": 196, "prev_chunk_id": 192, "next_chunk_id": 194, "url": "https://huggingface.co/docs/transformers/tasks/token_classification", "doc_title": "Token classification" }, { "chunk_id": 194, "text": "1. Define your training hyperparameters in [TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments). The only required parameter is `output_dir` which specifies where to save your model. You'll push this model to the Hub by setting `push_to_hub=True` (you need to be signed in to Hugging Face to upload your model). At the end of each epoch, the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) will evaluate the seqeval scores and save the training checkpoint.\n2. Pass the training arguments to [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) along with the model, dataset, tokenizer, data collator, and `compute_metrics` function.\n3. Call [train()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.train) to finetune your model.", "source_file": "transformers/tasks/token_classification.md", "section_heading": "Train", "char_start": 9587, "char_end": 10451, "token_estimate": 216, "prev_chunk_id": 193, "next_chunk_id": 195, "url": "https://huggingface.co/docs/transformers/tasks/token_classification", "doc_title": "Token classification" }, { "chunk_id": 195, "text": "```py\n>>> training_args = TrainingArguments(\n... output_dir=\"my_awesome_wnut_model\",\n... learning_rate=2e-5,\n... per_device_train_batch_size=16,\n... per_device_eval_batch_size=16,\n... num_train_epochs=2,\n... weight_decay=0.01,\n... eval_strategy=\"epoch\",\n... save_strategy=\"epoch\",\n... load_best_model_at_end=True,\n... push_to_hub=True,\n... )\n\n>>> trainer = Trainer(\n... model=model,\n... args=training_args,\n... train_dataset=tokenized_wnut[\"train\"],\n... eval_dataset=tokenized_wnut[\"test\"],\n... processing_class=tokenizer,\n... data_collator=data_collator,\n... compute_metrics=compute_metrics,\n... )\n\n>>> trainer.train()\n```\n\nOnce training is completed, share your model to the Hub with the [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.push_to_hub) method so everyone can use your model:\n\n```py\n>>> trainer.push_to_hub()\n```", "source_file": "transformers/tasks/token_classification.md", "section_heading": "Train", "char_start": 10453, "char_end": 11386, "token_estimate": 233, "prev_chunk_id": 194, "next_chunk_id": 196, "url": "https://huggingface.co/docs/transformers/tasks/token_classification", "doc_title": "Token classification" }, { "chunk_id": 196, "text": "For a more in-depth example of how to finetune a model for token classification, take a look at the corresponding\n[PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/token_classification.ipynb).", "source_file": "transformers/tasks/token_classification.md", "section_heading": "Train", "char_start": 11388, "char_end": 11631, "token_estimate": 60, "prev_chunk_id": 195, "next_chunk_id": 197, "url": "https://huggingface.co/docs/transformers/tasks/token_classification", "doc_title": "Token classification" }, { "chunk_id": 197, "text": "## Inference\n\nGreat, now that you've finetuned a model, you can use it for inference!\n\nGrab some text you'd like to run inference on:\n\n```py\n>>> text = \"The Golden State Warriors are an American professional basketball team based in San Francisco.\"\n```\n\nThe simplest way to try out your finetuned model for inference is to use it in a [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline). Instantiate a `pipeline` for NER with your model, and pass your text to it:", "source_file": "transformers/tasks/token_classification.md", "section_heading": "Inference", "char_start": 11633, "char_end": 12132, "token_estimate": 124, "prev_chunk_id": 196, "next_chunk_id": 198, "url": "https://huggingface.co/docs/transformers/tasks/token_classification", "doc_title": "Token classification" }, { "chunk_id": 198, "text": "```py\n>>> from transformers import pipeline\n\n>>> classifier = pipeline(\"ner\", model=\"stevhliu/my_awesome_wnut_model\")\n>>> classifier(text)\n[{'entity': 'B-location',\n 'score': 0.42658573,\n 'index': 2,\n 'word': 'golden',\n 'start': 4,\n 'end': 10},\n {'entity': 'I-location',\n 'score': 0.35856336,\n 'index': 3,\n 'word': 'state',\n 'start': 11,\n 'end': 16},\n {'entity': 'B-group',\n 'score': 0.3064001,\n 'index': 4,\n 'word': 'warriors',\n 'start': 17,\n 'end': 25},\n {'entity': 'B-location',\n 'score': 0.65523505,\n 'index': 13,\n 'word': 'san',\n 'start': 80,\n 'end': 83},\n {'entity': 'B-location',\n 'score': 0.4668663,\n 'index': 14,\n 'word': 'francisco',\n 'start': 84,\n 'end': 93}]\n```\n\nYou can also manually replicate the results of the `pipeline` if you'd like:\n\nTokenize the text and return PyTorch tensors:\n\n```py\n>>> from transformers import AutoTokenizer\n\n>>> tokenizer = AutoTokenizer.from_pretrained(\"stevhliu/my_awesome_wnut_model\")\n>>> inputs = tokenizer(text, return_tensors=\"pt\")\n```", "source_file": "transformers/tasks/token_classification.md", "section_heading": "Inference", "char_start": 12134, "char_end": 13143, "token_estimate": 252, "prev_chunk_id": 197, "next_chunk_id": 199, "url": "https://huggingface.co/docs/transformers/tasks/token_classification", "doc_title": "Token classification" }, { "chunk_id": 199, "text": "Pass your inputs to the model and return the `logits`:\n\n```py\n>>> from transformers import AutoModelForTokenClassification\n\n>>> model = AutoModelForTokenClassification.from_pretrained(\"stevhliu/my_awesome_wnut_model\")\n>>> with torch.no_grad():\n... logits = model(**inputs).logits\n```\n\nGet the class with the highest probability, and use the model's `id2label` mapping to convert it to a text label:\n\n```py\n>>> predictions = torch.argmax(logits, dim=2)\n>>> predicted_token_class = [model.config.id2label[t.item()] for t in predictions[0]]\n>>> predicted_token_class\n['O',\n 'O',\n 'B-location',\n 'I-location',\n 'B-group',\n 'O',\n 'O',\n 'O',\n 'O',\n 'O',\n 'O',\n 'O',\n 'O',\n 'B-location',\n 'B-location',\n 'O',\n 'O']\n```", "source_file": "transformers/tasks/token_classification.md", "section_heading": "Inference", "char_start": 13145, "char_end": 13860, "token_estimate": 178, "prev_chunk_id": 198, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/tasks/token_classification", "doc_title": "Token classification" }, { "chunk_id": 200, "text": "# Question answering\n\nQuestion answering tasks return an answer given a question. If you've ever asked a virtual assistant like Alexa, Siri or Google what the weather is, then you've used a question answering model before. There are two common types of question answering tasks:\n\n- Extractive: extract the answer from the given context.\n- Abstractive: generate an answer from the context that correctly answers the question.\n\nThis guide will show you how to:\n\n1. Finetune [DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased) on the [SQuAD](https://huggingface.co/datasets/squad) dataset for extractive question answering.\n2. Use your finetuned model for inference.\n\nTo see all architectures and checkpoints compatible with this task, we recommend checking the [task-page](https://huggingface.co/tasks/question-answering)\n\nBefore you begin, make sure you have all the necessary libraries installed:\n\n```bash\npip install transformers datasets evaluate\n```", "source_file": "transformers/tasks/question_answering.md", "section_heading": "Question answering", "char_start": 0, "char_end": 972, "token_estimate": 243, "prev_chunk_id": null, "next_chunk_id": 201, "url": "https://huggingface.co/docs/transformers/tasks/question_answering", "doc_title": "Question answering" }, { "chunk_id": 201, "text": "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:\n\n```py\n>>> from huggingface_hub import notebook_login\n\n>>> notebook_login()\n```", "source_file": "transformers/tasks/question_answering.md", "section_heading": "Question answering", "char_start": 974, "char_end": 1209, "token_estimate": 58, "prev_chunk_id": 200, "next_chunk_id": 202, "url": "https://huggingface.co/docs/transformers/tasks/question_answering", "doc_title": "Question answering" }, { "chunk_id": 202, "text": "## Load SQuAD dataset\n\nStart by loading a smaller subset of the SQuAD dataset from the \ud83e\udd17 Datasets library. This'll give you a chance to experiment and make sure everything works before spending more time training on the full dataset.\n\n```py\n>>> from datasets import load_dataset\n\n>>> squad = load_dataset(\"squad\", split=\"train[:5000]\")\n```\n\nSplit the dataset's `train` split into a train and test set with the [train_test_split](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.train_test_split) method:\n\n```py\n>>> squad = squad.train_test_split(test_size=0.2)\n```\n\nThen take a look at an example:", "source_file": "transformers/tasks/question_answering.md", "section_heading": "Load SQuAD dataset", "char_start": 1211, "char_end": 1854, "token_estimate": 160, "prev_chunk_id": 201, "next_chunk_id": 203, "url": "https://huggingface.co/docs/transformers/tasks/question_answering", "doc_title": "Question answering" }, { "chunk_id": 203, "text": "```py\n>>> squad[\"train\"][0]\n{'answers': {'answer_start': [515], 'text': ['Saint Bernadette Soubirous']},\n 'context': 'Architecturally, the school has a Catholic character. Atop the Main Building\\'s gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend \"Venite Ad Me Omnes\". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary.',\n 'id': '5733be284776f41900661182',\n 'question': 'To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?',\n 'title': 'University_of_Notre_Dame'\n}\n```\n\nThere are several important fields here:", "source_file": "transformers/tasks/question_answering.md", "section_heading": "Load SQuAD dataset", "char_start": 1856, "char_end": 2880, "token_estimate": 256, "prev_chunk_id": 202, "next_chunk_id": 204, "url": "https://huggingface.co/docs/transformers/tasks/question_answering", "doc_title": "Question answering" }, { "chunk_id": 204, "text": "- `answers`: the starting location of the answer token and the answer text.\n- `context`: background information from which the model needs to extract the answer.\n- `question`: the question a model should answer.", "source_file": "transformers/tasks/question_answering.md", "section_heading": "Load SQuAD dataset", "char_start": 2882, "char_end": 3093, "token_estimate": 52, "prev_chunk_id": 203, "next_chunk_id": 205, "url": "https://huggingface.co/docs/transformers/tasks/question_answering", "doc_title": "Question answering" }, { "chunk_id": 205, "text": "## Preprocess\n\nThe next step is to load a DistilBERT tokenizer to process the `question` and `context` fields:\n\n```py\n>>> from transformers import AutoTokenizer\n\n>>> tokenizer = AutoTokenizer.from_pretrained(\"distilbert/distilbert-base-uncased\")\n```\n\nThere are a few preprocessing steps particular to question answering tasks you should be aware of:\n\n1. Some examples in a dataset may have a very long `context` that exceeds the maximum input length of the model. To deal with longer sequences, truncate only the `context` by setting `truncation=\"only_second\"`.\n2. Next, map the start and end positions of the answer to the original `context` by setting\n `return_offset_mapping=True`.\n3. With the mapping in hand, now you can find the start and end tokens of the answer. Use the `sequence_ids` method to\n find which part of the offset corresponds to the `question` and which corresponds to the `context`.\n\nHere is how you can create a function to truncate and map the start and end tokens of the `answer` to the `context`:", "source_file": "transformers/tasks/question_answering.md", "section_heading": "Preprocess", "char_start": 3095, "char_end": 4121, "token_estimate": 256, "prev_chunk_id": 204, "next_chunk_id": 206, "url": "https://huggingface.co/docs/transformers/tasks/question_answering", "doc_title": "Question answering" }, { "chunk_id": 206, "text": "```py\n>>> def preprocess_function(examples):\n... questions = [q.strip() for q in examples[\"question\"]]\n... inputs = tokenizer(\n... questions,\n... examples[\"context\"],\n... max_length=384,\n... truncation=\"only_second\",\n... return_offsets_mapping=True,\n... padding=\"max_length\",\n... )\n\n... offset_mapping = inputs.pop(\"offset_mapping\")\n... answers = examples[\"answers\"]\n... start_positions = []\n... end_positions = []\n\n... for i, offset in enumerate(offset_mapping):\n... answer = answers[i]\n... start_char = answer[\"answer_start\"][0]\n... end_char = answer[\"answer_start\"][0] + len(answer[\"text\"][0])\n... sequence_ids = inputs.sequence_ids(i)\n\n... # Find the start and end of the context\n... idx = 0\n... while sequence_ids[idx] != 1:\n... idx += 1\n... context_start = idx\n... while sequence_ids[idx] == 1:\n... idx += 1\n... context_end = idx - 1\n\n... # If the answer is not fully inside the context, label it (0, 0)\n... if offset[context_start][0] > end_char or offset[context_end][1] = context_start and offset[idx][1] >= end_char:\n... idx -= 1\n... end_positions.append(idx + 1)\n\n... inputs[\"start_positions\"] = start_positions\n... inputs[\"end_positions\"] = end_positions\n... return inputs\n```", "source_file": "transformers/tasks/question_answering.md", "section_heading": "Preprocess", "char_start": 4123, "char_end": 5551, "token_estimate": 357, "prev_chunk_id": 205, "next_chunk_id": 207, "url": "https://huggingface.co/docs/transformers/tasks/question_answering", "doc_title": "Question answering" }, { "chunk_id": 207, "text": "To apply the preprocessing function over the entire dataset, use \ud83e\udd17 Datasets [map](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) function. You can speed up the `map` function by setting `batched=True` to process multiple elements of the dataset at once. Remove any columns you don't need:\n\n```py\n>>> tokenized_squad = squad.map(preprocess_function, batched=True, remove_columns=squad[\"train\"].column_names)\n```\n\nNow create a batch of examples using [DefaultDataCollator](/docs/transformers/v5.6.2/en/main_classes/data_collator#transformers.DefaultDataCollator). Unlike other data collators in \ud83e\udd17 Transformers, the [DefaultDataCollator](/docs/transformers/v5.6.2/en/main_classes/data_collator#transformers.DefaultDataCollator) does not apply any additional preprocessing such as padding.\n\n```py\n>>> from transformers import DefaultDataCollator\n\n>>> data_collator = DefaultDataCollator()\n```", "source_file": "transformers/tasks/question_answering.md", "section_heading": "Preprocess", "char_start": 5553, "char_end": 6494, "token_estimate": 235, "prev_chunk_id": 206, "next_chunk_id": 208, "url": "https://huggingface.co/docs/transformers/tasks/question_answering", "doc_title": "Question answering" }, { "chunk_id": 208, "text": "## Train\n\nIf you aren't familiar with finetuning a model with the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer), take a look at the basic tutorial [here](../training#train-with-pytorch-trainer)!\n\nYou're ready to start training your model now! Load DistilBERT with [AutoModelForQuestionAnswering](/docs/transformers/v5.6.2/en/model_doc/auto#transformers.AutoModelForQuestionAnswering):\n\n```py\n>>> from transformers import AutoModelForQuestionAnswering, TrainingArguments, Trainer\n\n>>> model = AutoModelForQuestionAnswering.from_pretrained(\"distilbert/distilbert-base-uncased\")\n```\n\nAt this point, only three steps remain:", "source_file": "transformers/tasks/question_answering.md", "section_heading": "Train", "char_start": 6496, "char_end": 7152, "token_estimate": 164, "prev_chunk_id": 207, "next_chunk_id": 209, "url": "https://huggingface.co/docs/transformers/tasks/question_answering", "doc_title": "Question answering" }, { "chunk_id": 209, "text": "1. Define your training hyperparameters in [TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments). The only required parameter is `output_dir` which specifies where to save your model. You'll push this model to the Hub by setting `push_to_hub=True` (you need to be signed in to Hugging Face to upload your model).\n2. Pass the training arguments to [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) along with the model, dataset, tokenizer, and data collator.\n3. Call [train()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.train) to finetune your model.", "source_file": "transformers/tasks/question_answering.md", "section_heading": "Train", "char_start": 7154, "char_end": 7811, "token_estimate": 164, "prev_chunk_id": 208, "next_chunk_id": 210, "url": "https://huggingface.co/docs/transformers/tasks/question_answering", "doc_title": "Question answering" }, { "chunk_id": 210, "text": "```py\n>>> training_args = TrainingArguments(\n... output_dir=\"my_awesome_qa_model\",\n... eval_strategy=\"epoch\",\n... learning_rate=2e-5,\n... per_device_train_batch_size=16,\n... per_device_eval_batch_size=16,\n... num_train_epochs=3,\n... weight_decay=0.01,\n... push_to_hub=True,\n... )\n\n>>> trainer = Trainer(\n... model=model,\n... args=training_args,\n... train_dataset=tokenized_squad[\"train\"],\n... eval_dataset=tokenized_squad[\"test\"],\n... processing_class=tokenizer,\n... data_collator=data_collator,\n... )\n\n>>> trainer.train()\n```\n\nOnce training is completed, share your model to the Hub with the [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.push_to_hub) method so everyone can use your model:\n\n```py\n>>> trainer.push_to_hub()\n```", "source_file": "transformers/tasks/question_answering.md", "section_heading": "Train", "char_start": 7813, "char_end": 8637, "token_estimate": 206, "prev_chunk_id": 209, "next_chunk_id": 211, "url": "https://huggingface.co/docs/transformers/tasks/question_answering", "doc_title": "Question answering" }, { "chunk_id": 211, "text": "For a more in-depth example of how to finetune a model for question answering, take a look at the corresponding\n[PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/question_answering.ipynb).", "source_file": "transformers/tasks/question_answering.md", "section_heading": "Train", "char_start": 8639, "char_end": 8878, "token_estimate": 59, "prev_chunk_id": 210, "next_chunk_id": 212, "url": "https://huggingface.co/docs/transformers/tasks/question_answering", "doc_title": "Question answering" }, { "chunk_id": 212, "text": "## Evaluate\n\nEvaluation for question answering requires a significant amount of postprocessing. To avoid taking up too much of your time, this guide skips the evaluation step. The [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) still calculates the evaluation loss during training so you're not completely in the dark about your model's performance.\n\nIf you have more time and you're interested in how to evaluate your model for question answering, take a look at the [Question answering](https://huggingface.co/course/chapter7/7?fw=pt#post-processing) chapter from the \ud83e\udd17 Hugging Face Course!", "source_file": "transformers/tasks/question_answering.md", "section_heading": "Evaluate", "char_start": 8880, "char_end": 9506, "token_estimate": 156, "prev_chunk_id": 211, "next_chunk_id": 213, "url": "https://huggingface.co/docs/transformers/tasks/question_answering", "doc_title": "Question answering" }, { "chunk_id": 213, "text": "## Inference\n\nGreat, now that you've finetuned a model, you can use it for inference!\n\nCome up with a question and some context you'd like the model to predict:\n\n```py\n>>> question = \"How many programming languages does BLOOM support?\"\n>>> context = \"BLOOM has 176 billion parameters and can generate text in 46 languages natural languages and 13 programming languages.\"\n```\n\nTokenize the text and return PyTorch tensors:\n\n```py\n>>> from transformers import AutoTokenizer\n\n>>> tokenizer = AutoTokenizer.from_pretrained(\"my_awesome_qa_model\")\n>>> inputs = tokenizer(question, context, return_tensors=\"pt\")\n```\n\nPass your inputs to the model and return the `logits`:\n\n```py\n>>> import torch\n>>> from transformers import AutoModelForQuestionAnswering\n\n>>> model = AutoModelForQuestionAnswering.from_pretrained(\"my_awesome_qa_model\")\n>>> with torch.no_grad():\n... outputs = model(**inputs)\n```\n\nGet the highest probability from the model output for the start and end positions:", "source_file": "transformers/tasks/question_answering.md", "section_heading": "Inference", "char_start": 9508, "char_end": 10485, "token_estimate": 244, "prev_chunk_id": 212, "next_chunk_id": 214, "url": "https://huggingface.co/docs/transformers/tasks/question_answering", "doc_title": "Question answering" }, { "chunk_id": 214, "text": "```py\n>>> answer_start_index = outputs.start_logits.argmax()\n>>> answer_end_index = outputs.end_logits.argmax()\n```\n\nDecode the predicted tokens to get the answer:\n\n```py\n>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]\n>>> tokenizer.decode(predict_answer_tokens)\n'176 billion parameters and can generate text in 46 languages natural languages and 13'\n```", "source_file": "transformers/tasks/question_answering.md", "section_heading": "Inference", "char_start": 10487, "char_end": 10884, "token_estimate": 99, "prev_chunk_id": 213, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/tasks/question_answering", "doc_title": "Question answering" }, { "chunk_id": 215, "text": "# Causal language modeling\n\nThere are two types of language modeling, causal and masked. This guide illustrates causal language modeling.\nCausal language models are frequently used for text generation. You can use these models for creative applications like\nchoosing your own text adventure or an intelligent coding assistant like Copilot or CodeParrot.\n\nCausal language modeling predicts the next token in a sequence of tokens, and the model can only attend to tokens on\nthe left. This means the model cannot see future tokens. GPT-2 is an example of a causal language model.\n\nThis guide will show you how to:\n\n1. Finetune [DistilGPT2](https://huggingface.co/distilbert/distilgpt2) on the [r/askscience](https://www.reddit.com/r/askscience/) subset of the [ELI5](https://huggingface.co/datasets/dany0407/eli5_category) dataset.\n2. Use your finetuned model for inference.\n\nTo see all architectures and checkpoints compatible with this task, we recommend checking the [task-page](https://huggingface.co/tasks/text-generation)", "source_file": "transformers/tasks/language_modeling.md", "section_heading": "Causal language modeling", "char_start": 0, "char_end": 1024, "token_estimate": 256, "prev_chunk_id": null, "next_chunk_id": 216, "url": "https://huggingface.co/docs/transformers/tasks/language_modeling", "doc_title": "Causal language modeling" }, { "chunk_id": 216, "text": "Before you begin, make sure you have all the necessary libraries installed:\n\n```bash\npip install transformers datasets evaluate\n```\n\nWe 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:\n\n```py\n>>> from huggingface_hub import notebook_login\n\n>>> notebook_login()\n```", "source_file": "transformers/tasks/language_modeling.md", "section_heading": "Causal language modeling", "char_start": 1026, "char_end": 1396, "token_estimate": 92, "prev_chunk_id": 215, "next_chunk_id": 217, "url": "https://huggingface.co/docs/transformers/tasks/language_modeling", "doc_title": "Causal language modeling" }, { "chunk_id": 217, "text": "## Load ELI5 dataset\n\nStart by loading the first 5000 examples from the [ELI5-Category](https://huggingface.co/datasets/dany0407/eli5_category) dataset with the \ud83e\udd17 Datasets library. This'll give you a chance to experiment and make sure everything works before spending more time training on the full dataset.\n\n```py\n>>> from datasets import load_dataset\n\n>>> eli5 = load_dataset(\"dany0407/eli5_category\", split=\"train[:5000]\")\n```\n\nSplit the dataset's `train` split into a train and test set with the [train_test_split](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.train_test_split) method:\n\n```py\n>>> eli5 = eli5.train_test_split(test_size=0.2)\n```\n\nThen take a look at an example:", "source_file": "transformers/tasks/language_modeling.md", "section_heading": "Load ELI5 dataset", "char_start": 1398, "char_end": 2129, "token_estimate": 182, "prev_chunk_id": 216, "next_chunk_id": 218, "url": "https://huggingface.co/docs/transformers/tasks/language_modeling", "doc_title": "Causal language modeling" }, { "chunk_id": 218, "text": "```py\n>>> eli5[\"train\"][0]\n{'q_id': '7h191n',\n 'title': 'What does the tax bill that was passed today mean? How will it affect Americans in each tax bracket?',\n 'selftext': '',\n 'category': 'Economics',\n 'subreddit': 'explainlikeimfive',\n 'answers': {'a_id': ['dqnds8l', 'dqnd1jl', 'dqng3i1', 'dqnku5x'],\n 'text': [\"The tax bill is 500 pages long and there were a lot of changes still going on right to the end. It's not just an adjustment to the income tax brackets, it's a whole bunch of changes. As such there is no good answer to your question. The big take aways are: - Big reduction in corporate income tax rate will make large companies very happy. - Pass through rate change will make certain styles of business (law firms, hedge funds) extremely happy - Income tax changes are moderate, and are set to expire (though it's the kind of thing that might just always get re-applied without being made permanent) - People in high tax states (California, New York) lose out, and many of them will end up with their taxes raised.\",\n 'None yet. It has to be reconciled with a vastly different house bill and then passed again.',\n 'Also: does this apply to 2017 taxes? Or does it start with 2018 taxes?',\n 'This article explains both the House and senate bills, including the proposed changes to your income taxes based on your income level. URL_0'],\n 'score': [21, 19, 5, 3],\n 'text_urls': [[],\n [],\n [],\n ['https://www.investopedia.com/news/trumps-tax-reform-what-can-be-done/']]},\n 'title_urls': ['url'],\n 'selftext_urls': ['url']}\n```", "source_file": "transformers/tasks/language_modeling.md", "section_heading": "Load ELI5 dataset", "char_start": 2131, "char_end": 3684, "token_estimate": 388, "prev_chunk_id": 217, "next_chunk_id": 219, "url": "https://huggingface.co/docs/transformers/tasks/language_modeling", "doc_title": "Causal language modeling" }, { "chunk_id": 219, "text": "While this may look like a lot, you're only really interested in the `text` field. What's cool about language modeling\ntasks is you don't need labels (also known as an unsupervised task) because the next word *is* the label.", "source_file": "transformers/tasks/language_modeling.md", "section_heading": "Load ELI5 dataset", "char_start": 3686, "char_end": 3910, "token_estimate": 56, "prev_chunk_id": 218, "next_chunk_id": 220, "url": "https://huggingface.co/docs/transformers/tasks/language_modeling", "doc_title": "Causal language modeling" }, { "chunk_id": 220, "text": "## Preprocess\n\nThe next step is to load a DistilGPT2 tokenizer to process the `text` subfield:\n\n```py\n>>> from transformers import AutoTokenizer\n\n>>> tokenizer = AutoTokenizer.from_pretrained(\"distilbert/distilgpt2\")\n```\n\nYou'll notice from the example above, the `text` field is actually nested inside `answers`. This means you'll need to\nextract the `text` subfield from its nested structure with the [`flatten`](https://huggingface.co/docs/datasets/process#flatten) method:", "source_file": "transformers/tasks/language_modeling.md", "section_heading": "Preprocess", "char_start": 3912, "char_end": 4388, "token_estimate": 119, "prev_chunk_id": 219, "next_chunk_id": 221, "url": "https://huggingface.co/docs/transformers/tasks/language_modeling", "doc_title": "Causal language modeling" }, { "chunk_id": 221, "text": "```py\n>>> eli5 = eli5.flatten()\n>>> eli5[\"train\"][0]\n{'q_id': '7h191n',\n 'title': 'What does the tax bill that was passed today mean? How will it affect Americans in each tax bracket?',\n 'selftext': '',\n 'category': 'Economics',\n 'subreddit': 'explainlikeimfive',\n 'answers.a_id': ['dqnds8l', 'dqnd1jl', 'dqng3i1', 'dqnku5x'],\n 'answers.text': [\"The tax bill is 500 pages long and there were a lot of changes still going on right to the end. It's not just an adjustment to the income tax brackets, it's a whole bunch of changes. As such there is no good answer to your question. The big take aways are: - Big reduction in corporate income tax rate will make large companies very happy. - Pass through rate change will make certain styles of business (law firms, hedge funds) extremely happy - Income tax changes are moderate, and are set to expire (though it's the kind of thing that might just always get re-applied without being made permanent) - People in high tax states (California, New York) lose out, and many of them will end up with their taxes raised.\",\n 'None yet. It has to be reconciled with a vastly different house bill and then passed again.',\n 'Also: does this apply to 2017 taxes? Or does it start with 2018 taxes?',\n 'This article explains both the House and senate bills, including the proposed changes to your income taxes based on your income level. URL_0'],\n 'answers.score': [21, 19, 5, 3],\n 'answers.text_urls': [[],\n [],\n [],\n ['https://www.investopedia.com/news/trumps-tax-reform-what-can-be-done/']],\n 'title_urls': ['url'],\n 'selftext_urls': ['url']}\n```", "source_file": "transformers/tasks/language_modeling.md", "section_heading": "Preprocess", "char_start": 4390, "char_end": 5979, "token_estimate": 397, "prev_chunk_id": 220, "next_chunk_id": 222, "url": "https://huggingface.co/docs/transformers/tasks/language_modeling", "doc_title": "Causal language modeling" }, { "chunk_id": 222, "text": "Each subfield is now a separate column as indicated by the `answers` prefix, and the `text` field is a list now. Instead\nof tokenizing each sentence separately, convert the list to a string so you can jointly tokenize them.\n\nHere is a first preprocessing function to join the list of strings for each example and tokenize the result:\n\n```py\n>>> def preprocess_function(examples):\n... return tokenizer([\" \".join(x) for x in examples[\"answers.text\"]])\n```\n\nTo apply this preprocessing function over the entire dataset, use the \ud83e\udd17 Datasets [map](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) method. You can speed up the `map` function by setting `batched=True` to process multiple elements of the dataset at once, and increasing the number of processes with `num_proc`. Remove any columns you don't need:", "source_file": "transformers/tasks/language_modeling.md", "section_heading": "Preprocess", "char_start": 5981, "char_end": 6840, "token_estimate": 214, "prev_chunk_id": 221, "next_chunk_id": 223, "url": "https://huggingface.co/docs/transformers/tasks/language_modeling", "doc_title": "Causal language modeling" }, { "chunk_id": 223, "text": "```py\n>>> tokenized_eli5 = eli5.map(\n... preprocess_function,\n... batched=True,\n... num_proc=4,\n... remove_columns=eli5[\"train\"].column_names,\n... )\n```\n\nThis dataset contains the token sequences, but some of these are longer than the maximum input length for the model.\n\nYou can now use a second preprocessing function to\n\n- concatenate all the sequences\n- split the concatenated sequences into shorter chunks defined by `block_size`, which should be both shorter than the maximum input length and short enough for your GPU RAM.", "source_file": "transformers/tasks/language_modeling.md", "section_heading": "Preprocess", "char_start": 6842, "char_end": 7387, "token_estimate": 136, "prev_chunk_id": 222, "next_chunk_id": 224, "url": "https://huggingface.co/docs/transformers/tasks/language_modeling", "doc_title": "Causal language modeling" }, { "chunk_id": 224, "text": "```py\n>>> block_size = 128\n\n>>> def group_texts(examples):\n... # Concatenate all texts.\n... concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}\n... total_length = len(concatenated_examples[list(examples.keys())[0]])\n... # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can\n... # customize this part to your needs.\n... if total_length >= block_size:\n... total_length = (total_length // block_size) * block_size\n... # Split by chunks of block_size.\n... result = {\n... k: [t[i : i + block_size] for i in range(0, total_length, block_size)]\n... for k, t in concatenated_examples.items()\n... }\n... result[\"labels\"] = result[\"input_ids\"].copy()\n... return result\n```\n\nApply the `group_texts` function over the entire dataset:\n\n```py\n>>> lm_dataset = tokenized_eli5.map(group_texts, batched=True, num_proc=4)\n```", "source_file": "transformers/tasks/language_modeling.md", "section_heading": "Preprocess", "char_start": 7389, "char_end": 8340, "token_estimate": 237, "prev_chunk_id": 223, "next_chunk_id": 225, "url": "https://huggingface.co/docs/transformers/tasks/language_modeling", "doc_title": "Causal language modeling" }, { "chunk_id": 225, "text": "Now create a batch of examples using [DataCollatorForLanguageModeling](/docs/transformers/v5.6.2/en/main_classes/data_collator#transformers.DataCollatorForLanguageModeling). It's more efficient to *dynamically pad* the\nsentences to the longest length in a batch during collation, instead of padding the whole dataset to the maximum length.\n\nUse the end-of-sequence token as the padding token and set `mlm=False`. This will use the inputs as labels shifted to the right by one element:\n\n```py\n>>> from transformers import DataCollatorForLanguageModeling\n\n>>> tokenizer.pad_token = tokenizer.eos_token\n>>> data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)\n```", "source_file": "transformers/tasks/language_modeling.md", "section_heading": "Preprocess", "char_start": 8342, "char_end": 9029, "token_estimate": 171, "prev_chunk_id": 224, "next_chunk_id": 226, "url": "https://huggingface.co/docs/transformers/tasks/language_modeling", "doc_title": "Causal language modeling" }, { "chunk_id": 226, "text": "## Train\n\nIf you aren't familiar with finetuning a model with the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer), take a look at the [basic tutorial](../training#train-with-pytorch-trainer)!\n\nYou're ready to start training your model now! Load DistilGPT2 with [AutoModelForCausalLM](/docs/transformers/v5.6.2/en/model_doc/auto#transformers.AutoModelForCausalLM):\n\n```py\n>>> from transformers import AutoModelForCausalLM, TrainingArguments, Trainer\n\n>>> model = AutoModelForCausalLM.from_pretrained(\"distilbert/distilgpt2\")\n```\n\nAt this point, only three steps remain:", "source_file": "transformers/tasks/language_modeling.md", "section_heading": "Train", "char_start": 9031, "char_end": 9633, "token_estimate": 150, "prev_chunk_id": 225, "next_chunk_id": 227, "url": "https://huggingface.co/docs/transformers/tasks/language_modeling", "doc_title": "Causal language modeling" }, { "chunk_id": 227, "text": "1. Define your training hyperparameters in [TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments). The only required parameter is `output_dir` which specifies where to save your model. You'll push this model to the Hub by setting `push_to_hub=True` (you need to be signed in to Hugging Face to upload your model).\n2. Pass the training arguments to [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) along with the model, datasets, and data collator.\n3. Call [train()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.train) to finetune your model.", "source_file": "transformers/tasks/language_modeling.md", "section_heading": "Train", "char_start": 9635, "char_end": 10282, "token_estimate": 161, "prev_chunk_id": 226, "next_chunk_id": 228, "url": "https://huggingface.co/docs/transformers/tasks/language_modeling", "doc_title": "Causal language modeling" }, { "chunk_id": 228, "text": "```py\n>>> training_args = TrainingArguments(\n... output_dir=\"my_awesome_eli5_clm-model\",\n... eval_strategy=\"epoch\",\n... learning_rate=2e-5,\n... weight_decay=0.01,\n... push_to_hub=True,\n... )\n\n>>> trainer = Trainer(\n... model=model,\n... args=training_args,\n... train_dataset=lm_dataset[\"train\"],\n... eval_dataset=lm_dataset[\"test\"],\n... data_collator=data_collator,\n... processing_class=tokenizer,\n... )\n\n>>> trainer.train()\n```\n\nOnce training is completed, use the [evaluate()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.evaluate) method to evaluate your model and get its perplexity:\n\n```py\n>>> import math\n\n>>> eval_results = trainer.evaluate()\n>>> print(f\"Perplexity: {math.exp(eval_results['eval_loss']):.2f}\")\nPerplexity: 49.61\n```\n\nThen share your model to the Hub with the [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.push_to_hub) method so everyone can use your model:\n\n```py\n>>> trainer.push_to_hub()\n```", "source_file": "transformers/tasks/language_modeling.md", "section_heading": "Train", "char_start": 10284, "char_end": 11311, "token_estimate": 256, "prev_chunk_id": 227, "next_chunk_id": 229, "url": "https://huggingface.co/docs/transformers/tasks/language_modeling", "doc_title": "Causal language modeling" }, { "chunk_id": 229, "text": "For a more in-depth example of how to finetune a model for causal language modeling, take a look at the corresponding\n[PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/language_modeling.ipynb).", "source_file": "transformers/tasks/language_modeling.md", "section_heading": "Train", "char_start": 11313, "char_end": 11557, "token_estimate": 61, "prev_chunk_id": 228, "next_chunk_id": 230, "url": "https://huggingface.co/docs/transformers/tasks/language_modeling", "doc_title": "Causal language modeling" }, { "chunk_id": 230, "text": "## Inference\n\nGreat, now that you've finetuned a model, you can use it for inference!\n\nCome up with a prompt you'd like to generate text from:\n\n```py\n>>> prompt = \"Somatic hypermutation allows the immune system to\"\n```\n\nThe simplest way to try out your finetuned model for inference is to use it in a [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline). Instantiate a `pipeline` for text generation with your model, and pass your text to it:\n\n```py\n>>> from transformers import pipeline\n\n>>> generator = pipeline(\"text-generation\", model=\"username/my_awesome_eli5_clm-model\")\n>>> generator(prompt)\n[{'generated_text': \"Somatic hypermutation allows the immune system to be able to effectively reverse the damage caused by an infection.\\n\\n\\nThe damage caused by an infection is caused by the immune system's ability to perform its own self-correcting tasks.\"}]\n```\n\nTokenize the text and return the `input_ids` as PyTorch tensors:", "source_file": "transformers/tasks/language_modeling.md", "section_heading": "Inference", "char_start": 11559, "char_end": 12524, "token_estimate": 241, "prev_chunk_id": 229, "next_chunk_id": 231, "url": "https://huggingface.co/docs/transformers/tasks/language_modeling", "doc_title": "Causal language modeling" }, { "chunk_id": 231, "text": "```py\n>>> from transformers import AutoTokenizer\n\n>>> tokenizer = AutoTokenizer.from_pretrained(\"username/my_awesome_eli5_clm-model\")\n>>> inputs = tokenizer(prompt, return_tensors=\"pt\").input_ids\n```\n\nUse the [generate()](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationMixin.generate) method to generate text.\nFor more details about the different text generation strategies and parameters for controlling generation, check out the [Text generation strategies](../generation_strategies) page.\n\n```py\n>>> from transformers import AutoModelForCausalLM\n\n>>> model = AutoModelForCausalLM.from_pretrained(\"username/my_awesome_eli5_clm-model\")\n>>> outputs = model.generate(inputs, max_new_tokens=100, do_sample=True, top_k=50, top_p=0.95)\n```\n\nDecode the generated token ids back into text:", "source_file": "transformers/tasks/language_modeling.md", "section_heading": "Inference", "char_start": 12526, "char_end": 13343, "token_estimate": 204, "prev_chunk_id": 230, "next_chunk_id": 232, "url": "https://huggingface.co/docs/transformers/tasks/language_modeling", "doc_title": "Causal language modeling" }, { "chunk_id": 232, "text": "```py\n>>> tokenizer.batch_decode(outputs, skip_special_tokens=True)\n[\"Somatic hypermutation allows the immune system to react to drugs with the ability to adapt to a different environmental situation. In other words, a system of 'hypermutation' can help the immune system to adapt to a different environmental situation or in some cases even a single life. In contrast, researchers at the University of Massachusetts-Boston have found that 'hypermutation' is much stronger in mice than in humans but can be found in humans, and that it's not completely unknown to the immune system. A study on how the immune system\"]\n```", "source_file": "transformers/tasks/language_modeling.md", "section_heading": "Inference", "char_start": 13345, "char_end": 13966, "token_estimate": 155, "prev_chunk_id": 231, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/tasks/language_modeling", "doc_title": "Causal language modeling" }, { "chunk_id": 233, "text": "# Summarization\n\nSummarization creates a shorter version of a document or an article that captures all the important information. Along with translation, it is another example of a task that can be formulated as a sequence-to-sequence task. Summarization can be:\n\n- Extractive: extract the most relevant information from a document.\n- Abstractive: generate new text that captures the most relevant information.\n\nThis guide will show you how to:\n\n1. Finetune [T5](https://huggingface.co/google-t5/t5-small) on the California state bill subset of the [BillSum](https://huggingface.co/datasets/FiscalNote/billsum) dataset for abstractive summarization.\n2. Use your finetuned model for inference.\n\nTo see all architectures and checkpoints compatible with this task, we recommend checking the [task-page](https://huggingface.co/tasks/summarization)\n\nBefore you begin, make sure you have all the necessary libraries installed:\n\n```bash\npip install transformers datasets evaluate rouge_score\n```", "source_file": "transformers/tasks/summarization.md", "section_heading": "Summarization", "char_start": 0, "char_end": 988, "token_estimate": 247, "prev_chunk_id": null, "next_chunk_id": 234, "url": "https://huggingface.co/docs/transformers/tasks/summarization", "doc_title": "Summarization" }, { "chunk_id": 234, "text": "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:\n\n```py\n>>> from huggingface_hub import notebook_login\n\n>>> notebook_login()\n```", "source_file": "transformers/tasks/summarization.md", "section_heading": "Summarization", "char_start": 990, "char_end": 1225, "token_estimate": 58, "prev_chunk_id": 233, "next_chunk_id": 235, "url": "https://huggingface.co/docs/transformers/tasks/summarization", "doc_title": "Summarization" }, { "chunk_id": 235, "text": "## Load BillSum dataset\n\nStart by loading the smaller California state bill subset of the BillSum dataset from the \ud83e\udd17 Datasets library:\n\n```py\n>>> from datasets import load_dataset\n\n>>> billsum = load_dataset(\"billsum\", split=\"ca_test\")\n```\n\nSplit the dataset into a train and test set with the [train_test_split](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.train_test_split) method:\n\n```py\n>>> billsum = billsum.train_test_split(test_size=0.2)\n```\n\nThen take a look at an example:", "source_file": "transformers/tasks/summarization.md", "section_heading": "Load BillSum dataset", "char_start": 1227, "char_end": 1758, "token_estimate": 132, "prev_chunk_id": 234, "next_chunk_id": 236, "url": "https://huggingface.co/docs/transformers/tasks/summarization", "doc_title": "Summarization" }, { "chunk_id": 236, "text": "```py\n>>> billsum[\"train\"][0]\n{'summary': 'Existing law authorizes state agencies to enter into contracts for the acquisition of goods or services upon approval by the Department of General Services. Existing law sets forth various requirements and prohibitions for those contracts, including, but not limited to, a prohibition on entering into contracts for the acquisition of goods or services of $100,000 or more with a contractor that discriminates between spouses and domestic partners or same-sex and different-sex couples in the provision of benefits. Existing law provides that a contract entered into in violation of those requirements and prohibitions is void and authorizes the state or any person acting on behalf of the state to bring a civil action seeking a determination that a contract is in violation and therefore void. Under existing law, a willful violation of those requirements and prohibitions is a misdemeanor.\\nThis bill would also prohibit a state agency from entering into contracts for the acquisition of goods or services of $100,000 or more with a contractor that discriminates between employees on the basis of gender identity in the provision of benefits, as specified. By expanding the scope of a crime, this bill would impose a state-mandated local program.\\nThe California Constitution requires the state to reimburse local agencies and school districts for certain costs mandated by the state. Statutory provisions establish procedures for making that reimbursement.\\nThis bill would provide that no reimbursement is required by this act for a specified reason.',\n 'text': 'The people of the State of California do enact as follows:\\n\\n\\nSECTION 1.\\nSection 10295.35 is added to the Public Contract Code, to read:\\n10295.35.\\n(a) (1) Notwithstanding any other law, a state agency shall not enter into any contract for the acquisition of goods or services in the amount of one hundred thousand dollars ($100,000) or more with a contractor that, in the provision of benefits, discriminates between employees on the basis of an employee\u2019s or dependent\u2019s actual or perceived gender identity, including, but not limited to, the employee\u2019s or dependent\u2019s identification as transgender.\\n(2) For purposes of this section, \u201ccontract\u201d includes contracts with a cumulative amount of one hundred thousand dollars ($100,000) or more per contractor in each fiscal year.\\n(3) For purposes of this section, an employee health plan is discriminatory if the plan is not consistent with Section 1365.5 of the Health and Safety Code and Section 10140 of the Insurance Code.\\n(4) The requirements of this section shall apply only to those portions of a contractor\u2019s operations that occur under any of the following conditions:\\n(A) Within the state.\\n(B) On real property outside the state if the property is owned by the state or if the state has a right to occupy the property, and if the contractor\u2019s presence at that location is connected to a contract with the state.\\n(C) Elsewhere in the United States where work related to a state contract is being performed.\\n(b) Contractors shall treat as confidential, to the maximum extent allowed by law or by the requirement of the contractor\u2019s insurance provider, any request by an employee or applicant for employment benefits or any documentation of eligibility for benefits submitted by an employee or applicant for employment.\\n(c) After taking all reasonable measures to find a contractor that complies with this section, as determined by the state agency, the requirements of this section may be waived under any of the following circumstances:\\n(1) There is only one prospective contractor willing to enter into a specific contract with the state agency.\\n(2) The contract is necessary to respond to an emergency, as determined by the state agency, that endangers the public health, welfare, or safety, or the contract is necessary for the provision of essential services, and no entity that complies with the requirements of this section capable of responding to the emergency is immediately available.\\n(3) The requirements of this section violate, or are inconsistent with, the terms or conditions of a grant, subvention, or agreement, if the agency has made a good faith attempt to change the terms or conditions of any grant, subvention, or agreement to authorize application of this section.\\n(4) The contractor is providing wholesale or bulk water, power, or natural gas, the conveyance or transmission of the same, or ancillary services, as required for ensuring reliable services in accordance with good utility practice, if the purchase of the same cannot practically be accomplished through the standard competitive bidding procedures and the contractor is not providing direct retail services to end users.\\n(d) (1) A contractor shall not be deemed to discriminate in the provision of benefits if the contractor, in providing the benefits, pays the actual costs incurred in obtaining the benefit.\\n(2) If a contractor is unable to provide a certain benefit, despite taking reasonable measures to do so, the contractor shall not be deemed to discriminate in the provision of benefits.\\n(e) (1) Every contract subject to this chapter shall contain a statement by which the contractor certifies that the contractor is in compliance with this section.\\n(2) The department or other contracting agency shall enforce this section pursuant to its existing enforcement powers.\\n(3) (A) If a contractor falsely certifies that it is in compliance with this section, the contract with that contractor shall be subject to Article 9 (commencing with Section 10420), unless, within a time period specified by the department or other contracting agency, the contractor provides to the department or agency proof that it has complied, or is in the process of complying, with this section.\\n(B) The application of the remedies or penalties contained in Article 9 (commencing with Section 10420) to a contract subject to this chapter shall not preclude the application of any existing remedies otherwise available to the department or other contracting agency under its existing enforcement powers.\\n(f) Nothing in this section is intended to regulate the contracting practices of any local jurisdiction.\\n(g) This section shall be construed so as not to conflict with applicable federal laws, rules, or regulations. In the event that a court or agency of competent jurisdiction holds that federal law, rule, or regulation invalidates any clause, sentence, paragraph, or section of this code or the application thereof to any person or circumstances, it is the intent of the state that the court or agency sever that clause, sentence, paragraph, or section so that the remainder of this section shall remain in effect.\\nSEC. 2.\\nSection 10295.35 of the Public Contract Code shall not be construed to create any new enforcement authority or responsibility in the Department of General Services or any other contracting agency.\\nSEC. 3.\\nNo reimbursement is required by this act pursuant to Section 6 of Article XIII\\u2009B of the California Constitution because the only costs that may be incurred by a local agency or school district will be incurred because this act creates a new crime or infraction, eliminates a crime or infraction, or changes the penalty for a crime or infraction, within the meaning of Section 17556 of the Government Code, or changes the definition of a crime within the meaning of Section 6 of Article XIII\\u2009B of the California Constitution.',\n 'title': 'An act to add Section 10295.35 to the Public Contract Code, relating to public contracts.'}\n```", "source_file": "transformers/tasks/summarization.md", "section_heading": "Load BillSum dataset", "char_start": 1760, "char_end": 9405, "token_estimate": 1911, "prev_chunk_id": 235, "next_chunk_id": 237, "url": "https://huggingface.co/docs/transformers/tasks/summarization", "doc_title": "Summarization" }, { "chunk_id": 237, "text": "There are two fields that you'll want to use:\n\n- `text`: the text of the bill which'll be the input to the model.\n- `summary`: a condensed version of `text` which'll be the model target.", "source_file": "transformers/tasks/summarization.md", "section_heading": "Load BillSum dataset", "char_start": 9407, "char_end": 9593, "token_estimate": 46, "prev_chunk_id": 236, "next_chunk_id": 238, "url": "https://huggingface.co/docs/transformers/tasks/summarization", "doc_title": "Summarization" }, { "chunk_id": 238, "text": "## Preprocess\n\nThe next step is to load a T5 tokenizer to process `text` and `summary`:\n\n```py\n>>> from transformers import AutoTokenizer\n\n>>> checkpoint = \"google-t5/t5-small\"\n>>> tokenizer = AutoTokenizer.from_pretrained(checkpoint)\n```\n\nThe preprocessing function you want to create needs to:\n\n1. Prefix the input with a prompt so T5 knows this is a summarization task. Some models capable of multiple NLP tasks require prompting for specific tasks.\n2. Use the keyword `text_target` argument when tokenizing labels.\n3. Truncate sequences to be no longer than the maximum length set by the `max_length` parameter.\n\n```py\n>>> prefix = \"summarize: \"\n\n>>> def preprocess_function(examples):\n... inputs = [prefix + doc for doc in examples[\"text\"]]\n... model_inputs = tokenizer(inputs, max_length=1024, truncation=True)\n\n... labels = tokenizer(text_target=examples[\"summary\"], max_length=128, truncation=True)\n\n... model_inputs[\"labels\"] = labels[\"input_ids\"]\n... return model_inputs\n```", "source_file": "transformers/tasks/summarization.md", "section_heading": "Preprocess", "char_start": 9595, "char_end": 10599, "token_estimate": 251, "prev_chunk_id": 237, "next_chunk_id": 239, "url": "https://huggingface.co/docs/transformers/tasks/summarization", "doc_title": "Summarization" }, { "chunk_id": 239, "text": "To apply the preprocessing function over the entire dataset, use \ud83e\udd17 Datasets [map](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) method. You can speed up the `map` function by setting `batched=True` to process multiple elements of the dataset at once:\n\n```py\n>>> tokenized_billsum = billsum.map(preprocess_function, batched=True)\n```\n\nNow create a batch of examples using [DataCollatorForSeq2Seq](/docs/transformers/v5.6.2/en/main_classes/data_collator#transformers.DataCollatorForSeq2Seq). It's more efficient to *dynamically pad* the sentences to the longest length in a batch during collation, instead of padding the whole dataset to the maximum length.\n\n```py\n>>> from transformers import DataCollatorForSeq2Seq\n\n>>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint)\n```", "source_file": "transformers/tasks/summarization.md", "section_heading": "Preprocess", "char_start": 10601, "char_end": 11456, "token_estimate": 213, "prev_chunk_id": 238, "next_chunk_id": 240, "url": "https://huggingface.co/docs/transformers/tasks/summarization", "doc_title": "Summarization" }, { "chunk_id": 240, "text": "## Evaluate\n\nIncluding a metric during training is often helpful for evaluating your model's performance. You can quickly load a evaluation method with the \ud83e\udd17 [Evaluate](https://huggingface.co/docs/evaluate/index) library. For this task, load the [ROUGE](https://huggingface.co/spaces/evaluate-metric/rouge) metric (see the \ud83e\udd17 Evaluate [quick tour](https://huggingface.co/docs/evaluate/a_quick_tour) to learn more about how to load and compute a metric):\n\n```py\n>>> import evaluate\n\n>>> rouge = evaluate.load(\"rouge\")\n```\n\nThen create a function that passes your predictions and labels to [compute](https://huggingface.co/docs/evaluate/v0.4.6/en/package_reference/main_classes#evaluate.EvaluationModule.compute) to calculate the ROUGE metric:", "source_file": "transformers/tasks/summarization.md", "section_heading": "Evaluate", "char_start": 11458, "char_end": 12198, "token_estimate": 185, "prev_chunk_id": 239, "next_chunk_id": 241, "url": "https://huggingface.co/docs/transformers/tasks/summarization", "doc_title": "Summarization" }, { "chunk_id": 241, "text": "```py\n>>> import numpy as np\n\n>>> def compute_metrics(eval_pred):\n... predictions, labels = eval_pred\n... decoded_preds = tokenizer.batch_decode(predictions, skip_special_tokens=True)\n... labels = np.where(labels != -100, labels, tokenizer.pad_token_id)\n... decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)\n\n... result = rouge.compute(predictions=decoded_preds, references=decoded_labels, use_stemmer=True)\n\n... prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in predictions]\n... result[\"gen_len\"] = np.mean(prediction_lens)\n\n... return {k: round(v, 4) for k, v in result.items()}\n```\n\nYour `compute_metrics` function is ready to go now, and you'll return to it when you setup your training.", "source_file": "transformers/tasks/summarization.md", "section_heading": "Evaluate", "char_start": 12200, "char_end": 12977, "token_estimate": 194, "prev_chunk_id": 240, "next_chunk_id": 242, "url": "https://huggingface.co/docs/transformers/tasks/summarization", "doc_title": "Summarization" }, { "chunk_id": 242, "text": "## Train\n\nIf you aren't familiar with finetuning a model with the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer), take a look at the basic tutorial [here](../training#train-with-pytorch-trainer)!\n\nYou're ready to start training your model now! Load T5 with [AutoModelForSeq2SeqLM](/docs/transformers/v5.6.2/en/model_doc/auto#transformers.AutoModelForSeq2SeqLM):\n\n```py\n>>> from transformers import AutoModelForSeq2SeqLM, Seq2SeqTrainingArguments, Seq2SeqTrainer\n\n>>> model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint)\n```\n\nAt this point, only three steps remain:", "source_file": "transformers/tasks/summarization.md", "section_heading": "Train", "char_start": 12979, "char_end": 13583, "token_estimate": 151, "prev_chunk_id": 241, "next_chunk_id": 243, "url": "https://huggingface.co/docs/transformers/tasks/summarization", "doc_title": "Summarization" }, { "chunk_id": 243, "text": "1. Define your training hyperparameters in [Seq2SeqTrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Seq2SeqTrainingArguments). The only required parameter is `output_dir` which specifies where to save your model. You'll push this model to the Hub by setting `push_to_hub=True` (you need to be signed in to Hugging Face to upload your model). At the end of each epoch, the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) will evaluate the ROUGE metric and save the training checkpoint.\n2. Pass the training arguments to [Seq2SeqTrainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Seq2SeqTrainer) along with the model, dataset, tokenizer, data collator, and `compute_metrics` function.\n3. Call [train()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.train) to finetune your model.", "source_file": "transformers/tasks/summarization.md", "section_heading": "Train", "char_start": 13585, "char_end": 14475, "token_estimate": 222, "prev_chunk_id": 242, "next_chunk_id": 244, "url": "https://huggingface.co/docs/transformers/tasks/summarization", "doc_title": "Summarization" }, { "chunk_id": 244, "text": "```py\n>>> training_args = Seq2SeqTrainingArguments(\n... output_dir=\"my_awesome_billsum_model\",\n... eval_strategy=\"epoch\",\n... learning_rate=2e-5,\n... per_device_train_batch_size=16,\n... per_device_eval_batch_size=16,\n... weight_decay=0.01,\n... save_total_limit=3,\n... num_train_epochs=4,\n... predict_with_generate=True,\n... fp16=True, #change to bf16=True for XPU\n... push_to_hub=True,\n... )\n\n>>> trainer = Seq2SeqTrainer(\n... model=model,\n... args=training_args,\n... train_dataset=tokenized_billsum[\"train\"],\n... eval_dataset=tokenized_billsum[\"test\"],\n... processing_class=tokenizer,\n... data_collator=data_collator,\n... compute_metrics=compute_metrics,\n... )\n\n>>> trainer.train()\n```\n\nOnce training is completed, share your model to the Hub with the [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.push_to_hub) method so everyone can use your model:\n\n```py\n>>> trainer.push_to_hub()\n```", "source_file": "transformers/tasks/summarization.md", "section_heading": "Train", "char_start": 14477, "char_end": 15477, "token_estimate": 250, "prev_chunk_id": 243, "next_chunk_id": 245, "url": "https://huggingface.co/docs/transformers/tasks/summarization", "doc_title": "Summarization" }, { "chunk_id": 245, "text": "For a more in-depth example of how to finetune a model for summarization, take a look at the corresponding\n[PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization.ipynb).", "source_file": "transformers/tasks/summarization.md", "section_heading": "Train", "char_start": 15479, "char_end": 15708, "token_estimate": 57, "prev_chunk_id": 244, "next_chunk_id": 246, "url": "https://huggingface.co/docs/transformers/tasks/summarization", "doc_title": "Summarization" }, { "chunk_id": 246, "text": "## Inference\n\nGreat, now that you've finetuned a model, you can use it for inference!\n\nCome up with some text you'd like to summarize. For T5, you need to prefix your input depending on the task you're working on. For summarization you should prefix your input as shown below:\n\n```py\n>>> text = \"summarize: The Inflation Reduction Act lowers prescription drug costs, health care costs, and energy costs. It's the most aggressive action on tackling the climate crisis in American history, which will lift up American workers and create good-paying, union jobs across the country. It'll lower the deficit and ask the ultra-wealthy and corporations to pay their fair share. And no one making under $400,000 per year will pay a penny more in taxes.\"\n```\n\nTokenize the text and return the `input_ids` as PyTorch tensors:\n\n```py\n>>> from transformers import AutoTokenizer\n\n>>> tokenizer = AutoTokenizer.from_pretrained(\"username/my_awesome_billsum_model\")\n>>> inputs = tokenizer(text, return_tensors=\"pt\").input_ids\n```", "source_file": "transformers/tasks/summarization.md", "section_heading": "Inference", "char_start": 15710, "char_end": 16723, "token_estimate": 253, "prev_chunk_id": 245, "next_chunk_id": 247, "url": "https://huggingface.co/docs/transformers/tasks/summarization", "doc_title": "Summarization" }, { "chunk_id": 247, "text": "Use the [generate()](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationMixin.generate) method to create the summarization. For more details about the different text generation strategies and parameters for controlling generation, check out the [Text Generation](../main_classes/text_generation) API.\n\n```py\n>>> from transformers import AutoModelForSeq2SeqLM\n\n>>> model = AutoModelForSeq2SeqLM.from_pretrained(\"username/my_awesome_billsum_model\")\n>>> outputs = model.generate(inputs, max_new_tokens=100, do_sample=False)\n```\n\nDecode the generated token ids back into text:\n\n```py\n>>> tokenizer.decode(outputs[0], skip_special_tokens=True)\n'the inflation reduction act lowers prescription drug costs, health care costs, and energy costs. it's the most aggressive action on tackling the climate crisis in american history. it will ask the ultra-wealthy and corporations to pay their fair share.'\n```", "source_file": "transformers/tasks/summarization.md", "section_heading": "Inference", "char_start": 16725, "char_end": 17652, "token_estimate": 231, "prev_chunk_id": 246, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/tasks/summarization", "doc_title": "Summarization" }, { "chunk_id": 248, "text": "# Translation\n\nTranslation converts a sequence of text from one language to another. It is one of several tasks you can formulate as a sequence-to-sequence problem, a powerful framework for returning some output from an input, like translation or summarization. Translation systems are commonly used for translation between different language texts, but it can also be used for speech or some combination in between like text-to-speech or speech-to-text.\n\nThis guide will show you how to:\n\n1. Finetune [T5](https://huggingface.co/google-t5/t5-small) on the English-French subset of the [OPUS Books](https://huggingface.co/datasets/opus_books) dataset to translate English text to French.\n2. Use your finetuned model for inference.\n\nTo see all architectures and checkpoints compatible with this task, we recommend checking the [task-page](https://huggingface.co/tasks/translation).\n\nBefore you begin, make sure you have all the necessary libraries installed:\n\n```bash\npip install transformers datasets evaluate sacrebleu\n```", "source_file": "transformers/tasks/translation.md", "section_heading": "Translation", "char_start": 0, "char_end": 1023, "token_estimate": 255, "prev_chunk_id": null, "next_chunk_id": 249, "url": "https://huggingface.co/docs/transformers/tasks/translation", "doc_title": "Translation" }, { "chunk_id": 249, "text": "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:\n\n```py\n>>> from huggingface_hub import notebook_login\n\n>>> notebook_login()\n```", "source_file": "transformers/tasks/translation.md", "section_heading": "Translation", "char_start": 1025, "char_end": 1260, "token_estimate": 58, "prev_chunk_id": 248, "next_chunk_id": 250, "url": "https://huggingface.co/docs/transformers/tasks/translation", "doc_title": "Translation" }, { "chunk_id": 250, "text": "## Load OPUS Books dataset\n\nStart by loading the English-French subset of the [OPUS Books](https://huggingface.co/datasets/opus_books) dataset from the \ud83e\udd17 Datasets library:\n\n```py\n>>> from datasets import load_dataset\n\n>>> books = load_dataset(\"opus_books\", \"en-fr\")\n```\n\nSplit the dataset into a train and test set with the [train_test_split](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.train_test_split) method:\n\n```py\n>>> books = books[\"train\"].train_test_split(test_size=0.2)\n```\n\nThen take a look at an example:\n\n```py\n>>> books[\"train\"][0]\n{'id': '90560',\n 'translation': {'en': 'But this lofty plateau measured only a few fathoms, and soon we reentered Our Element.',\n 'fr': 'Mais ce plateau \u00e9lev\u00e9 ne mesurait que quelques toises, et bient\u00f4t nous f\u00fbmes rentr\u00e9s dans notre \u00e9l\u00e9ment.'}}\n```\n\n`translation`: an English and French translation of the text.", "source_file": "transformers/tasks/translation.md", "section_heading": "Load OPUS Books dataset", "char_start": 1262, "char_end": 2170, "token_estimate": 227, "prev_chunk_id": 249, "next_chunk_id": 251, "url": "https://huggingface.co/docs/transformers/tasks/translation", "doc_title": "Translation" }, { "chunk_id": 251, "text": "## Preprocess\n\nThe next step is to load a T5 tokenizer to process the English-French language pairs:\n\n```py\n>>> from transformers import AutoTokenizer\n\n>>> checkpoint = \"google-t5/t5-small\"\n>>> tokenizer = AutoTokenizer.from_pretrained(checkpoint)\n```\n\nThe preprocessing function you want to create needs to:\n\n1. Prefix the input with a prompt so T5 knows this is a translation task. Some models capable of multiple NLP tasks require prompting for specific tasks.\n2. Set the target language (French) in the `text_target` parameter to ensure the tokenizer processes the target text correctly. If you don't set `text_target`, the tokenizer processes the target text as English.\n3. Truncate sequences to be no longer than the maximum length set by the `max_length` parameter.", "source_file": "transformers/tasks/translation.md", "section_heading": "Preprocess", "char_start": 2172, "char_end": 2944, "token_estimate": 193, "prev_chunk_id": 250, "next_chunk_id": 252, "url": "https://huggingface.co/docs/transformers/tasks/translation", "doc_title": "Translation" }, { "chunk_id": 252, "text": "```py\n>>> source_lang = \"en\"\n>>> target_lang = \"fr\"\n>>> prefix = \"translate English to French: \"\n\n>>> def preprocess_function(examples):\n... inputs = [prefix + example[source_lang] for example in examples[\"translation\"]]\n... targets = [example[target_lang] for example in examples[\"translation\"]]\n... model_inputs = tokenizer(inputs, text_target=targets, max_length=128, truncation=True)\n... return model_inputs\n```\n\nTo apply the preprocessing function over the entire dataset, use \ud83e\udd17 Datasets [map](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) method. You can speed up the `map` function by setting `batched=True` to process multiple elements of the dataset at once:\n\n```py\n>>> tokenized_books = books.map(preprocess_function, batched=True)\n```", "source_file": "transformers/tasks/translation.md", "section_heading": "Preprocess", "char_start": 2946, "char_end": 3761, "token_estimate": 203, "prev_chunk_id": 251, "next_chunk_id": 253, "url": "https://huggingface.co/docs/transformers/tasks/translation", "doc_title": "Translation" }, { "chunk_id": 253, "text": "Now create a batch of examples using [DataCollatorForSeq2Seq](/docs/transformers/v5.6.2/en/main_classes/data_collator#transformers.DataCollatorForSeq2Seq). It's more efficient to *dynamically pad* the sentences to the longest length in a batch during collation, instead of padding the whole dataset to the maximum length.\n\n```py\n>>> from transformers import DataCollatorForSeq2Seq\n\n>>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint)\n```", "source_file": "transformers/tasks/translation.md", "section_heading": "Preprocess", "char_start": 3763, "char_end": 4230, "token_estimate": 116, "prev_chunk_id": 252, "next_chunk_id": 254, "url": "https://huggingface.co/docs/transformers/tasks/translation", "doc_title": "Translation" }, { "chunk_id": 254, "text": "## Evaluate\n\nIncluding a metric during training is often helpful for evaluating your model's performance. You can quickly load a evaluation method with the \ud83e\udd17 [Evaluate](https://huggingface.co/docs/evaluate/index) library. For this task, load the [SacreBLEU](https://huggingface.co/spaces/evaluate-metric/sacrebleu) metric (see the \ud83e\udd17 Evaluate [quick tour](https://huggingface.co/docs/evaluate/a_quick_tour) to learn more about how to load and compute a metric):\n\n```py\n>>> import evaluate\n\n>>> metric = evaluate.load(\"sacrebleu\")\n```\n\nThen create a function that passes your predictions and labels to [compute](https://huggingface.co/docs/evaluate/v0.4.6/en/package_reference/main_classes#evaluate.EvaluationModule.compute) to calculate the SacreBLEU score:", "source_file": "transformers/tasks/translation.md", "section_heading": "Evaluate", "char_start": 4232, "char_end": 4988, "token_estimate": 189, "prev_chunk_id": 253, "next_chunk_id": 255, "url": "https://huggingface.co/docs/transformers/tasks/translation", "doc_title": "Translation" }, { "chunk_id": 255, "text": "```py\n>>> import numpy as np\n\n>>> def postprocess_text(preds, labels):\n... preds = [pred.strip() for pred in preds]\n... labels = [[label.strip()] for label in labels]\n\n... return preds, labels\n\n>>> def compute_metrics(eval_preds):\n... preds, labels = eval_preds\n... if isinstance(preds, tuple):\n... preds = preds[0]\n... decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)\n\n... labels = np.where(labels != -100, labels, tokenizer.pad_token_id)\n... decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)\n\n... decoded_preds, decoded_labels = postprocess_text(decoded_preds, decoded_labels)\n\n... result = metric.compute(predictions=decoded_preds, references=decoded_labels)\n... result = {\"bleu\": result[\"score\"]}\n\n... prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in preds]\n... result[\"gen_len\"] = np.mean(prediction_lens)\n... result = {k: round(v, 4) for k, v in result.items()}\n... return result\n```", "source_file": "transformers/tasks/translation.md", "section_heading": "Evaluate", "char_start": 4990, "char_end": 6025, "token_estimate": 258, "prev_chunk_id": 254, "next_chunk_id": 256, "url": "https://huggingface.co/docs/transformers/tasks/translation", "doc_title": "Translation" }, { "chunk_id": 256, "text": "Your `compute_metrics` function is ready to go now, and you'll return to it when you setup your training.", "source_file": "transformers/tasks/translation.md", "section_heading": "Evaluate", "char_start": 6027, "char_end": 6132, "token_estimate": 26, "prev_chunk_id": 255, "next_chunk_id": 257, "url": "https://huggingface.co/docs/transformers/tasks/translation", "doc_title": "Translation" }, { "chunk_id": 257, "text": "## Train\n\nIf you aren't familiar with finetuning a model with the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer), take a look at the basic tutorial [here](../training#train-with-pytorch-trainer)!\n\nYou're ready to start training your model now! Load T5 with [AutoModelForSeq2SeqLM](/docs/transformers/v5.6.2/en/model_doc/auto#transformers.AutoModelForSeq2SeqLM):\n\n```py\n>>> from transformers import AutoModelForSeq2SeqLM, Seq2SeqTrainingArguments, Seq2SeqTrainer\n\n>>> model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint)\n```\n\nAt this point, only three steps remain:", "source_file": "transformers/tasks/translation.md", "section_heading": "Train", "char_start": 6134, "char_end": 6738, "token_estimate": 151, "prev_chunk_id": 256, "next_chunk_id": 258, "url": "https://huggingface.co/docs/transformers/tasks/translation", "doc_title": "Translation" }, { "chunk_id": 258, "text": "1. Define your training hyperparameters in [Seq2SeqTrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Seq2SeqTrainingArguments). The only required parameter is `output_dir` which specifies where to save your model. You'll push this model to the Hub by setting `push_to_hub=True` (you need to be signed in to Hugging Face to upload your model). At the end of each epoch, the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) will evaluate the SacreBLEU metric and save the training checkpoint.\n2. Pass the training arguments to [Seq2SeqTrainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Seq2SeqTrainer) along with the model, dataset, tokenizer, data collator, and `compute_metrics` function.\n3. Call [train()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.train) to finetune your model.", "source_file": "transformers/tasks/translation.md", "section_heading": "Train", "char_start": 6740, "char_end": 7634, "token_estimate": 223, "prev_chunk_id": 257, "next_chunk_id": 259, "url": "https://huggingface.co/docs/transformers/tasks/translation", "doc_title": "Translation" }, { "chunk_id": 259, "text": "```py\n>>> training_args = Seq2SeqTrainingArguments(\n... output_dir=\"my_awesome_opus_books_model\",\n... eval_strategy=\"epoch\",\n... learning_rate=2e-5,\n... per_device_train_batch_size=16,\n... per_device_eval_batch_size=16,\n... weight_decay=0.01,\n... save_total_limit=3,\n... num_train_epochs=2,\n... predict_with_generate=True,\n... fp16=True, #change to bf16=True for XPU\n... push_to_hub=True,\n... )\n\n>>> trainer = Seq2SeqTrainer(\n... model=model,\n... args=training_args,\n... train_dataset=tokenized_books[\"train\"],\n... eval_dataset=tokenized_books[\"test\"],\n... processing_class=tokenizer,\n... data_collator=data_collator,\n... compute_metrics=compute_metrics,\n... )\n\n>>> trainer.train()\n```\n\nOnce training is completed, share your model to the Hub with the [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.push_to_hub) method so everyone can use your model:\n\n```py\n>>> trainer.push_to_hub()\n```", "source_file": "transformers/tasks/translation.md", "section_heading": "Train", "char_start": 7636, "char_end": 8635, "token_estimate": 249, "prev_chunk_id": 258, "next_chunk_id": 260, "url": "https://huggingface.co/docs/transformers/tasks/translation", "doc_title": "Translation" }, { "chunk_id": 260, "text": "For a more in-depth example of how to finetune a model for translation, take a look at the corresponding\n[PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/translation.ipynb).", "source_file": "transformers/tasks/translation.md", "section_heading": "Train", "char_start": 8637, "char_end": 8862, "token_estimate": 56, "prev_chunk_id": 259, "next_chunk_id": 261, "url": "https://huggingface.co/docs/transformers/tasks/translation", "doc_title": "Translation" }, { "chunk_id": 261, "text": "## Inference\n\nGreat, now that you've finetuned a model, you can use it for inference!\n\nCome up with some text you'd like to translate to another language. For T5, you need to prefix your input depending on the task you're working on. For translation from English to French, you should prefix your input as shown below:\n\n```py\n>>> text = \"translate English to French: Legumes share resources with nitrogen-fixing bacteria.\"\n```\n\nTokenize the text and return the `input_ids` as PyTorch tensors:\n\n```py\n>>> from transformers import AutoTokenizer\n\n>>> tokenizer = AutoTokenizer.from_pretrained(\"username/my_awesome_opus_books_model\")\n>>> inputs = tokenizer(text, return_tensors=\"pt\").input_ids\n```\n\nUse the [generate()](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationMixin.generate) method to create the translation. For more details about the different text generation strategies and parameters for controlling generation, check out the [Text Generation](../main_classes/text_generation) API.", "source_file": "transformers/tasks/translation.md", "section_heading": "Inference", "char_start": 8864, "char_end": 9887, "token_estimate": 255, "prev_chunk_id": 260, "next_chunk_id": 262, "url": "https://huggingface.co/docs/transformers/tasks/translation", "doc_title": "Translation" }, { "chunk_id": 262, "text": "```py\n>>> from transformers import AutoModelForSeq2SeqLM\n\n>>> model = AutoModelForSeq2SeqLM.from_pretrained(\"username/my_awesome_opus_books_model\")\n>>> outputs = model.generate(inputs, max_new_tokens=40, do_sample=True, top_k=30, top_p=0.95)\n```\n\nDecode the generated token ids back into text:\n\n```py\n>>> tokenizer.decode(outputs[0], skip_special_tokens=True)\n'Les lign\u00e9es partagent des ressources avec des bact\u00e9ries enfixant l'azote.'\n```", "source_file": "transformers/tasks/translation.md", "section_heading": "Inference", "char_start": 9889, "char_end": 10328, "token_estimate": 109, "prev_chunk_id": 261, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/tasks/translation", "doc_title": "Translation" }, { "chunk_id": 263, "text": "# Image classification\n\nImage classification assigns a label or class to an image. Unlike text or audio classification, the inputs are the\npixel values that comprise an image. There are many applications for image classification, such as detecting damage\nafter a natural disaster, monitoring crop health, or helping screen medical images for signs of disease.\n\nThis guide illustrates how to:\n\n1. Fine-tune [ViT](../model_doc/vit) on the [Food-101](https://huggingface.co/datasets/ethz/food101) dataset to classify a food item in an image.\n2. Use your fine-tuned model for inference.\n\nTo see all architectures and checkpoints compatible with this task, we recommend checking the [task-page](https://huggingface.co/tasks/image-classification)\n\nBefore you begin, make sure you have all the necessary libraries installed:\n\n```bash\npip install transformers datasets evaluate accelerate pillow torchvision scikit-learn trackio\n```", "source_file": "transformers/tasks/image_classification.md", "section_heading": "Image classification", "char_start": 0, "char_end": 924, "token_estimate": 231, "prev_chunk_id": null, "next_chunk_id": 264, "url": "https://huggingface.co/docs/transformers/tasks/image_classification", "doc_title": "Image classification" }, { "chunk_id": 264, "text": "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:\n\n```py\n>>> from huggingface_hub import notebook_login\n\n>>> notebook_login()\n```", "source_file": "transformers/tasks/image_classification.md", "section_heading": "Image classification", "char_start": 926, "char_end": 1155, "token_estimate": 57, "prev_chunk_id": 263, "next_chunk_id": 265, "url": "https://huggingface.co/docs/transformers/tasks/image_classification", "doc_title": "Image classification" }, { "chunk_id": 265, "text": "## Load Food-101 dataset\n\nStart by loading a smaller subset of the Food-101 dataset from the \ud83e\udd17 Datasets library. This will give you a chance to\nexperiment and make sure everything works before spending more time training on the full dataset.\n\n```py\n>>> from datasets import load_dataset\n\n>>> food = load_dataset(\"ethz/food101\", split=\"train[:5000]\")\n```\n\nSplit the dataset's `train` split into a train and test set with the [train_test_split](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.train_test_split) method:\n\n```py\n>>> food = food.train_test_split(test_size=0.2)\n```\n\nThen take a look at an example:\n\n```py\n>>> food[\"train\"][0]\n{'image': ,\n 'label': 79}\n```\n\nEach example in the dataset has two fields:\n\n- `image`: a PIL image of the food item\n- `label`: the label class of the food item\n\nTo make it easier for the model to get the label name from the label id, create a dictionary that maps the label name\nto an integer and vice versa:", "source_file": "transformers/tasks/image_classification.md", "section_heading": "Load Food-101 dataset", "char_start": 1157, "char_end": 2149, "token_estimate": 248, "prev_chunk_id": 264, "next_chunk_id": 266, "url": "https://huggingface.co/docs/transformers/tasks/image_classification", "doc_title": "Image classification" }, { "chunk_id": 266, "text": "```py\n>>> labels = food[\"train\"].features[\"label\"].names\n>>> label2id, id2label = dict(), dict()\n>>> for i, label in enumerate(labels):\n... label2id[label] = str(i)\n... id2label[str(i)] = label\n```\n\nNow you can convert the label id to a label name:\n\n```py\n>>> id2label[str(79)]\n'prime_rib'\n```", "source_file": "transformers/tasks/image_classification.md", "section_heading": "Load Food-101 dataset", "char_start": 2151, "char_end": 2452, "token_estimate": 75, "prev_chunk_id": 265, "next_chunk_id": 267, "url": "https://huggingface.co/docs/transformers/tasks/image_classification", "doc_title": "Image classification" }, { "chunk_id": 267, "text": "## Preprocess\n\nThe next step is to load a ViT image processor to process the image into a tensor:\n\n```py\n>>> from transformers import AutoImageProcessor\n\n>>> checkpoint = \"google/vit-base-patch16-224-in21k\"\n>>> image_processor = AutoImageProcessor.from_pretrained(checkpoint)\n```\n\nApply some image transformations to the images to make the model more robust against overfitting. Here you'll use torchvision's [`transforms`](https://pytorch.org/vision/stable/transforms.html) module, but you can also use any image library you like.\n\nCrop a random part of the image, resize it, and normalize it with the image mean and standard deviation:", "source_file": "transformers/tasks/image_classification.md", "section_heading": "Preprocess", "char_start": 2454, "char_end": 3091, "token_estimate": 159, "prev_chunk_id": 266, "next_chunk_id": 268, "url": "https://huggingface.co/docs/transformers/tasks/image_classification", "doc_title": "Image classification" }, { "chunk_id": 268, "text": "```py\n>>> from torchvision.transforms import RandomResizedCrop, Compose, Normalize, ToTensor\n\n>>> normalize = Normalize(mean=image_processor.image_mean, std=image_processor.image_std)\n>>> size = (\n... image_processor.size[\"shortest_edge\"]\n... if \"shortest_edge\" in image_processor.size\n... else (image_processor.size[\"height\"], image_processor.size[\"width\"])\n... )\n>>> _transforms = Compose([RandomResizedCrop(size), ToTensor(), normalize])\n```\n\nThen create a preprocessing function to apply the transforms and return the `pixel_values` - the inputs to the model - of the image:\n\n```py\n>>> def transforms(examples):\n... examples[\"pixel_values\"] = [_transforms(img.convert(\"RGB\")) for img in examples[\"image\"]]\n... del examples[\"image\"]\n... return examples\n```", "source_file": "transformers/tasks/image_classification.md", "section_heading": "Preprocess", "char_start": 3093, "char_end": 3876, "token_estimate": 195, "prev_chunk_id": 267, "next_chunk_id": 269, "url": "https://huggingface.co/docs/transformers/tasks/image_classification", "doc_title": "Image classification" }, { "chunk_id": 269, "text": "To apply the preprocessing function over the entire dataset, use \ud83e\udd17 Datasets [with_transform](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.with_transform) method. The transforms are applied on the fly when you load an element of the dataset:\n\n```py\n>>> food = food.with_transform(transforms)\n```\n\nNow create a batch of examples using [DefaultDataCollator](/docs/transformers/v5.6.2/en/main_classes/data_collator#transformers.DefaultDataCollator). Unlike other data collators in \ud83e\udd17 Transformers, the `DefaultDataCollator` does not apply additional preprocessing such as padding.\n\n```py\n>>> from transformers import DefaultDataCollator\n\n>>> data_collator = DefaultDataCollator()\n```", "source_file": "transformers/tasks/image_classification.md", "section_heading": "Preprocess", "char_start": 3878, "char_end": 4606, "token_estimate": 182, "prev_chunk_id": 268, "next_chunk_id": 270, "url": "https://huggingface.co/docs/transformers/tasks/image_classification", "doc_title": "Image classification" }, { "chunk_id": 270, "text": "## Evaluate\n\nIncluding a metric during training is often helpful for evaluating your model's performance. You can quickly load an\nevaluation method with the \ud83e\udd17 [Evaluate](https://huggingface.co/docs/evaluate/index) library. For this task, load\nthe [accuracy](https://huggingface.co/spaces/evaluate-metric/accuracy) metric (see the \ud83e\udd17 Evaluate [quick tour](https://huggingface.co/docs/evaluate/a_quick_tour) to learn more about how to load and compute a metric):\n\n```py\n>>> import evaluate\n\n>>> accuracy = evaluate.load(\"accuracy\")\n```\n\nThen create a function that passes your predictions and labels to [compute](https://huggingface.co/docs/evaluate/v0.4.6/en/package_reference/main_classes#evaluate.EvaluationModule.compute) to calculate the accuracy:\n\n```py\n>>> import numpy as np\n\n>>> def compute_metrics(eval_pred):\n... predictions, labels = eval_pred\n... predictions = np.argmax(predictions, axis=1)\n... return accuracy.compute(predictions=predictions, references=labels)\n```", "source_file": "transformers/tasks/image_classification.md", "section_heading": "Evaluate", "char_start": 4608, "char_end": 5597, "token_estimate": 247, "prev_chunk_id": 269, "next_chunk_id": 271, "url": "https://huggingface.co/docs/transformers/tasks/image_classification", "doc_title": "Image classification" }, { "chunk_id": 271, "text": "Your `compute_metrics` function is ready to go now, and you'll return to it when you set up your training.", "source_file": "transformers/tasks/image_classification.md", "section_heading": "Evaluate", "char_start": 5599, "char_end": 5705, "token_estimate": 26, "prev_chunk_id": 270, "next_chunk_id": 272, "url": "https://huggingface.co/docs/transformers/tasks/image_classification", "doc_title": "Image classification" }, { "chunk_id": 272, "text": "## Train\n\nIf you aren't familiar with finetuning a model with the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer), take a look at the basic tutorial [here](../training#train-with-pytorch-trainer)!\n\nYou're ready to start training your model now! Load ViT with [AutoModelForImageClassification](/docs/transformers/v5.6.2/en/model_doc/auto#transformers.AutoModelForImageClassification). Specify the number of labels along with the number of expected labels, and the label mappings:\n\n```py\n>>> from transformers import AutoModelForImageClassification, TrainingArguments, Trainer\n\n>>> model = AutoModelForImageClassification.from_pretrained(\n... checkpoint,\n... num_labels=len(labels),\n... id2label=id2label,\n... label2id=label2id,\n... )\n```\n\nAt this point, only three steps remain:", "source_file": "transformers/tasks/image_classification.md", "section_heading": "Train", "char_start": 5707, "char_end": 6534, "token_estimate": 206, "prev_chunk_id": 271, "next_chunk_id": 273, "url": "https://huggingface.co/docs/transformers/tasks/image_classification", "doc_title": "Image classification" }, { "chunk_id": 273, "text": "1. Define your training hyperparameters in [TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments). It is important you don't remove unused columns because that'll drop the `image` column. Without the `image` column, you can't create `pixel_values`. Set `remove_unused_columns=False` to prevent this behavior! The only other required parameter is `output_dir` which specifies where to save your model. You'll push this model to the Hub by setting `push_to_hub=True` (you need to be signed in to Hugging Face to upload your model). At the end of each epoch, the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) will evaluate the accuracy and save the training checkpoint.\n2. Pass the training arguments to [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) along with the model, dataset, tokenizer, data collator, and `compute_metrics` function.\n3. Call [train()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.train) to finetune your model.", "source_file": "transformers/tasks/image_classification.md", "section_heading": "Train", "char_start": 6536, "char_end": 7610, "token_estimate": 268, "prev_chunk_id": 272, "next_chunk_id": 274, "url": "https://huggingface.co/docs/transformers/tasks/image_classification", "doc_title": "Image classification" }, { "chunk_id": 274, "text": "```py\n>>> training_args = TrainingArguments(\n... output_dir=\"my_awesome_food_model\",\n... remove_unused_columns=False,\n... eval_strategy=\"epoch\",\n... save_strategy=\"epoch\",\n... learning_rate=5e-5,\n... per_device_train_batch_size=16,\n... gradient_accumulation_steps=4,\n... per_device_eval_batch_size=16,\n... num_train_epochs=3,\n... warmup_steps=0.1,\n... logging_steps=10,\n... report_to=\"trackio\",\n... run_name=\"food101\",\n... load_best_model_at_end=True,\n... metric_for_best_model=\"accuracy\",\n... push_to_hub=True,\n... )\n\n>>> trainer = Trainer(\n... model=model,\n... args=training_args,\n... data_collator=data_collator,\n... train_dataset=food[\"train\"],\n... eval_dataset=food[\"test\"],\n... processing_class=image_processor,\n... compute_metrics=compute_metrics,\n... )\n\n>>> trainer.train()\n```", "source_file": "transformers/tasks/image_classification.md", "section_heading": "Train", "char_start": 7612, "char_end": 8489, "token_estimate": 219, "prev_chunk_id": 273, "next_chunk_id": 275, "url": "https://huggingface.co/docs/transformers/tasks/image_classification", "doc_title": "Image classification" }, { "chunk_id": 275, "text": "Once training is completed, share your model to the Hub with the [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.push_to_hub) method so everyone can use your model:\n\n```py\n>>> trainer.push_to_hub()\n```\n\nFor a more in-depth example of how to finetune a model for image classification, take a look at the corresponding [PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb).", "source_file": "transformers/tasks/image_classification.md", "section_heading": "Train", "char_start": 8491, "char_end": 8976, "token_estimate": 121, "prev_chunk_id": 274, "next_chunk_id": 276, "url": "https://huggingface.co/docs/transformers/tasks/image_classification", "doc_title": "Image classification" }, { "chunk_id": 276, "text": "## Inference\n\nGreat, now that you've fine-tuned a model, you can use it for inference!\n\nLoad an image you'd like to run inference on:\n\n```py\n>>> ds = load_dataset(\"ethz/food101\", split=\"validation[:10]\")\n>>> image = ds[\"image\"][0]\n```\n\nThe simplest way to try out your finetuned model for inference is to use it in a [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline). Instantiate a `pipeline` for image classification with your model, and pass your image to it:\n\n```py\n>>> from transformers import pipeline\n\n>>> classifier = pipeline(\"image-classification\", model=\"my_awesome_food_model\")\n>>> classifier(image)\n[{'score': 0.31856709718704224, 'label': 'beignets'},\n {'score': 0.015232225880026817, 'label': 'bruschetta'},\n {'score': 0.01519392803311348, 'label': 'chicken_wings'},\n {'score': 0.013022331520915031, 'label': 'pork_chop'},\n {'score': 0.012728818692266941, 'label': 'prime_rib'}]\n```\n\nYou can also manually replicate the results of the `pipeline` if you'd like:", "source_file": "transformers/tasks/image_classification.md", "section_heading": "Inference", "char_start": 0, "char_end": 1012, "token_estimate": 253, "prev_chunk_id": 275, "next_chunk_id": 277, "url": "https://huggingface.co/docs/transformers/tasks/image_classification", "doc_title": "Image classification" }, { "chunk_id": 277, "text": "Load an image processor to preprocess the image and return the `input` as PyTorch tensors:\n\n```py\n>>> from transformers import AutoImageProcessor\n>>> import torch\n\n>>> image_processor = AutoImageProcessor.from_pretrained(\"my_awesome_food_model\")\n>>> inputs = image_processor(image, return_tensors=\"pt\")\n```\n\nPass your inputs to the model and return the logits:\n\n```py\n>>> from transformers import AutoModelForImageClassification\n\n>>> model = AutoModelForImageClassification.from_pretrained(\"my_awesome_food_model\")\n>>> with torch.no_grad():\n... logits = model(**inputs).logits\n```\n\nGet the predicted label with the highest probability, and use the model's `id2label` mapping to convert it to a label:\n\n```py\n>>> predicted_label = logits.argmax(-1).item()\n>>> model.config.id2label[predicted_label]\n'beignets'\n```", "source_file": "transformers/tasks/image_classification.md", "section_heading": "Inference", "char_start": 9998, "char_end": 10814, "token_estimate": 204, "prev_chunk_id": 276, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/tasks/image_classification", "doc_title": "Image classification" }, { "chunk_id": 278, "text": "# Object detection\n\nObject detection is the computer vision task of detecting instances (such as humans, buildings, or cars) in an image. Object detection models receive an image as input and output\ncoordinates of the bounding boxes and associated labels of the detected objects. An image can contain multiple objects,\neach with its own bounding box and a label (e.g. it can have a car and a building), and each object can\nbe present in different parts of an image (e.g. the image can have several cars).\nThis task is commonly used in autonomous driving for detecting things like pedestrians, road signs, and traffic lights.\nOther applications include counting objects in images, image search, and more.\n\nIn this guide, you will learn how to:\n\n 1. Finetune [DETR](https://huggingface.co/docs/transformers/model_doc/detr), a model that combines a convolutional\n backbone with an encoder-decoder Transformer, on the [CPPE-5](https://huggingface.co/datasets/cppe-5)\n dataset.\n 2. Use your finetuned model for inference.", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Object detection", "char_start": 0, "char_end": 1016, "token_estimate": 254, "prev_chunk_id": null, "next_chunk_id": 279, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 279, "text": "To see all architectures and checkpoints compatible with this task, we recommend checking the [task-page](https://huggingface.co/tasks/object-detection)\n\nBefore you begin, make sure you have all the necessary libraries installed:\n\n```bash\npip install -q datasets transformers accelerate timm trackio\npip install -q -U albumentations>=1.4.5 torchmetrics pycocotools\n```\n\nYou'll use \ud83e\udd17 Datasets to load a dataset from the Hugging Face Hub, \ud83e\udd17 Transformers to train your model,\nand `albumentations` to augment the data.\n\nWe encourage you to share your model with the community. Log in to your Hugging Face account to upload it to the Hub.\nWhen prompted, enter your token to log in:\n\n```py\n>>> from huggingface_hub import notebook_login\n\n>>> notebook_login()\n```\n\nTo get started, we'll define global constants, namely the model name and image size. For this tutorial, we'll use the conditional DETR model due to its faster convergence. Feel free to select any object detection model available in the `transformers` library.", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Object detection", "char_start": 1018, "char_end": 2035, "token_estimate": 254, "prev_chunk_id": 278, "next_chunk_id": 280, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 280, "text": "```py\n>>> MODEL_NAME = \"microsoft/conditional-detr-resnet-50\" # or \"facebook/detr-resnet-50\"\n>>> IMAGE_SIZE = 480\n```", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Object detection", "char_start": 2037, "char_end": 2155, "token_estimate": 29, "prev_chunk_id": 279, "next_chunk_id": 281, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 281, "text": "## Load the CPPE-5 dataset\n\nThe [CPPE-5 dataset](https://huggingface.co/datasets/cppe-5) contains images with\nannotations identifying medical personal protective equipment (PPE) in the context of the COVID-19 pandemic.\n\nStart by loading the dataset and creating a `validation` split from `train`:\n\n```py\n>>> from datasets import load_dataset\n\n>>> cppe5 = load_dataset(\"cppe-5\")\n\n>>> if \"validation\" not in cppe5:\n... split = cppe5[\"train\"].train_test_split(0.15, seed=1337)\n... cppe5[\"train\"] = split[\"train\"]\n... cppe5[\"validation\"] = split[\"test\"]\n\n>>> cppe5\nDatasetDict({\n train: Dataset({\n features: ['image_id', 'image', 'width', 'height', 'objects'],\n num_rows: 850\n })\n test: Dataset({\n features: ['image_id', 'image', 'width', 'height', 'objects'],\n num_rows: 29\n })\n validation: Dataset({\n features: ['image_id', 'image', 'width', 'height', 'objects'],\n num_rows: 150\n })\n})\n```", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Load the CPPE-5 dataset", "char_start": 2157, "char_end": 3116, "token_estimate": 239, "prev_chunk_id": 280, "next_chunk_id": 282, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 282, "text": "You'll see that this dataset has 1000 images for train and validation sets and a test set with 29 images.\n\nTo get familiar with the data, explore what the examples look like.\n\n```py\n>>> cppe5[\"train\"][0]\n{\n 'image_id': 366,\n 'image': ,\n 'width': 500,\n 'height': 500,\n 'objects': {\n 'id': [1932, 1933, 1934],\n 'area': [27063, 34200, 32431],\n 'bbox': [[29.0, 11.0, 97.0, 279.0],\n [201.0, 1.0, 120.0, 285.0],\n [382.0, 0.0, 113.0, 287.0]],\n 'category': [0, 0, 0]\n }\n}\n```\n\nThe examples in the dataset have the following fields:", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Load the CPPE-5 dataset", "char_start": 3118, "char_end": 3669, "token_estimate": 137, "prev_chunk_id": 281, "next_chunk_id": 283, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 283, "text": "- `image_id`: the example image id\n- `image`: a `PIL.Image.Image` object containing the image\n- `width`: width of the image\n- `height`: height of the image\n- `objects`: a dictionary containing bounding box metadata for the objects in the image:\n - `id`: the annotation id\n - `area`: the area of the bounding box\n - `bbox`: the object's bounding box (in the [COCO format](https://albumentations.ai/docs/getting_started/bounding_boxes_augmentation/#coco) )\n - `category`: the object's category, with possible values including `Coverall (0)`, `Face_Shield (1)`, `Gloves (2)`, `Goggles (3)` and `Mask (4)`\n\nYou may notice that the `bbox` field follows the COCO format, which is the format that the DETR model expects.\nHowever, the grouping of the fields inside `objects` differs from the annotation format DETR requires. You will\nneed to apply some preprocessing transformations before using this data for training.\n\nTo get an even better understanding of the data, visualize an example in the dataset.", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Load the CPPE-5 dataset", "char_start": 3671, "char_end": 4673, "token_estimate": 250, "prev_chunk_id": 282, "next_chunk_id": 284, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 284, "text": "```py\n>>> import numpy as np\n>>> import os\n>>> from PIL import Image, ImageDraw\n\n>>> image = cppe5[\"train\"][2][\"image\"]\n>>> annotations = cppe5[\"train\"][2][\"objects\"]\n>>> draw = ImageDraw.Draw(image)\n\n>>> categories = cppe5[\"train\"].features[\"objects\"][\"category\"].feature.names\n\n>>> id2label = {index: x for index, x in enumerate(categories, start=0)}\n>>> label2id = {v: k for k, v in id2label.items()}\n\n>>> for i in range(len(annotations[\"id\"])):\n... box = annotations[\"bbox\"][i]\n... class_idx = annotations[\"category\"][i]\n... x, y, w, h = tuple(box)\n... # Check if coordinates are normalized or not\n... if max(box) > 1.0:\n... # Coordinates are un-normalized, no need to re-scale them\n... x1, y1 = int(x), int(y)\n... x2, y2 = int(x + w), int(y + h)\n... else:\n... # Coordinates are normalized, re-scale them\n... x1 = int(x * width)\n... y1 = int(y * height)\n... x2 = int((x + w) * width)\n... y2 = int((y + h) * height)\n... draw.rectangle((x, y, x + w, y + h), outline=\"red\", width=1)\n... draw.text((x, y), id2label[class_idx], fill=\"white\")\n\n>>> image\n```", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Load the CPPE-5 dataset", "char_start": 4675, "char_end": 5826, "token_estimate": 287, "prev_chunk_id": 283, "next_chunk_id": 285, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 285, "text": "To visualize the bounding boxes with associated labels, you can get the labels from the dataset's metadata, specifically\nthe `category` field.\nYou'll also want to create dictionaries that map a label id to a label class (`id2label`) and the other way around (`label2id`).\nYou can use them later when setting up the model. Including these maps will make your model reusable by others if you share\nit on the Hugging Face Hub. Please note that, the part of above code that draws the bounding boxes assume that it is in `COCO` format `(x_min, y_min, width, height)`. It has to be adjusted to work for other formats like `(x_min, y_min, x_max, y_max)`.", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Load the CPPE-5 dataset", "char_start": 5834, "char_end": 6481, "token_estimate": 161, "prev_chunk_id": 284, "next_chunk_id": 286, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 286, "text": "As a final step of getting familiar with the data, explore it for potential issues. One common problem with datasets for\nobject detection is bounding boxes that \"stretch\" beyond the edge of the image. Such \"runaway\" bounding boxes can raise\nerrors during training and should be addressed. There are a few examples with this issue in this dataset.\nTo keep things simple in this guide, we will set `clip=True` for `BboxParams` in transformations below.", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Load the CPPE-5 dataset", "char_start": 6483, "char_end": 6933, "token_estimate": 112, "prev_chunk_id": 285, "next_chunk_id": 287, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 287, "text": "## Preprocess the data\n\nTo finetune a model, you must preprocess the data you plan to use to match precisely the approach used for the pre-trained model.\n[AutoImageProcessor](/docs/transformers/v5.6.2/en/model_doc/auto#transformers.AutoImageProcessor) takes care of processing image data to create `pixel_values`, `pixel_mask`, and\n`labels` that a DETR model can train with. The image processor has some attributes that you won't have to worry about:\n\n- `image_mean = [0.485, 0.456, 0.406 ]`\n- `image_std = [0.229, 0.224, 0.225]`\n\nThese are the mean and standard deviation used to normalize images during the model pre-training. These values are crucial\nto replicate when doing inference or finetuning a pre-trained image model.\n\nInstantiate the image processor from the same checkpoint as the model you want to finetune.", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Preprocess the data", "char_start": 6935, "char_end": 7756, "token_estimate": 205, "prev_chunk_id": 286, "next_chunk_id": 288, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 288, "text": "```py\n>>> from transformers import AutoImageProcessor\n\n>>> MAX_SIZE = IMAGE_SIZE\n\n>>> image_processor = AutoImageProcessor.from_pretrained(\n... MODEL_NAME,\n... do_resize=True,\n... size={\"max_height\": MAX_SIZE, \"max_width\": MAX_SIZE},\n... do_pad=True,\n... pad_size={\"height\": MAX_SIZE, \"width\": MAX_SIZE},\n... )\n```\n\nBefore passing the images to the `image_processor`, apply two preprocessing transformations to the dataset:\n\n- Augmenting images\n- Reformatting annotations to meet DETR expectations", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Preprocess the data", "char_start": 7758, "char_end": 8275, "token_estimate": 129, "prev_chunk_id": 287, "next_chunk_id": 289, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 289, "text": "First, to make sure the model does not overfit on the training data, you can apply image augmentation with any data augmentation library. Here we use [Albumentations](https://albumentations.ai/docs/).\nThis library ensures that transformations affect the image and update the bounding boxes accordingly.\nThe \ud83e\udd17 Datasets library documentation has a detailed [guide on how to augment images for object detection](https://huggingface.co/docs/datasets/object_detection),\nand it uses the exact same dataset as an example. Apply some geometric and color transformations to the image. For additional augmentation options, explore the [Albumentations Demo Space](https://huggingface.co/spaces/qubvel-hf/albumentations-demo).", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Preprocess the data", "char_start": 8277, "char_end": 8991, "token_estimate": 178, "prev_chunk_id": 288, "next_chunk_id": 290, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 290, "text": "```py\n>>> import albumentations as A\n\n>>> train_augment_and_transform = A.Compose(\n... [\n... A.Perspective(p=0.1),\n... A.HorizontalFlip(p=0.5),\n... A.RandomBrightnessContrast(p=0.5),\n... A.HueSaturationValue(p=0.1),\n... ],\n... bbox_params=A.BboxParams(format=\"coco\", label_fields=[\"category\"], clip=True, min_area=25),\n... )\n\n>>> validation_transform = A.Compose(\n... [A.NoOp()],\n... bbox_params=A.BboxParams(format=\"coco\", label_fields=[\"category\"], clip=True),\n... )\n```\n\nThe `image_processor` expects the annotations to be in the following format: `{'image_id': int, 'annotations': list[Dict]}`,\n where each dictionary is a COCO object annotation. Let's add a function to reformat annotations for a single example:", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Preprocess the data", "char_start": 8993, "char_end": 9762, "token_estimate": 192, "prev_chunk_id": 289, "next_chunk_id": 291, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 291, "text": "```py\n>>> def format_image_annotations_as_coco(image_id, categories, areas, bboxes):\n... \"\"\"Format one set of image annotations to the COCO format\n\n... Args:\n... image_id (str): image id. e.g. \"0001\"\n... categories (list[int]): list of categories/class labels corresponding to provided bounding boxes\n... areas (list[float]): list of corresponding areas to provided bounding boxes\n... bboxes (list[tuple[float]]): list of bounding boxes provided in COCO format\n... ([center_x, center_y, width, height] in absolute coordinates)\n\n... Returns:\n... dict: {\n... \"image_id\": image id,\n... \"annotations\": list of formatted annotations\n... }\n... \"\"\"\n... annotations = []\n... for category, area, bbox in zip(categories, areas, bboxes):\n... formatted_annotation = {\n... \"image_id\": image_id,\n... \"category_id\": category,\n... \"iscrowd\": 0,\n... \"area\": area,\n... \"bbox\": list(bbox),\n... }\n... annotations.append(formatted_annotation)\n\n... return {\n... \"image_id\": image_id,\n... \"annotations\": annotations,\n... }\n\n```", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Preprocess the data", "char_start": 9764, "char_end": 10984, "token_estimate": 305, "prev_chunk_id": 290, "next_chunk_id": 292, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 292, "text": "Now you can combine the image and annotation transformations to use on a batch of examples:", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Preprocess the data", "char_start": 10986, "char_end": 11077, "token_estimate": 22, "prev_chunk_id": 291, "next_chunk_id": 293, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 293, "text": "```py\n>>> def augment_and_transform_batch(examples, transform, image_processor, return_pixel_mask=False):\n... \"\"\"Apply augmentations and format annotations in COCO format for object detection task\"\"\"\n\n... images = []\n... annotations = []\n... for image_id, image, objects in zip(examples[\"image_id\"], examples[\"image\"], examples[\"objects\"]):\n... image = np.array(image.convert(\"RGB\"))\n\n... # apply augmentations\n... output = transform(image=image, bboxes=objects[\"bbox\"], category=objects[\"category\"])\n... images.append(output[\"image\"])\n\n... # format annotations in COCO format\n... formatted_annotations = format_image_annotations_as_coco(\n... image_id, output[\"category\"], objects[\"area\"], output[\"bboxes\"]\n... )\n... annotations.append(formatted_annotations)\n\n... # Apply the image processor transformations: resizing, rescaling, normalization\n... result = image_processor(images=images, annotations=annotations, return_tensors=\"pt\")\n\n... if not return_pixel_mask:\n... result.pop(\"pixel_mask\", None)\n\n... return result\n```", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Preprocess the data", "char_start": 11079, "char_end": 12217, "token_estimate": 284, "prev_chunk_id": 292, "next_chunk_id": 294, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 294, "text": "Apply this preprocessing function to the entire dataset using \ud83e\udd17 Datasets [with_transform](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.with_transform) method. This method applies\ntransformations on the fly when you load an element of the dataset.\n\nAt this point, you can check what an example from the dataset looks like after the transformations. You should see a tensor\nwith `pixel_values`, a tensor with `pixel_mask`, and `labels`.", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Preprocess the data", "char_start": 12219, "char_end": 12703, "token_estimate": 121, "prev_chunk_id": 293, "next_chunk_id": 295, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 295, "text": "```py\n>>> from functools import partial\n\n>>> # Make transform functions for batch and apply for dataset splits\n>>> train_transform_batch = partial(\n... augment_and_transform_batch, transform=train_augment_and_transform, image_processor=image_processor\n... )\n>>> validation_transform_batch = partial(\n... augment_and_transform_batch, transform=validation_transform, image_processor=image_processor\n... )\n\n>>> cppe5[\"train\"] = cppe5[\"train\"].with_transform(train_transform_batch)\n>>> cppe5[\"validation\"] = cppe5[\"validation\"].with_transform(validation_transform_batch)\n>>> cppe5[\"test\"] = cppe5[\"test\"].with_transform(validation_transform_batch)\n\n>>> cppe5[\"train\"][15]\n{'pixel_values': tensor([[[ 1.9235, 1.9407, 1.9749, ..., -0.7822, -0.7479, -0.6965],\n [ 1.9578, 1.9749, 1.9920, ..., -0.7993, -0.7650, -0.7308],\n [ 2.0092, 2.0092, 2.0263, ..., -0.8507, -0.8164, -0.7822],\n ...,\n [ 0.0741, 0.0741, 0.0741, ..., 0.0741, 0.0741, 0.0741],\n [ 0.0741, 0.0741, 0.0741, ..., 0.0741, 0.0741, 0.0741],\n [ 0.0741, 0.0741, 0.0741, ..., 0.0741, 0.0741, 0.0741]],\n\n [[ 1.6232, 1.6408, 1.6583, ..., 0.8704, 1.0105, 1.1331],\n [ 1.6408, 1.6583, 1.6758, ..., 0.8529, 0.9930, 1.0980],\n [ 1.6933, 1.6933, 1.7108, ..., 0.8179, 0.9580, 1.0630],\n ...,\n [ 0.2052, 0.2052, 0.2052, ..., 0.2052, 0.2052, 0.2052],\n [ 0.2052, 0.2052, 0.2052, ..., 0.2052, 0.2052, 0.2052],\n [ 0.2052, 0.2052, 0.2052, ..., 0.2052, 0.2052, 0.2052]],\n\n [[ 1.8905, 1.9080, 1.9428, ..., -0.1487, -0.0964, -0.0615],\n [ 1.9254, 1.9428, 1.9603, ..., -0.1661, -0.1138, -0.0790],\n [ 1.9777, 1.9777, 1.9951, ..., -0.2010, -0.1138, -0.0790],\n ...,\n [ 0.4265, 0.4265, 0.4265, ..., 0.4265, 0.4265, 0.4265],\n [ 0.4265, 0.4265, 0.4265, ..., 0.4265, 0.4265, 0.4265],\n [ 0.4265, 0.4265, 0.4265, ..., 0.4265, 0.4265, 0.4265]]]),\n 'labels': {'image_id': tensor([688]), 'class_labels': tensor([3, 4, 2, 0, 0]), 'boxes': tensor([[0.4700, 0.1933, 0.1467, 0.0767],\n [0.4858, 0.2600, 0.1150, 0.1000],\n [0.4042, 0.4517, 0.1217, 0.1300],\n [0.4242, 0.3217, 0.3617, 0.5567],\n [0.6617, 0.4033, 0.5400, 0.4533]]), 'area': tensor([ 4048., 4140., 5694., 72478., 88128.]), 'iscrowd': tensor([0, 0, 0, 0, 0]), 'orig_size': tensor([480, 480])}}\n```", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Preprocess the data", "char_start": 12705, "char_end": 15188, "token_estimate": 620, "prev_chunk_id": 294, "next_chunk_id": 296, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 296, "text": "You have successfully augmented the individual images and prepared their annotations. However, preprocessing isn't\ncomplete yet. In the final step, create a custom `collate_fn` to batch images together.\nPad images (which are now `pixel_values`) to the largest image in a batch, and create a corresponding `pixel_mask`\nto indicate which pixels are real (1) and which are padding (0).\n\n```py\n>>> import torch\n\n>>> def collate_fn(batch):\n... data = {}\n... data[\"pixel_values\"] = torch.stack([x[\"pixel_values\"] for x in batch])\n... data[\"labels\"] = [x[\"labels\"] for x in batch]\n... if \"pixel_mask\" in batch[0]:\n... data[\"pixel_mask\"] = torch.stack([x[\"pixel_mask\"] for x in batch])\n... return data\n\n```", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Preprocess the data", "char_start": 15190, "char_end": 15916, "token_estimate": 181, "prev_chunk_id": 295, "next_chunk_id": 297, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 297, "text": "## Preparing function to compute mAP\n\nObject detection models are commonly evaluated with a set of COCO-style metrics. We are going to use `torchmetrics` to compute `mAP` (mean average precision) and `mAR` (mean average recall) metrics and will wrap it to `compute_metrics` function in order to use in [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) for evaluation.\n\nIntermediate format of boxes used for training is `YOLO` (normalized) but we will compute metrics for boxes in `Pascal VOC` (absolute) format in order to correctly handle box areas. Let's define a function that converts bounding boxes to `Pascal VOC` format:", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Preparing function to compute mAP", "char_start": 15918, "char_end": 16577, "token_estimate": 164, "prev_chunk_id": 296, "next_chunk_id": 298, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 298, "text": "```py\n>>> from transformers.image_transforms import center_to_corners_format\n\n>>> def convert_bbox_yolo_to_pascal(boxes, image_size):\n... \"\"\"\n... Convert bounding boxes from YOLO format (x_center, y_center, width, height) in range [0, 1]\n... to Pascal VOC format (x_min, y_min, x_max, y_max) in absolute coordinates.\n\n... Args:\n... boxes (torch.Tensor): Bounding boxes in YOLO format\n... image_size (tuple[int, int]): Image size in format (height, width)\n\n... Returns:\n... torch.Tensor: Bounding boxes in Pascal VOC format (x_min, y_min, x_max, y_max)\n... \"\"\"\n... # convert center to corners format\n... boxes = center_to_corners_format(boxes)\n\n... # convert to absolute coordinates\n... height, width = image_size\n... boxes = boxes * torch.tensor([[width, height, width, height]])\n\n... return boxes\n```", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Preparing function to compute mAP", "char_start": 16579, "char_end": 17452, "token_estimate": 218, "prev_chunk_id": 297, "next_chunk_id": 299, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 299, "text": "Then, in `compute_metrics` function we collect `predicted` and `target` bounding boxes, scores and labels from evaluation loop results and pass it to the scoring function.", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Preparing function to compute mAP", "char_start": 17454, "char_end": 17625, "token_estimate": 42, "prev_chunk_id": 298, "next_chunk_id": 300, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 300, "text": "```py\n>>> import numpy as np\n>>> from dataclasses import dataclass\n>>> from torchmetrics.detection.mean_ap import MeanAveragePrecision\n\n>>> @dataclass\n>>> class ModelOutput:\n... logits: torch.Tensor\n... pred_boxes: torch.Tensor\n\n>>> @torch.no_grad()\n>>> def compute_metrics(evaluation_results, image_processor, threshold=0.0, id2label=None):\n... \"\"\"\n... Compute mean average mAP, mAR and their variants for the object detection task.\n\n... Args:\n... evaluation_results (EvalPrediction): Predictions and targets from evaluation.\n... threshold (float, optional): Threshold to filter predicted boxes by confidence. Defaults to 0.0.\n... id2label (Optional[dict], optional): Mapping from class id to class name. Defaults to None.\n\n... Returns:\n... Mapping[str, float]: Metrics in a form of dictionary {: }\n... \"\"\"\n\n... predictions, targets = evaluation_results.predictions, evaluation_results.label_ids\n\n... # For metric computation we need to provide:\n... # - targets in a form of list of dictionaries with keys \"boxes\", \"labels\"\n... # - predictions in a form of list of dictionaries with keys \"boxes\", \"scores\", \"labels\"\n\n... image_sizes = []\n... post_processed_targets = []\n... post_processed_predictions = []\n\n... # Collect targets in the required format for metric computation\n... for batch in targets:\n... # collect image sizes, we will need them for predictions post processing\n... batch_image_sizes = torch.tensor(np.array([x[\"orig_size\"] for x in batch]))\n... image_sizes.append(batch_image_sizes)\n... # collect targets in the required format for metric computation\n... # boxes were converted to YOLO format needed for model training\n... # here we will convert them to Pascal VOC format (x_min, y_min, x_max, y_max)\n... for image_target in batch:\n... boxes = torch.tensor(image_target[\"boxes\"])\n... boxes = convert_bbox_yolo_to_pascal(boxes, image_target[\"orig_size\"])\n... labels = torch.tensor(image_target[\"class_labels\"])\n... post_processed_targets.append({\"boxes\": boxes, \"labels\": labels})\n\n... # Collect predictions in the required format for metric computation,\n... # model produce boxes in YOLO format, then image_processor convert them to Pascal VOC format\n... for batch, target_sizes in zip(predictions, image_sizes):\n... batch_logits, batch_boxes = batch[1], batch[2]\n... output = ModelOutput(logits=torch.tensor(batch_logits), pred_boxes=torch.tensor(batch_boxes))\n... post_processed_output = image_processor.post_process_object_detection(\n... output, threshold=threshold, target_sizes=target_sizes\n... )\n... post_processed_predictions.extend(post_processed_output)\n\n... # Compute metrics\n... metric = MeanAveragePrecision(box_format=\"xyxy\", class_metrics=True)\n... metric.update(post_processed_predictions, post_processed_targets)\n... metrics = metric.compute()\n\n... # Replace list of per class metrics with separate metric for each class\n... classes = metrics.pop(\"classes\")\n... map_per_class = metrics.pop(\"map_per_class\")\n... mar_100_per_class = metrics.pop(\"mar_100_per_class\")\n... for class_id, class_map, class_mar in zip(classes, map_per_class, mar_100_per_class):\n... class_name = id2label[class_id.item()] if id2label is not None else class_id.item()\n... metrics[f\"map_{class_name}\"] = class_map\n... metrics[f\"mar_100_{class_name}\"] = class_mar\n\n... metrics = {k: round(v.item(), 4) for k, v in metrics.items()}\n\n... return metrics\n\n>>> eval_compute_metrics_fn = partial(\n... compute_metrics, image_processor=image_processor, id2label=id2label, threshold=0.0\n... )\n```", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Preparing function to compute mAP", "char_start": 17627, "char_end": 21458, "token_estimate": 957, "prev_chunk_id": 299, "next_chunk_id": 301, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 301, "text": "## Training the detection model\n\nYou have done most of the heavy lifting in the previous sections, so now you are ready to train your model!\nThe images in this dataset are still quite large, even after resizing. This means that finetuning this model will\nrequire at least one GPU.\n\nTraining involves the following steps:\n\n1. Load the model with [AutoModelForObjectDetection](/docs/transformers/v5.6.2/en/model_doc/auto#transformers.AutoModelForObjectDetection) using the same checkpoint as in the preprocessing.\n2. Define your training hyperparameters in [TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments).\n3. Pass the training arguments to [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) along with the model, dataset, image processor, and data collator.\n4. Call [train()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.train) to finetune your model.", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Training the detection model", "char_start": 21460, "char_end": 22420, "token_estimate": 240, "prev_chunk_id": 300, "next_chunk_id": 302, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 302, "text": "When loading the model from the same checkpoint that you used for the preprocessing, remember to pass the `label2id`\nand `id2label` maps that you created earlier from the dataset's metadata. Additionally, we specify `ignore_mismatched_sizes=True` to replace the existing classification head with a new one.\n\n```py\n>>> from transformers import AutoModelForObjectDetection\n\n>>> model = AutoModelForObjectDetection.from_pretrained(\n... MODEL_NAME,\n... id2label=id2label,\n... label2id=label2id,\n... ignore_mismatched_sizes=True,\n... )\n```\n\nIn the [TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments) use `output_dir` to specify where to save your model, then configure hyperparameters as you see fit. For `num_train_epochs=30` training will take about 35 minutes in Google Colab T4 GPU, increase the number of epoch to get better results.\n\nImportant notes:", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Training the detection model", "char_start": 22422, "char_end": 23339, "token_estimate": 229, "prev_chunk_id": 301, "next_chunk_id": 303, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 303, "text": "- Do not remove unused columns because this will drop the image column. Without the image column, you\ncan't create `pixel_values`. For this reason, set `remove_unused_columns` to `False`.\n- Set `eval_do_concat_batches=False` to get proper evaluation results. Images have different number of target boxes, if batches are concatenated we will not be able to determine which boxes belongs to particular image.\n\nIf you wish to share your model by pushing to the Hub, set `push_to_hub` to `True` (you must be signed in to Hugging\nFace to upload your model).", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Training the detection model", "char_start": 23341, "char_end": 23893, "token_estimate": 138, "prev_chunk_id": 302, "next_chunk_id": 304, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 304, "text": "```py\n>>> from transformers import TrainingArguments\n\n>>> training_args = TrainingArguments(\n... output_dir=\"detr_finetuned_cppe5\",\n... num_train_epochs=30,\n... fp16=False,\n... per_device_train_batch_size=8,\n... dataloader_num_workers=4,\n... learning_rate=5e-5,\n... lr_scheduler_type=\"cosine\",\n... weight_decay=1e-4,\n... max_grad_norm=0.01,\n... metric_for_best_model=\"eval_map\",\n... greater_is_better=True,\n... load_best_model_at_end=True,\n... eval_strategy=\"epoch\",\n... save_strategy=\"epoch\",\n... save_total_limit=2,\n... remove_unused_columns=False,\n... report_to=\"trackio\",\n... run_name=\"cppe\",\n... eval_do_concat_batches=False,\n... push_to_hub=True,\n... )\n```\n\nFinally, bring everything together, and call [train()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.train):", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Training the detection model", "char_start": 23895, "char_end": 24772, "token_estimate": 219, "prev_chunk_id": 303, "next_chunk_id": 305, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 305, "text": "```py\n>>> from transformers import Trainer\n\n>>> trainer = Trainer(\n... model=model,\n... args=training_args,\n... train_dataset=cppe5[\"train\"],\n... eval_dataset=cppe5[\"validation\"],\n... processing_class=image_processor,\n... data_collator=collate_fn,\n... compute_metrics=eval_compute_metrics_fn,\n... )\n\n>>> trainer.train()\n```\n\n \n [3210/3210 26:07, Epoch 30/30]", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Training the detection model", "char_start": 24774, "char_end": 25162, "token_estimate": 97, "prev_chunk_id": 304, "next_chunk_id": 306, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 306, "text": "Epoch\n Training Loss\n Validation Loss\n Map\n Map 50\n Map 75\n Map Small\n Map Medium\n Map Large\n Mar 1\n Mar 10\n Mar 100\n Mar Small\n Mar Medium\n Mar Large\n Map Coverall\n Mar 100 Coverall\n Map Face Shield\n Mar 100 Face Shield\n Map Gloves\n Mar 100 Gloves\n Map Goggles\n Mar 100 Goggles\n Map Mask\n Mar 100 Mask\n \n \n \n \n 1\n No log\n 2.629903\n 0.008900\n 0.023200\n 0.006500\n 0.001300\n 0.002800\n 0.020500\n 0.021500\n 0.070400\n 0.101400\n 0.007600\n 0.106200\n 0.096100\n 0.036700\n 0.232000\n 0.000300\n 0.019000\n 0.003900\n 0.125400\n 0.000100\n 0.003100\n 0.003500\n 0.127600\n \n \n 2\n No log\n 3.479864\n 0.014800\n 0.034600\n 0.010800\n 0.008600\n 0.011700\n 0.012500\n 0.041100\n 0.098700\n 0.130000\n 0.056000\n 0.062200\n 0.111900\n 0.053500\n 0.447300\n 0.010600\n 0.100000\n 0.000200\n 0.022800\n 0.000100\n 0.015400\n 0.009700\n 0.064400\n \n \n 3\n No log\n 2.107622\n 0.041700\n 0.094000\n 0.034300\n 0.024100\n 0.026400\n 0.047400\n 0.091500\n 0.182800\n 0.225800\n 0.087200\n 0.199400\n 0.210600\n 0.150900\n 0.571200\n 0.017300\n 0.101300\n 0.007300\n 0.180400\n 0.002100\n 0.026200\n 0.031000\n 0.250200\n \n \n 4\n No log\n 2.031242\n 0.055900\n 0.120600\n 0.046900\n 0.013800\n 0.038100\n 0.090300\n 0.105900\n 0.225600\n 0.266100\n 0.130200\n 0.228100\n 0.330000\n 0.191000\n 0.572100\n 0.010600\n 0.157000\n 0.014600\n 0.235300\n 0.001700\n 0.052300\n 0.061800\n 0.313800\n \n \n 5\n 3.889400\n 1.883433\n 0.089700\n 0.201800\n 0.067300\n 0.022800\n 0.065300\n 0.129500\n 0.136000\n 0.272200\n 0.303700\n 0.112900\n 0.312500\n 0.424600\n 0.300200\n 0.585100\n 0.032700\n 0.202500\n 0.031300\n 0.271000\n 0.008700\n 0.126200\n 0.075500\n 0.333800\n \n \n 6\n 3.889400\n 1.807503\n 0.118500\n 0.270900\n 0.090200\n 0.034900\n 0.076700\n 0.152500\n 0.146100\n 0.297800\n 0.325400\n 0.171700\n 0.283700\n 0.545900\n 0.396900\n 0.554500\n 0.043000\n 0.262000\n 0.054500\n 0.271900\n 0.020300\n 0.230800\n 0.077600\n 0.308000\n \n \n 7\n 3.889400\n 1.716169\n 0.143500\n 0.307700\n 0.123200\n 0.045800\n 0.097800\n 0.258300\n 0.165300\n 0.327700\n 0.352600\n 0.140900\n 0.336700\n 0.599400\n 0.442900\n 0.620700\n 0.069400\n 0.301300\n 0.081600\n 0.292000\n 0.011000\n 0.230800\n 0.112700\n 0.318200\n \n \n 8\n 3.889400\n 1.679014\n 0.153000\n 0.355800\n 0.127900\n 0.038700\n 0.115600\n 0.291600\n 0.176000\n 0.322500\n 0.349700\n 0.135600\n 0.326100\n 0.643700\n 0.431700\n 0.582900\n 0.069800\n 0.265800\n 0.088600\n 0.274600\n 0.028300\n 0.280000\n 0.146700\n 0.345300\n \n \n 9\n 3.889400\n 1.618239\n 0.172100\n 0.375300\n 0.137600\n 0.046100\n 0.141700\n 0.308500\n 0.194000\n 0.356200\n 0.386200\n 0.162400\n 0.359200\n 0.677700\n 0.469800\n 0.623900\n 0.102100\n 0.317700\n 0.099100\n 0.290200\n 0.029300\n 0.335400\n 0.160200\n 0.364000\n \n \n 10\n 1.599700\n 1.572512\n 0.179500\n 0.400400\n 0.147200\n 0.056500\n 0.141700\n 0.316700\n 0.213100\n 0.357600\n 0.381300\n 0.197900\n 0.344300\n 0.638500\n 0.466900\n 0.623900\n 0.101300\n 0.311400\n 0.104700\n 0.279500\n 0.051600\n 0.338500\n 0.173000\n 0.353300\n \n \n 11\n 1.599700\n 1.528889\n 0.192200\n 0.415000\n 0.160800\n 0.053700\n 0.150500\n 0.378000\n 0.211500\n 0.371700\n 0.397800\n 0.204900\n 0.374600\n 0.684800\n 0.491900\n 0.632400\n 0.131200\n 0.346800\n 0.122000\n 0.300900\n 0.038400\n 0.344600\n 0.177500\n 0.364400\n \n \n 12\n 1.599700\n 1.517532\n 0.198300\n 0.429800\n 0.159800\n 0.066400\n 0.162900\n 0.383300\n 0.220700\n 0.382100\n 0.405400\n 0.214800\n 0.383200\n 0.672900\n 0.469000\n 0.610400\n 0.167800\n 0.379700\n 0.119700\n 0.307100\n 0.038100\n 0.335400\n 0.196800\n 0.394200\n \n \n 13\n 1.599700\n 1.488849\n 0.209800\n 0.452300\n 0.172300\n 0.094900\n 0.171100\n 0.437800\n 0.222000\n 0.379800\n 0.411500\n 0.203800\n 0.397300\n 0.707500\n 0.470700\n 0.620700\n 0.186900\n 0.407600\n 0.124200\n 0.306700\n 0.059300\n 0.355400\n 0.207700\n 0.367100\n \n \n 14\n 1.599700\n 1.482210\n 0.228900\n 0.482600\n 0.187800\n 0.083600\n 0.191800\n 0.444100\n 0.225900\n 0.376900\n 0.407400\n 0.182500\n 0.384800\n 0.700600\n 0.512100\n 0.640100\n 0.175000\n 0.363300\n 0.144300\n 0.300000\n 0.083100\n 0.363100\n 0.229900\n 0.370700\n \n \n 15\n 1.326800\n 1.475198\n 0.216300\n 0.455600\n 0.174900\n 0.088500\n 0.183500\n 0.424400\n 0.226900\n 0.373400\n 0.404300\n 0.199200\n 0.396400\n 0.677800\n 0.496300\n 0.633800\n 0.166300\n 0.392400\n 0.128900\n 0.312900\n 0.085200\n 0.312300\n 0.205000\n 0.370200\n \n \n 16\n 1.326800\n 1.459697\n 0.233200\n 0.504200\n 0.192200\n 0.096000\n 0.202000\n 0.430800\n 0.239100\n 0.382400\n 0.412600\n 0.219500\n 0.403100\n 0.670400\n 0.485200\n 0.625200\n 0.196500\n 0.410100\n 0.135700\n 0.299600\n 0.123100\n 0.356900\n 0.225300\n 0.371100\n \n \n 17\n 1.326800\n 1.407340\n 0.243400\n 0.511900\n 0.204500\n 0.121000\n 0.215700\n 0.468000\n 0.246200\n 0.394600\n 0.424200\n 0.225900\n 0.416100\n 0.705200\n 0.494900\n 0.638300\n 0.224900\n 0.430400\n 0.157200\n 0.317900\n 0.115700\n 0.369200\n 0.224200\n 0.365300\n \n \n 18\n 1.326800\n 1.419522\n 0.245100\n 0.521500\n 0.210000\n 0.116100\n 0.211500\n 0.489900\n 0.255400\n 0.391600\n 0.419700\n 0.198800\n 0.421200\n 0.701400\n 0.501800\n 0.634200\n 0.226700\n 0.410100\n 0.154400\n 0.321400\n 0.105900\n 0.352300\n 0.236700\n 0.380400\n \n \n 19\n 1.158600\n 1.398764\n 0.253600\n 0.519200\n 0.213600\n 0.135200\n 0.207700\n 0.491900\n 0.257300\n 0.397300\n 0.428000\n 0.241400\n 0.401800\n 0.703500\n 0.509700\n 0.631100\n 0.236700\n 0.441800\n 0.155900\n 0.330800\n 0.128100\n 0.352300\n 0.237500\n 0.384000\n \n \n 20\n 1.158600\n 1.390591\n 0.248800\n 0.520200\n 0.216600\n 0.127500\n 0.211400\n 0.471900\n 0.258300\n 0.407000\n 0.429100\n 0.240300\n 0.407600\n 0.708500\n 0.505800\n 0.623400\n 0.235500\n 0.431600\n 0.150000\n 0.325000\n 0.125700\n 0.375400\n 0.227200\n 0.390200\n \n \n 21\n 1.158600\n 1.360608\n 0.262700\n 0.544800\n 0.222100\n 0.134700\n 0.230000\n 0.487500\n 0.269500\n 0.413300\n 0.436300\n 0.236200\n 0.419100\n 0.709300\n 0.514100\n 0.637400\n 0.257200\n 0.450600\n 0.165100\n 0.338400\n 0.139400\n 0.372300\n 0.237700\n 0.382700\n \n \n 22\n 1.158600\n 1.368296\n 0.262800\n 0.542400\n 0.236400\n 0.137400\n 0.228100\n 0.498500\n 0.266500\n 0.409000\n 0.433000\n 0.239900\n 0.418500\n 0.697500\n 0.520500\n 0.641000\n 0.257500\n 0.455700\n 0.162600\n 0.334800\n 0.140200\n 0.353800\n 0.233200\n 0.379600\n \n \n 23\n 1.158600\n 1.368176\n 0.264800\n 0.541100\n 0.233100\n 0.138200\n 0.223900\n 0.498700\n 0.272300\n 0.407400\n 0.434400\n 0.233100\n 0.418300\n 0.702000\n 0.524400\n 0.642300\n 0.262300\n 0.444300\n 0.159700\n 0.335300\n 0.140500\n 0.366200\n 0.236900\n 0.384000\n \n \n 24\n 1.049700\n 1.355271\n 0.269700\n 0.549200\n 0.239100\n 0.134700\n 0.229900\n 0.519200\n 0.274800\n 0.412700\n 0.437600\n 0.245400\n 0.417200\n 0.711200\n 0.523200\n 0.644100\n 0.272100\n 0.440500\n 0.166700\n 0.341500\n 0.137700\n 0.373800\n 0.249000\n 0.388000\n \n \n 25\n 1.049700\n 1.355180\n 0.272500\n 0.547900\n 0.243800\n 0.149700\n 0.229900\n 0.523100\n 0.272500\n 0.415700\n 0.442200\n 0.256200\n 0.420200\n 0.705800\n 0.523900\n 0.639600\n 0.271700\n 0.451900\n 0.166300\n 0.346900\n 0.153700\n 0.383100\n 0.247000\n 0.389300\n \n \n 26\n 1.049700\n 1.349337\n 0.275600\n 0.556300\n 0.246400\n 0.146700\n 0.234800\n 0.516300\n 0.274200\n 0.418300\n 0.440900\n 0.248700\n 0.418900\n 0.705800\n 0.523200\n 0.636500\n 0.274700\n 0.440500\n 0.172400\n 0.349100\n 0.155600\n 0.384600\n 0.252300\n 0.393800\n \n \n 27\n 1.049700\n 1.350782\n 0.275200\n 0.548700\n 0.246800\n 0.147300\n 0.236400\n 0.527200\n 0.280100\n 0.416200\n 0.442600\n 0.253400\n 0.424000\n 0.710300\n 0.526600\n 0.640100\n 0.273200\n 0.445600\n 0.167000\n 0.346900\n 0.160100\n 0.387700\n 0.249200\n 0.392900\n \n \n 28\n 1.049700\n 1.346533\n 0.277000\n 0.552800\n 0.252900\n 0.147400\n 0.240000\n 0.527600\n 0.280900\n 0.420900\n 0.444100\n 0.255500\n 0.424500\n 0.711200\n 0.530200\n 0.646800\n 0.277400\n 0.441800\n 0.170900\n 0.346900\n 0.156600\n 0.389200\n 0.249600\n 0.396000\n \n \n 29\n 0.993700\n 1.346575\n 0.277100\n 0.554800\n 0.252900\n 0.148400\n 0.239700\n 0.523600\n 0.278400\n 0.420000\n 0.443300\n 0.256300\n 0.424000\n 0.705600\n 0.529600\n 0.647300\n 0.273900\n 0.439200\n 0.174300\n 0.348700\n 0.157600\n 0.386200\n 0.250100\n 0.395100\n \n \n 30\n 0.993700\n 1.346446\n 0.277400\n 0.554700\n 0.252700\n 0.147900\n 0.240800\n 0.523600\n 0.278800\n 0.420400\n 0.443300\n 0.256100\n 0.424200\n 0.705500\n 0.530100\n 0.646800\n 0.275600\n 0.440500\n 0.174500\n 0.348700\n 0.157300\n 0.386200\n 0.249200\n 0.394200", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Training the detection model", "char_start": 25178, "char_end": 36959, "token_estimate": 2950, "prev_chunk_id": 305, "next_chunk_id": 307, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 307, "text": "If you have set `push_to_hub` to `True` in the `training_args`, the training checkpoints are pushed to the\nHugging Face Hub. Upon training completion, push the final model to the Hub as well by calling the [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.push_to_hub) method.\n\n```py\n>>> trainer.push_to_hub()\n```", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Training the detection model", "char_start": 36969, "char_end": 37319, "token_estimate": 87, "prev_chunk_id": 306, "next_chunk_id": 308, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 308, "text": "## Evaluate\n\n```py\n>>> from pprint import pprint\n\n>>> metrics = trainer.evaluate(eval_dataset=cppe5[\"test\"], metric_key_prefix=\"test\")\n>>> pprint(metrics)\n{'epoch': 30.0,\n 'test_loss': 1.0877351760864258,\n 'test_map': 0.4116,\n 'test_map_50': 0.741,\n 'test_map_75': 0.3663,\n 'test_map_Coverall': 0.5937,\n 'test_map_Face_Shield': 0.5863,\n 'test_map_Gloves': 0.3416,\n 'test_map_Goggles': 0.1468,\n 'test_map_Mask': 0.3894,\n 'test_map_large': 0.5637,\n 'test_map_medium': 0.3257,\n 'test_map_small': 0.3589,\n 'test_mar_1': 0.323,\n 'test_mar_10': 0.5237,\n 'test_mar_100': 0.5587,\n 'test_mar_100_Coverall': 0.6756,\n 'test_mar_100_Face_Shield': 0.7294,\n 'test_mar_100_Gloves': 0.4721,\n 'test_mar_100_Goggles': 0.4125,\n 'test_mar_100_Mask': 0.5038,\n 'test_mar_large': 0.7283,\n 'test_mar_medium': 0.4901,\n 'test_mar_small': 0.4469,\n 'test_runtime': 1.6526,\n 'test_samples_per_second': 17.548,\n 'test_steps_per_second': 2.42}\n```", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Evaluate", "char_start": 37321, "char_end": 38263, "token_estimate": 235, "prev_chunk_id": 307, "next_chunk_id": 309, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 309, "text": "These results can be further improved by adjusting the hyperparameters in [TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments). Give it a go!", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Evaluate", "char_start": 38265, "char_end": 38455, "token_estimate": 47, "prev_chunk_id": 308, "next_chunk_id": 310, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 310, "text": "## Inference\n\nNow that you have finetuned a model, evaluated it, and uploaded it to the Hugging Face Hub, you can use it for inference.\n\n```py\n>>> import torch\n>>> import requests\n\n>>> from PIL import Image, ImageDraw\n>>> from transformers import AutoImageProcessor, AutoModelForObjectDetection\n\n>>> url = \"https://images.pexels.com/photos/8413299/pexels-photo-8413299.jpeg?auto=compress&cs=tinysrgb&w=630&h=375&dpr=2\"\n>>> image = Image.open(requests.get(url, stream=True).raw)\n```\n\nLoad model and image processor from the Hugging Face Hub (skip to use already trained in this session):\n\n```py\n>>> from accelerate import Accelerator\n\n>>> device = Accelerator().device\n>>> model_repo = \"qubvel-hf/detr_finetuned_cppe5\"\n\n>>> image_processor = AutoImageProcessor.from_pretrained(model_repo)\n>>> model = AutoModelForObjectDetection.from_pretrained(model_repo)\n>>> model = model.to(device)\n```\n\nAnd detect bounding boxes:", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Inference", "char_start": 38457, "char_end": 39373, "token_estimate": 229, "prev_chunk_id": 309, "next_chunk_id": 311, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 311, "text": "```py\n\n>>> with torch.no_grad():\n... inputs = image_processor(images=[image], return_tensors=\"pt\")\n... outputs = model(**inputs.to(device))\n... target_sizes = torch.tensor([[image.size[1], image.size[0]]])\n... results = image_processor.post_process_object_detection(outputs, threshold=0.3, target_sizes=target_sizes)[0]\n\n>>> for score, label, box in zip(results[\"scores\"], results[\"labels\"], results[\"boxes\"]):\n... box = [round(i, 2) for i in box.tolist()]\n... print(\n... f\"Detected {model.config.id2label[label.item()]} with confidence \"\n... f\"{round(score.item(), 3)} at location {box}\"\n... )\nDetected Gloves with confidence 0.683 at location [244.58, 124.33, 300.35, 185.13]\nDetected Mask with confidence 0.517 at location [143.73, 64.58, 219.57, 125.89]\nDetected Gloves with confidence 0.425 at location [179.15, 155.57, 262.4, 226.35]\nDetected Coverall with confidence 0.407 at location [307.13, -1.18, 477.82, 318.06]\nDetected Coverall with confidence 0.391 at location [68.61, 126.66, 309.03, 318.89]\n```", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Inference", "char_start": 39375, "char_end": 40430, "token_estimate": 263, "prev_chunk_id": 310, "next_chunk_id": 312, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 312, "text": "Let's plot the result:\n\n```py\n>>> draw = ImageDraw.Draw(image)\n\n>>> for score, label, box in zip(results[\"scores\"], results[\"labels\"], results[\"boxes\"]):\n... box = [round(i, 2) for i in box.tolist()]\n... x, y, x2, y2 = tuple(box)\n... draw.rectangle((x, y, x2, y2), outline=\"red\", width=1)\n... draw.text((x, y), model.config.id2label[label.item()], fill=\"white\")\n\n>>> image\n```", "source_file": "transformers/tasks/object_detection.md", "section_heading": "Inference", "char_start": 40432, "char_end": 40824, "token_estimate": 98, "prev_chunk_id": 311, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/tasks/object_detection", "doc_title": "Object detection" }, { "chunk_id": 313, "text": "# Image Segmentation\n\nImage segmentation models separate areas corresponding to different areas of interest in an image. These models work by assigning a label to each pixel. There are several types of segmentation: semantic segmentation, instance segmentation, and panoptic segmentation.\n\nIn this guide, we will:\n\n1. [Take a look at different types of segmentation](#types-of-segmentation).\n2. [Have an end-to-end fine-tuning example for semantic segmentation](#fine-tuning-a-model-for-segmentation).\n\nBefore you begin, make sure you have all the necessary libraries installed:\n\n```py", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Image Segmentation", "char_start": 0, "char_end": 585, "token_estimate": 146, "prev_chunk_id": null, "next_chunk_id": 314, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 314, "text": "# uncomment to install the necessary libraries\n!pip install -q datasets transformers evaluate accelerate trackio\n```\n\nWe 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:\n\n```py\n>>> from huggingface_hub import notebook_login\n\n>>> notebook_login()\n```", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "uncomment to install the necessary libraries", "char_start": 586, "char_end": 941, "token_estimate": 88, "prev_chunk_id": 313, "next_chunk_id": 315, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 315, "text": "## Types of Segmentation\n\nSemantic segmentation assigns a label or class to every single pixel in an image. Let's take a look at a semantic segmentation model output. It will assign the same class to every instance of an object it comes across in an image, for example, all cats will be labeled as \"cat\" instead of \"cat-1\", \"cat-2\".\nWe can use transformers' image segmentation pipeline to quickly infer a semantic segmentation model. Let's take a look at the example image.\n\n```python\nfrom transformers import pipeline\nfrom PIL import Image\nimport requests\n\nurl = \"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/segmentation_input.jpg\"\nimage = Image.open(requests.get(url, stream=True).raw)\nimage\n```\n\nWe will use [nvidia/segformer-b1-finetuned-cityscapes-1024-1024](https://huggingface.co/nvidia/segformer-b1-finetuned-cityscapes-1024-1024).", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Types of Segmentation", "char_start": 0, "char_end": 892, "token_estimate": 223, "prev_chunk_id": 314, "next_chunk_id": 316, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 316, "text": "```python\nsemantic_segmentation = pipeline(\"image-segmentation\", \"nvidia/segformer-b1-finetuned-cityscapes-1024-1024\")\nresults = semantic_segmentation(image)\nresults\n```\n\nThe segmentation pipeline output includes a mask for every predicted class.\n\n```bash\n[{'score': None,\n 'label': 'road',\n 'mask': },\n {'score': None,\n 'label': 'sidewalk',\n 'mask': },\n {'score': None,\n 'label': 'building',\n 'mask': },\n {'score': None,\n 'label': 'wall',\n 'mask': },\n {'score': None,\n 'label': 'pole',\n 'mask': },\n {'score': None,\n 'label': 'traffic sign',\n 'mask': },\n {'score': None,\n 'label': 'vegetation',\n 'mask': },\n {'score': None,\n 'label': 'terrain',\n 'mask': },\n {'score': None,\n 'label': 'sky',\n 'mask': },\n {'score': None,\n 'label': 'car',\n 'mask': }]\n```\n\nTaking a look at the mask for the car class, we can see every car is classified with the same mask.\n\n```python\nresults[-1][\"mask\"]\n```", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Types of Segmentation", "char_start": 1844, "char_end": 2752, "token_estimate": 227, "prev_chunk_id": 315, "next_chunk_id": 317, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 317, "text": "In instance segmentation, the goal is not to classify every pixel, but to predict a mask for **every instance of an object** in a given image. It works very similar to object detection, where there is a bounding box for every instance, there's a segmentation mask instead. We will use [facebook/mask2former-swin-large-cityscapes-instance](https://huggingface.co/facebook/mask2former-swin-large-cityscapes-instance) for this.\n\n```python\ninstance_segmentation = pipeline(\"image-segmentation\", \"facebook/mask2former-swin-large-cityscapes-instance\")\nresults = instance_segmentation(image)\nresults\n```\n\nAs you can see below, there are multiple cars classified, and there's no classification for pixels other than pixels that belong to car and person instances.\n\n```bash\n[{'score': 0.999944,\n 'label': 'car',\n 'mask': },\n {'score': 0.999945,\n 'label': 'car',\n 'mask': },\n {'score': 0.999652,\n 'label': 'car',\n 'mask': },\n {'score': 0.903529,\n 'label': 'person',\n 'mask': }]\n```\n\nChecking out one of the car masks below.", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Types of Segmentation", "char_start": 2761, "char_end": 3782, "token_estimate": 255, "prev_chunk_id": 316, "next_chunk_id": 318, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 318, "text": "```python\nresults[2][\"mask\"]\n```\n\nPanoptic segmentation combines semantic segmentation and instance segmentation, where every pixel is classified into a class and an instance of that class, and there are multiple masks for each instance of a class. We can use [facebook/mask2former-swin-large-cityscapes-panoptic](https://huggingface.co/facebook/mask2former-swin-large-cityscapes-panoptic) for this.\n\n```python\npanoptic_segmentation = pipeline(\"image-segmentation\", \"facebook/mask2former-swin-large-cityscapes-panoptic\")\nresults = panoptic_segmentation(image)\nresults\n```\n\nAs you can see below, we have more classes. We will later illustrate to see that every pixel is classified into one of the classes.", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Types of Segmentation", "char_start": 0, "char_end": 704, "token_estimate": 176, "prev_chunk_id": 317, "next_chunk_id": 319, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 319, "text": "```bash\n[{'score': 0.999981,\n 'label': 'car',\n 'mask': },\n {'score': 0.999958,\n 'label': 'car',\n 'mask': },\n {'score': 0.99997,\n 'label': 'vegetation',\n 'mask': },\n {'score': 0.999575,\n 'label': 'pole',\n 'mask': },\n {'score': 0.999958,\n 'label': 'building',\n 'mask': },\n {'score': 0.999634,\n 'label': 'road',\n 'mask': },\n {'score': 0.996092,\n 'label': 'sidewalk',\n 'mask': },\n {'score': 0.999221,\n 'label': 'car',\n 'mask': },\n {'score': 0.99987,\n 'label': 'sky',\n 'mask': }]\n```\n\nLet's have a side by side comparison for all types of segmentation.\n\nSeeing all types of segmentation, let's have a deep dive on fine-tuning a model for semantic segmentation.\n\nCommon real-world applications of semantic segmentation include training self-driving cars to identify pedestrians and important traffic information, identifying cells and abnormalities in medical imagery, and monitoring environmental changes from satellite imagery.", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Types of Segmentation", "char_start": 0, "char_end": 941, "token_estimate": 235, "prev_chunk_id": 318, "next_chunk_id": 320, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 320, "text": "## Fine-tuning a Model for Segmentation\n\nWe will now:\n\n1. Finetune [SegFormer](https://huggingface.co/docs/transformers/main/en/model_doc/segformer#segformer) on the [SceneParse150](https://huggingface.co/datasets/scene_parse_150) dataset.\n2. Use your fine-tuned model for inference.\n\nTo see all architectures and checkpoints compatible with this task, we recommend checking the [task-page](https://huggingface.co/tasks/image-segmentation)", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Fine-tuning a Model for Segmentation", "char_start": 5447, "char_end": 5886, "token_estimate": 109, "prev_chunk_id": 319, "next_chunk_id": 321, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 321, "text": "### Load SceneParse150 dataset\n\nStart by loading a smaller subset of the SceneParse150 dataset from the \ud83e\udd17 Datasets library. This'll give you a chance to experiment and make sure everything works before spending more time training on the full dataset.\n\n```py\n>>> from datasets import load_dataset\n\n>>> ds = load_dataset(\"merve/scene_parse_150\", split=\"train[:50]\")\n```\n\nSplit the dataset's `train` split into a train and test set with the [train_test_split](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.train_test_split) method:\n\n```py\n>>> ds = ds.train_test_split(test_size=0.2)\n>>> train_ds = ds[\"train\"]\n>>> test_ds = ds[\"test\"]\n```\n\nThen take a look at an example:\n\n```py\n>>> train_ds[0]\n{'image': ,\n 'annotation': ,\n 'scene_category': 368}", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Load SceneParse150 dataset", "char_start": 5888, "char_end": 6681, "token_estimate": 198, "prev_chunk_id": 320, "next_chunk_id": 322, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 322, "text": "# view the image\n>>> train_ds[0][\"image\"]\n```\n\n- `image`: a PIL image of the scene.\n- `annotation`: a PIL image of the segmentation map, which is also the model's target.\n- `scene_category`: a category id that describes the image scene like \"kitchen\" or \"office\". In this guide, you'll only need `image` and `annotation`, both of which are PIL images.\n\nYou'll also want to create a dictionary that maps a label id to a label class which will be useful when you set up the model later. Download the mappings from the Hub and create the `id2label` and `label2id` dictionaries:\n\n```py\n>>> import json\n>>> from pathlib import Path\n>>> from huggingface_hub import hf_hub_download\n\n>>> repo_id = \"huggingface/label-files\"\n>>> filename = \"ade20k-id2label.json\"\n>>> id2label = json.loads(Path(hf_hub_download(repo_id, filename, repo_type=\"dataset\")).read_text())\n>>> id2label = {int(k): v for k, v in id2label.items()}\n>>> label2id = {v: k for k, v in id2label.items()}\n>>> num_labels = len(id2label)\n```", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "view the image", "char_start": 6683, "char_end": 7679, "token_estimate": 249, "prev_chunk_id": 321, "next_chunk_id": 323, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 323, "text": "#### Custom dataset\n\nYou could also create and use your own dataset if you prefer to train with the [run_semantic_segmentation.py](https://github.com/huggingface/transformers/blob/main/examples/pytorch/semantic-segmentation/run_semantic_segmentation.py) script instead of a notebook instance. The script requires:\n\n1. a [DatasetDict](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.DatasetDict) with two [Image](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Image) columns, \"image\" and \"label\"", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Custom dataset", "char_start": 7681, "char_end": 8254, "token_estimate": 143, "prev_chunk_id": 322, "next_chunk_id": 324, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 324, "text": "```py\n from datasets import Dataset, DatasetDict, Image\n\n image_paths_train = [\"path/to/image_1.jpg/jpg\", \"path/to/image_2.jpg/jpg\", ..., \"path/to/image_n.jpg/jpg\"]\n label_paths_train = [\"path/to/annotation_1.png\", \"path/to/annotation_2.png\", ..., \"path/to/annotation_n.png\"]\n\n image_paths_validation = [...]\n label_paths_validation = [...]\n\n def create_dataset(image_paths, label_paths):\n dataset = Dataset.from_dict({\"image\": sorted(image_paths),\n \"label\": sorted(label_paths)})\n dataset = dataset.cast_column(\"image\", Image())\n dataset = dataset.cast_column(\"label\", Image())\n return dataset\n\n # step 1: create Dataset objects\n train_dataset = create_dataset(image_paths_train, label_paths_train)\n validation_dataset = create_dataset(image_paths_validation, label_paths_validation)\n\n # step 2: create DatasetDict\n dataset = DatasetDict({\n \"train\": train_dataset,\n \"validation\": validation_dataset,\n }\n )\n\n # step 3: push to Hub (assumes you have ran the hf auth login command in a terminal/notebook)\n dataset.push_to_hub(\"your-name/dataset-repo\")\n\n # optionally, you can push to a private repo on the Hub\n # dataset.push_to_hub(\"name of repo on the hub\", private=True)\n ```", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Custom dataset", "char_start": 8261, "char_end": 9600, "token_estimate": 336, "prev_chunk_id": 323, "next_chunk_id": 325, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 325, "text": "2. an id2label dictionary mapping the class integers to their class names\n\n ```py\n import json\n # simple example\n id2label = {0: 'cat', 1: 'dog'}\n with open('id2label.json', 'w') as fp:\n json.dump(id2label, fp)\n ```\n\nAs an example, take a look at this [example dataset](https://huggingface.co/datasets/nielsr/ade20k-demo) which was created with the steps shown above.", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Custom dataset", "char_start": 9602, "char_end": 10001, "token_estimate": 99, "prev_chunk_id": 324, "next_chunk_id": 326, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 326, "text": "### Preprocess\n\nThe next step is to load a SegFormer image processor to prepare the images and annotations for the model. Some datasets, like this one, use the zero-index as the background class. However, the background class isn't actually included in the 150 classes, so you'll need to set `do_reduce_labels=True` to subtract one from all the labels. The zero-index is replaced by `255` so it's ignored by SegFormer's loss function:\n\n```py\n>>> from transformers import AutoImageProcessor\n\n>>> checkpoint = \"nvidia/mit-b0\"\n>>> image_processor = AutoImageProcessor.from_pretrained(checkpoint, do_reduce_labels=True)\n```", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Preprocess", "char_start": 10003, "char_end": 10622, "token_estimate": 154, "prev_chunk_id": 325, "next_chunk_id": 327, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 327, "text": "It is common to apply some data augmentations to an image dataset to make a model more robust against overfitting. In this guide, you'll use the [`ColorJitter`](https://pytorch.org/vision/stable/generated/torchvision.transforms.ColorJitter.html) function from [torchvision](https://pytorch.org/vision/stable/index.html) to randomly change the color properties of an image, but you can also use any image library you like.\n\n```py\n>>> from torchvision.transforms import ColorJitter\n\n>>> jitter = ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.1)\n```\n\nNow create two preprocessing functions to prepare the images and annotations for the model. These functions convert the images into `pixel_values` and annotations to `labels`. For the training set, `jitter` is applied before providing the images to the image processor. For the test set, the image processor crops and normalizes the `images`, and only crops the `labels` because no data augmentation is applied during testing.", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Preprocess", "char_start": 10624, "char_end": 11619, "token_estimate": 248, "prev_chunk_id": 326, "next_chunk_id": 328, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 328, "text": "```py\n>>> def train_transforms(example_batch):\n... images = [jitter(x) for x in example_batch[\"image\"]]\n... labels = [x for x in example_batch[\"annotation\"]]\n... inputs = image_processor(images, labels)\n... return inputs\n\n>>> def val_transforms(example_batch):\n... images = [x for x in example_batch[\"image\"]]\n... labels = [x for x in example_batch[\"annotation\"]]\n... inputs = image_processor(images, labels)\n... return inputs\n```\n\nTo apply the `jitter` over the entire dataset, use the \ud83e\udd17 Datasets [set_transform](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.set_transform) function. The transform is applied on the fly which is faster and consumes less disk space:\n\n```py\n>>> train_ds.set_transform(train_transforms)\n>>> test_ds.set_transform(val_transforms)\n```", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Preprocess", "char_start": 11621, "char_end": 12466, "token_estimate": 211, "prev_chunk_id": 327, "next_chunk_id": 329, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 329, "text": "### Evaluate\n\nIncluding a metric during training is often helpful for evaluating your model's performance. You can quickly load an evaluation method with the \ud83e\udd17 [Evaluate](https://huggingface.co/docs/evaluate/index) library. For this task, load the [mean Intersection over Union](https://huggingface.co/spaces/evaluate-metric/accuracy) (IoU) metric (see the \ud83e\udd17 Evaluate [quick tour](https://huggingface.co/docs/evaluate/a_quick_tour) to learn more about how to load and compute a metric):\n\n```py\n>>> import evaluate\n\n>>> metric = evaluate.load(\"mean_iou\")\n```\n\nThen create a function to [compute](https://huggingface.co/docs/evaluate/v0.4.6/en/package_reference/main_classes#evaluate.EvaluationModule.compute) the metrics. Your predictions need to be converted to\nlogits first, and then reshaped to match the size of the labels before you can call [compute](https://huggingface.co/docs/evaluate/v0.4.6/en/package_reference/main_classes#evaluate.EvaluationModule.compute):", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Evaluate", "char_start": 12468, "char_end": 13437, "token_estimate": 242, "prev_chunk_id": 328, "next_chunk_id": 330, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 330, "text": "```py\n>>> import numpy as np\n>>> import torch\n>>> from torch import nn\n\n>>> def compute_metrics(eval_pred):\n... with torch.no_grad():\n... logits, labels = eval_pred\n... logits_tensor = torch.from_numpy(logits)\n... logits_tensor = nn.functional.interpolate(\n... logits_tensor,\n... size=labels.shape[-2:],\n... mode=\"bilinear\",\n... align_corners=False,\n... ).argmax(dim=1)\n\n... pred_labels = logits_tensor.detach().cpu().numpy()\n... metrics = metric.compute(\n... predictions=pred_labels,\n... references=labels,\n... num_labels=num_labels,\n... ignore_index=255,\n... reduce_labels=False,\n... )\n... for key, value in metrics.items():\n... if isinstance(value, np.ndarray):\n... metrics[key] = value.tolist()\n... return metrics\n```", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Evaluate", "char_start": 13439, "char_end": 14372, "token_estimate": 233, "prev_chunk_id": 329, "next_chunk_id": 331, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 331, "text": "Your `compute_metrics` function is ready to go now, and you'll return to it when you setup your training.", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Evaluate", "char_start": 14374, "char_end": 14479, "token_estimate": 26, "prev_chunk_id": 330, "next_chunk_id": 332, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 332, "text": "### Train\n\nIf you aren't familiar with finetuning a model with the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer), take a look at the basic tutorial [here](../training#finetune-with-trainer)!\n\nYou're ready to start training your model now! Load SegFormer with [AutoModelForSemanticSegmentation](/docs/transformers/v5.6.2/en/model_doc/auto#transformers.AutoModelForSemanticSegmentation), and pass the model the mapping between label ids and label classes:\n\n```py\n>>> from transformers import AutoModelForSemanticSegmentation, TrainingArguments, Trainer\n\n>>> model = AutoModelForSemanticSegmentation.from_pretrained(checkpoint, id2label=id2label, label2id=label2id)\n```\n\nAt this point, only three steps remain:", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Train", "char_start": 14481, "char_end": 15224, "token_estimate": 185, "prev_chunk_id": 331, "next_chunk_id": 333, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 333, "text": "1. Define your training hyperparameters in [TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments). It is important you don't remove unused columns because this'll drop the `image` column. Without the `image` column, you can't create `pixel_values`. Set `remove_unused_columns=False` to prevent this behavior! The only other required parameter is `output_dir` which specifies where to save your model. You'll push this model to the Hub by setting `push_to_hub=True` (you need to be signed in to Hugging Face to upload your model). At the end of each epoch, the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) will evaluate the IoU metric and save the training checkpoint.\n2. Pass the training arguments to [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) along with the model, dataset, tokenizer, data collator, and `compute_metrics` function.\n3. Call [train()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.train) to finetune your model.", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Train", "char_start": 15226, "char_end": 16302, "token_estimate": 269, "prev_chunk_id": 332, "next_chunk_id": 334, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 334, "text": "```py\n>>> training_args = TrainingArguments(\n... output_dir=\"segformer-b0-scene-parse-150\",\n... learning_rate=6e-5,\n... num_train_epochs=50,\n... per_device_train_batch_size=2,\n... per_device_eval_batch_size=2,\n... save_total_limit=3,\n... eval_strategy=\"steps\",\n... save_strategy=\"steps\",\n... save_steps=20,\n... eval_steps=20,\n... logging_steps=1,\n... report_to=\"trackio\",\n... run_name=\"scene-parse-150\",\n... eval_accumulation_steps=5,\n... remove_unused_columns=False,\n... push_to_hub=True,\n... )\n\n>>> trainer = Trainer(\n... model=model,\n... args=training_args,\n... train_dataset=train_ds,\n... eval_dataset=test_ds,\n... compute_metrics=compute_metrics,\n... )\n\n>>> trainer.train()\n```\n\nOnce training is completed, share your model to the Hub with the [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.push_to_hub) method so everyone can use your model:\n\n```py\n>>> trainer.push_to_hub()\n```", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Train", "char_start": 16304, "char_end": 17312, "token_estimate": 252, "prev_chunk_id": 333, "next_chunk_id": 335, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 335, "text": "### Inference\n\nGreat, now that you've finetuned a model, you can use it for inference!\n\nReload the dataset and load an image for inference.\n\n```py\n>>> from datasets import load_dataset\n\n>>> ds = load_dataset(\"scene_parse_150\", split=\"train[:50]\")\n>>> ds = ds.train_test_split(test_size=0.2)\n>>> test_ds = ds[\"test\"]\n>>> image = ds[\"test\"][0][\"image\"]\n>>> image\n```\n\nWe will now see how to infer without a pipeline. Process the image with an image processor and place the `pixel_values` on a GPU:\n\n```py\n>>> from accelerate import Accelerator\n>>> device = Accelerator().device\n>>> encoding = image_processor(image, return_tensors=\"pt\")\n>>> pixel_values = encoding.pixel_values.to(device)\n```\n\nPass your input to the model and return the `logits`:\n\n```py\n>>> outputs = model(pixel_values=pixel_values)\n>>> logits = outputs.logits.cpu()\n```\n\nNext, rescale the logits to the original image size:", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Inference", "char_start": 0, "char_end": 891, "token_estimate": 222, "prev_chunk_id": 334, "next_chunk_id": 336, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 336, "text": "```py\n>>> upsampled_logits = nn.functional.interpolate(\n... logits,\n... size=image.size[::-1],\n... mode=\"bilinear\",\n... align_corners=False,\n... )\n\n>>> pred_seg = upsampled_logits.argmax(dim=1)[0]\n```\n\nTo visualize the results, load the [dataset color palette](https://github.com/tensorflow/models/blob/3f1ca33afe3c1631b733ea7e40c294273b9e406d/research/deeplab/utils/get_dataset_colormap.py#L51) as `ade_palette()` that maps each class to their RGB values.", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Inference", "char_start": 18213, "char_end": 18685, "token_estimate": 118, "prev_chunk_id": 335, "next_chunk_id": 337, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 337, "text": "```py\ndef ade_palette():\n return np.asarray([\n [0, 0, 0],\n [120, 120, 120],\n [180, 120, 120],\n [6, 230, 230],\n [80, 50, 50],\n [4, 200, 3],\n [120, 120, 80],\n [140, 140, 140],\n [204, 5, 255],\n [230, 230, 230],\n [4, 250, 7],\n [224, 5, 255],\n [235, 255, 7],\n [150, 5, 61],\n [120, 120, 70],\n [8, 255, 51],\n [255, 6, 82],\n [143, 255, 140],\n [204, 255, 4],\n [255, 51, 7],\n [204, 70, 3],\n [0, 102, 200],\n [61, 230, 250],\n [255, 6, 51],\n [11, 102, 255],\n [255, 7, 71],\n [255, 9, 224],\n [9, 7, 230],\n [220, 220, 220],\n [255, 9, 92],\n [112, 9, 255],\n [8, 255, 214],\n [7, 255, 224],\n [255, 184, 6],\n [10, 255, 71],\n [255, 41, 10],\n [7, 255, 255],\n [224, 255, 8],\n [102, 8, 255],\n [255, 61, 6],\n [255, 194, 7],\n [255, 122, 8],\n [0, 255, 20],\n [255, 8, 41],\n [255, 5, 153],\n [6, 51, 255],\n [235, 12, 255],\n [160, 150, 20],\n [0, 163, 255],\n [140, 140, 140],\n [250, 10, 15],\n [20, 255, 0],\n [31, 255, 0],\n [255, 31, 0],\n [255, 224, 0],\n [153, 255, 0],\n [0, 0, 255],\n [255, 71, 0],\n [0, 235, 255],\n [0, 173, 255],\n [31, 0, 255],\n [11, 200, 200],\n [255, 82, 0],\n [0, 255, 245],\n [0, 61, 255],\n [0, 255, 112],\n [0, 255, 133],\n [255, 0, 0],\n [255, 163, 0],\n [255, 102, 0],\n [194, 255, 0],\n [0, 143, 255],\n [51, 255, 0],\n [0, 82, 255],\n [0, 255, 41],\n [0, 255, 173],\n [10, 0, 255],\n [173, 255, 0],\n [0, 255, 153],\n [255, 92, 0],\n [255, 0, 255],\n [255, 0, 245],\n [255, 0, 102],\n [255, 173, 0],\n [255, 0, 20],\n [255, 184, 184],\n [0, 31, 255],\n [0, 255, 61],\n [0, 71, 255],\n [255, 0, 204],\n [0, 255, 194],\n [0, 255, 82],\n [0, 10, 255],\n [0, 112, 255],\n [51, 0, 255],\n [0, 194, 255],\n [0, 122, 255],\n [0, 255, 163],\n [255, 153, 0],\n [0, 255, 10],\n [255, 112, 0],\n [143, 255, 0],\n [82, 0, 255],\n [163, 255, 0],\n [255, 235, 0],\n [8, 184, 170],\n [133, 0, 255],\n [0, 255, 92],\n [184, 0, 255],\n [255, 0, 31],\n [0, 184, 255],\n [0, 214, 255],\n [255, 0, 112],\n [92, 255, 0],\n [0, 224, 255],\n [112, 224, 255],\n [70, 184, 160],\n [163, 0, 255],\n [153, 0, 255],\n [71, 255, 0],\n [255, 0, 163],\n [255, 204, 0],\n [255, 0, 143],\n [0, 255, 235],\n [133, 255, 0],\n [255, 0, 235],\n [245, 0, 255],\n [255, 0, 122],\n [255, 245, 0],\n [10, 190, 212],\n [214, 255, 0],\n [0, 204, 255],\n [20, 0, 255],\n [255, 255, 0],\n [0, 153, 255],\n [0, 41, 255],\n [0, 255, 204],\n [41, 0, 255],\n [41, 255, 0],\n [173, 0, 255],\n [0, 245, 255],\n [71, 0, 255],\n [122, 0, 255],\n [0, 255, 184],\n [0, 92, 255],\n [184, 255, 0],\n [0, 133, 255],\n [255, 214, 0],\n [25, 194, 194],\n [102, 255, 0],\n [92, 0, 255],\n ])\n```", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Inference", "char_start": 18687, "char_end": 21882, "token_estimate": 798, "prev_chunk_id": 336, "next_chunk_id": 338, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 338, "text": "Then you can combine and plot your image and the predicted segmentation map:\n\n```py\n>>> import matplotlib.pyplot as plt\n>>> import numpy as np\n\n>>> color_seg = np.zeros((pred_seg.shape[0], pred_seg.shape[1], 3), dtype=np.uint8)\n>>> palette = np.array(ade_palette())\n>>> for label, color in enumerate(palette):\n... color_seg[pred_seg == label, :] = color\n>>> color_seg = color_seg[..., ::-1] # convert to BGR\n\n>>> img = np.array(image) * 0.5 + color_seg * 0.5 # plot the image with the segmentation map\n>>> img = img.astype(np.uint8)\n\n>>> plt.figure(figsize=(15, 10))\n>>> plt.imshow(img)\n>>> plt.show()\n```", "source_file": "transformers/tasks/semantic_segmentation.md", "section_heading": "Inference", "char_start": 21884, "char_end": 22495, "token_estimate": 152, "prev_chunk_id": 337, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/tasks/semantic_segmentation", "doc_title": "Image Segmentation" }, { "chunk_id": 339, "text": "# Audio classification\n\nAudio classification - just like with text - assigns a class label as output from the input data. The only difference is instead of text inputs, you have raw audio waveforms. Some practical applications of audio classification include identifying speaker intent, language classification, and even animal species by their sounds.\n\nThis guide will show you how to:\n\n1. Fine-tune [Wav2Vec2](https://huggingface.co/facebook/wav2vec2-base) on the [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) dataset to classify speaker intent.\n2. Use your fine-tuned model for inference.\n\nTo see all architectures and checkpoints compatible with this task, we recommend checking the [task-page](https://huggingface.co/tasks/audio-classification)\n\nBefore you begin, make sure you have all the necessary libraries installed:\n\n```bash\npip install transformers datasets evaluate soundfile librosa torchcodec\n```", "source_file": "transformers/tasks/audio_classification.md", "section_heading": "Audio classification", "char_start": 0, "char_end": 924, "token_estimate": 231, "prev_chunk_id": null, "next_chunk_id": 340, "url": "https://huggingface.co/docs/transformers/tasks/audio_classification", "doc_title": "Audio classification" }, { "chunk_id": 340, "text": "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:\n\n```py\n>>> from huggingface_hub import notebook_login\n\n>>> notebook_login()\n```", "source_file": "transformers/tasks/audio_classification.md", "section_heading": "Audio classification", "char_start": 926, "char_end": 1161, "token_estimate": 58, "prev_chunk_id": 339, "next_chunk_id": 341, "url": "https://huggingface.co/docs/transformers/tasks/audio_classification", "doc_title": "Audio classification" }, { "chunk_id": 341, "text": "## Load MInDS-14 dataset\n\nStart by loading the MInDS-14 dataset from the \ud83e\udd17 Datasets library:\n\n```py\n>>> from datasets import load_dataset, Audio\n\n>>> minds = load_dataset(\"PolyAI/minds14\", name=\"en-US\", split=\"train\")\n```\n\nSplit the dataset's `train` split into a smaller train and test set with the [train_test_split](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.train_test_split) method. This will give you a chance to experiment and make sure everything works before spending more time on the full dataset.\n\n```py\n>>> minds = minds.train_test_split(test_size=0.2)\n```\n\nThen take a look at the dataset:\n\n```py\n>>> minds\nDatasetDict({\n train: Dataset({\n features: ['path', 'audio', 'transcription', 'english_transcription', 'intent_class', 'lang_id'],\n num_rows: 450\n })\n test: Dataset({\n features: ['path', 'audio', 'transcription', 'english_transcription', 'intent_class', 'lang_id'],\n num_rows: 113\n })\n})\n```", "source_file": "transformers/tasks/audio_classification.md", "section_heading": "Load MInDS-14 dataset", "char_start": 1163, "char_end": 2166, "token_estimate": 250, "prev_chunk_id": 340, "next_chunk_id": 342, "url": "https://huggingface.co/docs/transformers/tasks/audio_classification", "doc_title": "Audio classification" }, { "chunk_id": 342, "text": "While the dataset contains a lot of useful information, like `lang_id` and `english_transcription`, you will focus on the `audio` and `intent_class` in this guide. Remove the other columns with the [remove_columns](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.remove_columns) method:\n\n```py\n>>> minds = minds.remove_columns([\"path\", \"transcription\", \"english_transcription\", \"lang_id\"])\n```\n\nHere's an example:\n\n```py\n>>> minds[\"train\"][0]\n{'audio': {'array': array([ 0. , 0. , 0. , ..., -0.00048828,\n -0.00024414, -0.00024414], dtype=float32),\n 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~APP_ERROR/602b9a5fbb1e6d0fbce91f52.wav',\n 'sampling_rate': 8000},\n 'intent_class': 2}\n```\n\nThere are two fields:", "source_file": "transformers/tasks/audio_classification.md", "section_heading": "Load MInDS-14 dataset", "char_start": 2168, "char_end": 3043, "token_estimate": 218, "prev_chunk_id": 341, "next_chunk_id": 343, "url": "https://huggingface.co/docs/transformers/tasks/audio_classification", "doc_title": "Audio classification" }, { "chunk_id": 343, "text": "- `audio`: a 1-dimensional `array` of the speech signal that must be called to load and resample the audio file.\n- `intent_class`: represents the class id of the speaker's intent.\n\nTo make it easier for the model to get the label name from the label id, create a dictionary that maps the label name to an integer and vice versa:\n\n```py\n>>> labels = minds[\"train\"].features[\"intent_class\"].names\n>>> label2id, id2label = dict(), dict()\n>>> for i, label in enumerate(labels):\n... label2id[label] = str(i)\n... id2label[str(i)] = label\n```\n\nNow you can convert the label id to a label name:\n\n```py\n>>> id2label[str(2)]\n'app_error'\n```", "source_file": "transformers/tasks/audio_classification.md", "section_heading": "Load MInDS-14 dataset", "char_start": 3045, "char_end": 3683, "token_estimate": 159, "prev_chunk_id": 342, "next_chunk_id": 344, "url": "https://huggingface.co/docs/transformers/tasks/audio_classification", "doc_title": "Audio classification" }, { "chunk_id": 344, "text": "## Preprocess\n\nThe next step is to load a Wav2Vec2 feature extractor to process the audio signal:\n\n```py\n>>> from transformers import AutoFeatureExtractor\n\n>>> feature_extractor = AutoFeatureExtractor.from_pretrained(\"facebook/wav2vec2-base\")\n```\n\nThe MInDS-14 dataset has a sampling rate of 8kHz (you can find this information in its [dataset card](https://huggingface.co/datasets/PolyAI/minds14)), which means you'll need to resample the dataset to 16kHz to use the pretrained Wav2Vec2 model:\n\n```py\n>>> minds = minds.cast_column(\"audio\", Audio(sampling_rate=16_000))\n>>> minds[\"train\"][0]\n{'audio': {'array': array([ 2.2098757e-05, 4.6582241e-05, -2.2803260e-05, ...,\n -2.8419291e-04, -2.3305941e-04, -1.1425107e-04], dtype=float32),\n 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~APP_ERROR/602b9a5fbb1e6d0fbce91f52.wav',\n 'sampling_rate': 16000},\n 'intent_class': 2}\n```\n\nNow create a preprocessing function that:", "source_file": "transformers/tasks/audio_classification.md", "section_heading": "Preprocess", "char_start": 3685, "char_end": 4701, "token_estimate": 254, "prev_chunk_id": 343, "next_chunk_id": 345, "url": "https://huggingface.co/docs/transformers/tasks/audio_classification", "doc_title": "Audio classification" }, { "chunk_id": 345, "text": "1. Calls the `audio` column to load, and if necessary, resample the audio file.\n2. Checks if the sampling rate of the audio file matches the sampling rate of the audio data a model was pretrained with. You can find this information in the Wav2Vec2 [model card](https://huggingface.co/facebook/wav2vec2-base).\n3. Set a maximum input length to batch longer inputs without truncating them.\n\n```py\n>>> def preprocess_function(examples):\n... audio_arrays = [x[\"array\"] for x in examples[\"audio\"]]\n... inputs = feature_extractor(\n... audio_arrays, sampling_rate=feature_extractor.sampling_rate, max_length=16000, truncation=True\n... )\n... return inputs\n```", "source_file": "transformers/tasks/audio_classification.md", "section_heading": "Preprocess", "char_start": 4703, "char_end": 5377, "token_estimate": 168, "prev_chunk_id": 344, "next_chunk_id": 346, "url": "https://huggingface.co/docs/transformers/tasks/audio_classification", "doc_title": "Audio classification" }, { "chunk_id": 346, "text": "To apply the preprocessing function over the entire dataset, use \ud83e\udd17 Datasets [map](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) function. You can speed up `map` by setting `batched=True` to process multiple elements of the dataset at once. Remove unnecessary columns and rename `intent_class` to `label`, as required by the model:\n\n```py\n>>> encoded_minds = minds.map(preprocess_function, remove_columns=\"audio\", batched=True)\n>>> encoded_minds = encoded_minds.rename_column(\"intent_class\", \"label\")\n```", "source_file": "transformers/tasks/audio_classification.md", "section_heading": "Preprocess", "char_start": 5379, "char_end": 5936, "token_estimate": 139, "prev_chunk_id": 345, "next_chunk_id": 347, "url": "https://huggingface.co/docs/transformers/tasks/audio_classification", "doc_title": "Audio classification" }, { "chunk_id": 347, "text": "## Evaluate\n\nIncluding a metric during training is often helpful for evaluating your model's performance. You can quickly load an evaluation method with the \ud83e\udd17 [Evaluate](https://huggingface.co/docs/evaluate/index) library. For this task, load the [accuracy](https://huggingface.co/spaces/evaluate-metric/accuracy) metric (see the \ud83e\udd17 Evaluate [quick tour](https://huggingface.co/docs/evaluate/a_quick_tour) to learn more about how to load and compute a metric):\n\n```py\n>>> import evaluate\n\n>>> accuracy = evaluate.load(\"accuracy\")\n```\n\nThen create a function that passes your predictions and labels to [compute](https://huggingface.co/docs/evaluate/v0.4.6/en/package_reference/main_classes#evaluate.EvaluationModule.compute) to calculate the accuracy:\n\n```py\n>>> import numpy as np\n\n>>> def compute_metrics(eval_pred):\n... predictions = np.argmax(eval_pred.predictions, axis=1)\n... return accuracy.compute(predictions=predictions, references=eval_pred.label_ids)\n```", "source_file": "transformers/tasks/audio_classification.md", "section_heading": "Evaluate", "char_start": 5938, "char_end": 6910, "token_estimate": 243, "prev_chunk_id": 346, "next_chunk_id": 348, "url": "https://huggingface.co/docs/transformers/tasks/audio_classification", "doc_title": "Audio classification" }, { "chunk_id": 348, "text": "Your `compute_metrics` function is ready to go now, and you'll return to it when you setup your training.", "source_file": "transformers/tasks/audio_classification.md", "section_heading": "Evaluate", "char_start": 6912, "char_end": 7017, "token_estimate": 26, "prev_chunk_id": 347, "next_chunk_id": 349, "url": "https://huggingface.co/docs/transformers/tasks/audio_classification", "doc_title": "Audio classification" }, { "chunk_id": 349, "text": "## Train\n\nIf you aren't familiar with finetuning a model with the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer), take a look at the basic tutorial [here](../training#train-with-pytorch-trainer)!\n\nYou're ready to start training your model now! Load Wav2Vec2 with [AutoModelForAudioClassification](/docs/transformers/v5.6.2/en/model_doc/auto#transformers.AutoModelForAudioClassification) along with the number of expected labels, and the label mappings:\n\n```py\n>>> from transformers import AutoModelForAudioClassification, TrainingArguments, Trainer\n\n>>> num_labels = len(id2label)\n>>> model = AutoModelForAudioClassification.from_pretrained(\n... \"facebook/wav2vec2-base\", num_labels=num_labels, label2id=label2id, id2label=id2label\n... )\n```\n\nAt this point, only three steps remain:", "source_file": "transformers/tasks/audio_classification.md", "section_heading": "Train", "char_start": 7019, "char_end": 7840, "token_estimate": 205, "prev_chunk_id": 348, "next_chunk_id": 350, "url": "https://huggingface.co/docs/transformers/tasks/audio_classification", "doc_title": "Audio classification" }, { "chunk_id": 350, "text": "1. Define your training hyperparameters in [TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments). The only required parameter is `output_dir`, which specifies where to save your model. You'll push this model to the Hub by setting `push_to_hub=True` (you need to be signed in to Hugging Face to upload your model). At the end of each epoch, the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) will evaluate the accuracy and save the training checkpoint.\n2. Pass the training arguments to [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) along with the model, dataset, tokenizer, data collator, and `compute_metrics` function.\n3. Call [train()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.train) to fine-tune your model.", "source_file": "transformers/tasks/audio_classification.md", "section_heading": "Train", "char_start": 7842, "char_end": 8702, "token_estimate": 215, "prev_chunk_id": 349, "next_chunk_id": 351, "url": "https://huggingface.co/docs/transformers/tasks/audio_classification", "doc_title": "Audio classification" }, { "chunk_id": 351, "text": "```py\n>>> training_args = TrainingArguments(\n... output_dir=\"my_awesome_mind_model\",\n... eval_strategy=\"epoch\",\n... save_strategy=\"epoch\",\n... learning_rate=3e-5,\n... per_device_train_batch_size=32,\n... gradient_accumulation_steps=4,\n... per_device_eval_batch_size=32,\n... num_train_epochs=10,\n... warmup_steps=0.1,\n... logging_steps=10,\n... load_best_model_at_end=True,\n... metric_for_best_model=\"accuracy\",\n... push_to_hub=True,\n... report_to=\"trackio\",\n... )\n\n>>> trainer = Trainer(\n... model=model,\n... args=training_args,\n... train_dataset=encoded_minds[\"train\"],\n... eval_dataset=encoded_minds[\"test\"],\n... processing_class=feature_extractor,\n... compute_metrics=compute_metrics,\n... )\n\n>>> trainer.train()\n```\n\nOnce training is completed, share your model to the Hub with the [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.push_to_hub) method so everyone can use your model:", "source_file": "transformers/tasks/audio_classification.md", "section_heading": "Train", "char_start": 8704, "char_end": 9705, "token_estimate": 250, "prev_chunk_id": 350, "next_chunk_id": 352, "url": "https://huggingface.co/docs/transformers/tasks/audio_classification", "doc_title": "Audio classification" }, { "chunk_id": 352, "text": "```py\n>>> trainer.push_to_hub()\n```\n\nFor a more in-depth example of how to fine-tune a model for audio classification, take a look at the corresponding [PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/audio_classification.ipynb).", "source_file": "transformers/tasks/audio_classification.md", "section_heading": "Train", "char_start": 9707, "char_end": 9988, "token_estimate": 70, "prev_chunk_id": 351, "next_chunk_id": 353, "url": "https://huggingface.co/docs/transformers/tasks/audio_classification", "doc_title": "Audio classification" }, { "chunk_id": 353, "text": "## Inference\n\nGreat, now that you've fine-tuned a model, you can use it for inference!\n\nLoad an audio file for inference. Remember to resample the sampling rate of the audio file to match the model's sampling rate, if necessary.\n\n```py\n>>> from datasets import load_dataset, Audio\n\n>>> dataset = load_dataset(\"PolyAI/minds14\", name=\"en-US\", split=\"train\")\n>>> dataset = dataset.cast_column(\"audio\", Audio(sampling_rate=16000))\n>>> sampling_rate = dataset.features[\"audio\"].sampling_rate\n>>> audio_file = dataset[0][\"audio\"][\"path\"]\n```\n\nThe simplest way to try out your fine-tuned model for inference is to use it in a [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline). Instantiate a `pipeline` for audio classification with your model, and pass your audio file to it:", "source_file": "transformers/tasks/audio_classification.md", "section_heading": "Inference", "char_start": 9990, "char_end": 10796, "token_estimate": 201, "prev_chunk_id": 352, "next_chunk_id": 354, "url": "https://huggingface.co/docs/transformers/tasks/audio_classification", "doc_title": "Audio classification" }, { "chunk_id": 354, "text": "```py\n>>> from transformers import pipeline\n\n>>> classifier = pipeline(\"audio-classification\", model=\"stevhliu/my_awesome_minds_model\")\n>>> classifier(audio_file)\n[\n {'score': 0.09766869246959686, 'label': 'cash_deposit'},\n {'score': 0.07998877018690109, 'label': 'app_error'},\n {'score': 0.0781070664525032, 'label': 'joint_account'},\n {'score': 0.07667109370231628, 'label': 'pay_bill'},\n {'score': 0.0755252093076706, 'label': 'balance'}\n]\n```\n\nYou can also manually replicate the results of the `pipeline` if you'd like:\n\nLoad a feature extractor to preprocess the audio file and return the `input` as PyTorch tensors:\n\n```py\n>>> from transformers import AutoFeatureExtractor\n\n>>> feature_extractor = AutoFeatureExtractor.from_pretrained(\"stevhliu/my_awesome_minds_model\")\n>>> inputs = feature_extractor(dataset[0][\"audio\"][\"array\"], sampling_rate=sampling_rate, return_tensors=\"pt\")\n```\n\nPass your inputs to the model and return the logits:", "source_file": "transformers/tasks/audio_classification.md", "section_heading": "Inference", "char_start": 10798, "char_end": 11758, "token_estimate": 240, "prev_chunk_id": 353, "next_chunk_id": 355, "url": "https://huggingface.co/docs/transformers/tasks/audio_classification", "doc_title": "Audio classification" }, { "chunk_id": 355, "text": "```py\n>>> from transformers import AutoModelForAudioClassification\n\n>>> model = AutoModelForAudioClassification.from_pretrained(\"stevhliu/my_awesome_minds_model\")\n>>> with torch.no_grad():\n... logits = model(**inputs).logits\n```\n\nGet the class with the highest probability, and use the model's `id2label` mapping to convert it to a label:\n\n```py\n>>> import torch\n\n>>> predicted_class_ids = torch.argmax(logits).item()\n>>> predicted_label = model.config.id2label[predicted_class_ids]\n>>> predicted_label\n'cash_deposit'\n```", "source_file": "transformers/tasks/audio_classification.md", "section_heading": "Inference", "char_start": 11760, "char_end": 12285, "token_estimate": 131, "prev_chunk_id": 354, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/tasks/audio_classification", "doc_title": "Audio classification" }, { "chunk_id": 356, "text": "# Automatic speech recognition\n\nAutomatic speech recognition (ASR) converts a speech signal to text, mapping a sequence of audio inputs to text outputs. Virtual assistants like Siri and Alexa use ASR models to help users every day, and there are many other useful user-facing applications like live captioning and note-taking during meetings.\n\nThis guide will show you how to:\n\n1. Fine-tune [Wav2Vec2](https://huggingface.co/facebook/wav2vec2-base) on the [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) dataset to transcribe audio to text.\n2. Use your fine-tuned model for inference.\n\nTo see all architectures and checkpoints compatible with this task, we recommend checking the [task-page](https://huggingface.co/tasks/automatic-speech-recognition)\n\nBefore you begin, make sure you have all the necessary libraries installed:\n\n```bash\npip install transformers datasets evaluate jiwer soundfile librosa torchcodec\n```", "source_file": "transformers/tasks/asr.md", "section_heading": "Automatic speech recognition", "char_start": 0, "char_end": 929, "token_estimate": 232, "prev_chunk_id": null, "next_chunk_id": 357, "url": "https://huggingface.co/docs/transformers/tasks/asr", "doc_title": "Automatic speech recognition" }, { "chunk_id": 357, "text": "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:\n\n```py\n>>> from huggingface_hub import notebook_login\n\n>>> notebook_login()\n```", "source_file": "transformers/tasks/asr.md", "section_heading": "Automatic speech recognition", "char_start": 931, "char_end": 1166, "token_estimate": 58, "prev_chunk_id": 356, "next_chunk_id": 358, "url": "https://huggingface.co/docs/transformers/tasks/asr", "doc_title": "Automatic speech recognition" }, { "chunk_id": 358, "text": "## Load MInDS-14 dataset\n\nStart by loading a smaller subset of the [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) dataset from the \ud83e\udd17 Datasets library. This will give you a chance to experiment and make sure everything works before spending more time training on the full dataset.\n\n```py\n>>> from datasets import load_dataset, Audio\n\n>>> minds = load_dataset(\"PolyAI/minds14\", name=\"en-US\", split=\"train[:100]\")\n```\n\nSplit the dataset's `train` split into a train and test set with the `~Dataset.train_test_split` method:\n\n```py\n>>> minds = minds.train_test_split(test_size=0.2)\n```\n\nThen take a look at the dataset:\n\n```py\n>>> minds\nDatasetDict({\n train: Dataset({\n features: ['path', 'audio', 'transcription', 'english_transcription', 'intent_class', 'lang_id'],\n num_rows: 16\n })\n test: Dataset({\n features: ['path', 'audio', 'transcription', 'english_transcription', 'intent_class', 'lang_id'],\n num_rows: 4\n })\n})\n```", "source_file": "transformers/tasks/asr.md", "section_heading": "Load MInDS-14 dataset", "char_start": 1168, "char_end": 2141, "token_estimate": 243, "prev_chunk_id": 357, "next_chunk_id": 359, "url": "https://huggingface.co/docs/transformers/tasks/asr", "doc_title": "Automatic speech recognition" }, { "chunk_id": 359, "text": "While the dataset contains a lot of useful information, like `lang_id` and `english_transcription`, this guide focuses on the `audio` and `transcription`. Remove the other columns with the [remove_columns](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.remove_columns) method:\n\n```py\n>>> minds = minds.remove_columns([\"english_transcription\", \"intent_class\", \"lang_id\"])\n```\n\nReview the example again:", "source_file": "transformers/tasks/asr.md", "section_heading": "Load MInDS-14 dataset", "char_start": 2143, "char_end": 2592, "token_estimate": 112, "prev_chunk_id": 358, "next_chunk_id": 360, "url": "https://huggingface.co/docs/transformers/tasks/asr", "doc_title": "Automatic speech recognition" }, { "chunk_id": 360, "text": "```py\n>>> minds[\"train\"][0]\n{'audio': {'array': array([-0.00024414, 0. , 0. , ..., 0.00024414,\n 0.00024414, 0.00024414], dtype=float32),\n 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~APP_ERROR/602ba9e2963e11ccd901cd4f.wav',\n 'sampling_rate': 8000},\n 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~APP_ERROR/602ba9e2963e11ccd901cd4f.wav',\n 'transcription': \"hi I'm trying to use the banking app on my phone and currently my checking and savings account balance is not refreshing\"}\n```\n\nThere are two fields:\n\n- `audio`: a 1-dimensional `array` of the speech signal that must be called to load and resample the audio file.\n- `transcription`: the target text.", "source_file": "transformers/tasks/asr.md", "section_heading": "Load MInDS-14 dataset", "char_start": 2594, "char_end": 3455, "token_estimate": 215, "prev_chunk_id": 359, "next_chunk_id": 361, "url": "https://huggingface.co/docs/transformers/tasks/asr", "doc_title": "Automatic speech recognition" }, { "chunk_id": 361, "text": "## Preprocess\n\nThe next step is to load a Wav2Vec2 processor to process the audio signal:\n\n```py\n>>> from transformers import AutoProcessor\n\n>>> processor = AutoProcessor.from_pretrained(\"facebook/wav2vec2-base\")\n```\n\nThe MInDS-14 dataset has a sampling rate of 8000Hz (you can find this information in its [dataset card](https://huggingface.co/datasets/PolyAI/minds14)), which means you'll need to resample the dataset to 16000Hz to use the pretrained Wav2Vec2 model:", "source_file": "transformers/tasks/asr.md", "section_heading": "Preprocess", "char_start": 3457, "char_end": 3925, "token_estimate": 117, "prev_chunk_id": 360, "next_chunk_id": 362, "url": "https://huggingface.co/docs/transformers/tasks/asr", "doc_title": "Automatic speech recognition" }, { "chunk_id": 362, "text": "```py\n>>> minds = minds.cast_column(\"audio\", Audio(sampling_rate=16_000))\n>>> minds[\"train\"][0]\n{'audio': {'array': array([-2.38064706e-04, -1.58618059e-04, -5.43987835e-06, ...,\n 2.78103951e-04, 2.38446111e-04, 1.18740834e-04], dtype=float32),\n 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~APP_ERROR/602ba9e2963e11ccd901cd4f.wav',\n 'sampling_rate': 16000},\n 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~APP_ERROR/602ba9e2963e11ccd901cd4f.wav',\n 'transcription': \"hi I'm trying to use the banking app on my phone and currently my checking and savings account balance is not refreshing\"}\n```\n\nAs you can see in the `transcription` above, the text contains a mix of uppercase and lowercase characters. The Wav2Vec2 tokenizer is only trained on uppercase characters so you'll need to make sure the text matches the tokenizer's vocabulary:", "source_file": "transformers/tasks/asr.md", "section_heading": "Preprocess", "char_start": 3927, "char_end": 4953, "token_estimate": 256, "prev_chunk_id": 361, "next_chunk_id": 363, "url": "https://huggingface.co/docs/transformers/tasks/asr", "doc_title": "Automatic speech recognition" }, { "chunk_id": 363, "text": "```py\n>>> def uppercase(example):\n... return {\"transcription\": example[\"transcription\"].upper()}\n\n>>> minds = minds.map(uppercase)\n```\n\nNow create a preprocessing function that:\n\n1. Calls the `audio` column to load and resample the audio file.\n2. Extracts the `input_values` from the audio file and tokenize the `transcription` column with the processor.\n\n```py\n>>> def prepare_dataset(batch):\n... audio = batch[\"audio\"]\n... batch = processor(audio[\"array\"], sampling_rate=audio[\"sampling_rate\"], text=batch[\"transcription\"])\n... batch[\"input_length\"] = len(batch[\"input_values\"][0])\n... return batch\n```", "source_file": "transformers/tasks/asr.md", "section_heading": "Preprocess", "char_start": 4955, "char_end": 5579, "token_estimate": 156, "prev_chunk_id": 362, "next_chunk_id": 364, "url": "https://huggingface.co/docs/transformers/tasks/asr", "doc_title": "Automatic speech recognition" }, { "chunk_id": 364, "text": "To apply the preprocessing function over the entire dataset, use \ud83e\udd17 Datasets [map](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.map) function. You can speed up `map` by increasing the number of processes with the `num_proc` parameter. Remove the columns you don't need with the [remove_columns](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset.remove_columns) method:\n\n```py\n>>> encoded_minds = minds.map(prepare_dataset, remove_columns=minds.column_names[\"train\"], num_proc=4)\n```", "source_file": "transformers/tasks/asr.md", "section_heading": "Preprocess", "char_start": 5581, "char_end": 6157, "token_estimate": 144, "prev_chunk_id": 363, "next_chunk_id": 365, "url": "https://huggingface.co/docs/transformers/tasks/asr", "doc_title": "Automatic speech recognition" }, { "chunk_id": 365, "text": "\ud83e\udd17 Transformers doesn't have a data collator for ASR, so you'll need to adapt the [DataCollatorWithPadding](/docs/transformers/v5.6.2/en/main_classes/data_collator#transformers.DataCollatorWithPadding) to create a batch of examples. It'll also dynamically pad your text and labels to the length of the longest element in its batch (instead of the entire dataset) so they are a uniform length. While it is possible to pad your text in the `tokenizer` function by setting `padding=True`, dynamic padding is more efficient.\n\nUnlike other data collators, this specific data collator needs to apply a different padding method to `input_values` and `labels`:", "source_file": "transformers/tasks/asr.md", "section_heading": "Preprocess", "char_start": 6159, "char_end": 6810, "token_estimate": 162, "prev_chunk_id": 364, "next_chunk_id": 366, "url": "https://huggingface.co/docs/transformers/tasks/asr", "doc_title": "Automatic speech recognition" }, { "chunk_id": 366, "text": "```py\n>>> import torch\n\n>>> from dataclasses import dataclass, field\n>>> from typing import Any, Dict, List, Optional, Union\n\n>>> @dataclass\n... class DataCollatorCTCWithPadding:\n... processor: AutoProcessor\n... padding: Union[bool, str] = \"longest\"\n\n... def __call__(self, features: list[dict[str, Union[list[int], torch.Tensor]]]) -> dict[str, torch.Tensor]:\n... # split inputs and labels since they have to be of different lengths and need\n... # different padding methods\n... input_features = [{\"input_values\": feature[\"input_values\"][0]} for feature in features]\n... label_features = [{\"input_ids\": feature[\"labels\"]} for feature in features]\n\n... batch = self.processor.pad(input_features, padding=self.padding, return_tensors=\"pt\")\n\n... labels_batch = self.processor.pad(labels=label_features, padding=self.padding, return_tensors=\"pt\")\n\n... # replace padding with -100 to ignore loss correctly\n... labels = labels_batch[\"input_ids\"].masked_fill(labels_batch.attention_mask.ne(1), -100)\n\n... batch[\"labels\"] = labels\n\n... return batch\n```", "source_file": "transformers/tasks/asr.md", "section_heading": "Preprocess", "char_start": 6812, "char_end": 7948, "token_estimate": 284, "prev_chunk_id": 365, "next_chunk_id": 367, "url": "https://huggingface.co/docs/transformers/tasks/asr", "doc_title": "Automatic speech recognition" }, { "chunk_id": 367, "text": "Now instantiate your `DataCollatorForCTCWithPadding`:\n\n```py\n>>> data_collator = DataCollatorCTCWithPadding(processor=processor, padding=\"longest\")\n```", "source_file": "transformers/tasks/asr.md", "section_heading": "Preprocess", "char_start": 7950, "char_end": 8101, "token_estimate": 37, "prev_chunk_id": 366, "next_chunk_id": 368, "url": "https://huggingface.co/docs/transformers/tasks/asr", "doc_title": "Automatic speech recognition" }, { "chunk_id": 368, "text": "## Evaluate\n\nIncluding a metric during training is often helpful for evaluating your model's performance. You can quickly load an evaluation method with the \ud83e\udd17 [Evaluate](https://huggingface.co/docs/evaluate/index) library. For this task, load the [word error rate](https://huggingface.co/spaces/evaluate-metric/wer) (WER) metric (refer to the \ud83e\udd17 Evaluate [quick tour](https://huggingface.co/docs/evaluate/a_quick_tour) to learn more about loading and computing metrics):\n\n```py\n>>> import evaluate\n\n>>> wer = evaluate.load(\"wer\")\n```\n\nThen create a function that passes your predictions and labels to [compute](https://huggingface.co/docs/evaluate/v0.4.6/en/package_reference/main_classes#evaluate.EvaluationModule.compute) to calculate the WER:", "source_file": "transformers/tasks/asr.md", "section_heading": "Evaluate", "char_start": 8103, "char_end": 8847, "token_estimate": 186, "prev_chunk_id": 367, "next_chunk_id": 369, "url": "https://huggingface.co/docs/transformers/tasks/asr", "doc_title": "Automatic speech recognition" }, { "chunk_id": 369, "text": "```py\n>>> import numpy as np\n\n>>> def compute_metrics(pred):\n... pred_logits = pred.predictions\n... pred_ids = np.argmax(pred_logits, axis=-1)\n\n... pred.label_ids[pred.label_ids == -100] = processor.tokenizer.pad_token_id\n\n... pred_str = processor.batch_decode(pred_ids)\n... label_str = processor.batch_decode(pred.label_ids, group_tokens=False)\n\n... wer_score = wer.compute(predictions=pred_str, references=label_str)\n\n... return {\"wer\": wer_score}\n```\n\nYour `compute_metrics` function is ready to go now, and you'll return to it when you setup your training.", "source_file": "transformers/tasks/asr.md", "section_heading": "Evaluate", "char_start": 8849, "char_end": 9437, "token_estimate": 147, "prev_chunk_id": 368, "next_chunk_id": 370, "url": "https://huggingface.co/docs/transformers/tasks/asr", "doc_title": "Automatic speech recognition" }, { "chunk_id": 370, "text": "## Train\n\nIf you aren't familiar with finetuning a model with the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer), take a look at the basic tutorial [here](../training#train-with-pytorch-trainer)!\n\nYou are now ready to start training your model! Load Wav2Vec2 with [AutoModelForCTC](/docs/transformers/v5.6.2/en/model_doc/auto#transformers.AutoModelForCTC). Specify the reduction to apply with the `ctc_loss_reduction` parameter. It is often better to use the average instead of the default summation:\n\n```py\n>>> from transformers import AutoModelForCTC, TrainingArguments, Trainer\n\n>>> model = AutoModelForCTC.from_pretrained(\n... \"facebook/wav2vec2-base\",\n... ctc_loss_reduction=\"mean\",\n... pad_token_id=processor.tokenizer.pad_token_id,\n... )\n```\n\nAt this point, only three steps remain:", "source_file": "transformers/tasks/asr.md", "section_heading": "Train", "char_start": 9439, "char_end": 10275, "token_estimate": 209, "prev_chunk_id": 369, "next_chunk_id": 371, "url": "https://huggingface.co/docs/transformers/tasks/asr", "doc_title": "Automatic speech recognition" }, { "chunk_id": 371, "text": "1. Define your training hyperparameters in [TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments). The only required parameter is `output_dir` which specifies where to save your model. You'll push this model to the Hub by setting `push_to_hub=True` (you need to be signed in to Hugging Face to upload your model). At the end of each epoch, the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) will evaluate the WER and save the training checkpoint.\n2. Pass the training arguments to [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) along with the model, dataset, tokenizer, data collator, and `compute_metrics` function.\n3. Call [train()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.train) to fine-tune your model.", "source_file": "transformers/tasks/asr.md", "section_heading": "Train", "char_start": 10277, "char_end": 11131, "token_estimate": 213, "prev_chunk_id": 370, "next_chunk_id": 372, "url": "https://huggingface.co/docs/transformers/tasks/asr", "doc_title": "Automatic speech recognition" }, { "chunk_id": 372, "text": "```py\n>>> training_args = TrainingArguments(\n... output_dir=\"my_awesome_asr_mind_model\",\n... per_device_train_batch_size=8,\n... gradient_accumulation_steps=2,\n... learning_rate=1e-5,\n... warmup_steps=500,\n... max_steps=2000,\n... gradient_checkpointing=True,\n... fp16=True,\n... train_sampling_strategy=\"group_by_length\",\n... eval_strategy=\"steps\",\n... per_device_eval_batch_size=8,\n... save_steps=1000,\n... eval_steps=1000,\n... logging_steps=25,\n... load_best_model_at_end=True,\n... metric_for_best_model=\"wer\",\n... greater_is_better=False,\n... push_to_hub=True,\n... report_to=\"trackio\",\n... )\n\n>>> trainer = Trainer(\n... model=model,\n... args=training_args,\n... train_dataset=encoded_minds[\"train\"],\n... eval_dataset=encoded_minds[\"test\"],\n... processing_class=processor,\n... data_collator=data_collator,\n... compute_metrics=compute_metrics,\n... )\n\n>>> trainer.train()\n```", "source_file": "transformers/tasks/asr.md", "section_heading": "Train", "char_start": 11133, "char_end": 12109, "token_estimate": 244, "prev_chunk_id": 371, "next_chunk_id": 373, "url": "https://huggingface.co/docs/transformers/tasks/asr", "doc_title": "Automatic speech recognition" }, { "chunk_id": 373, "text": "Once training is completed, share your model to the Hub with the [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.push_to_hub) method so it can be accessible to everyone:\n\n```py\n>>> trainer.push_to_hub()\n```\n\nFor a more in-depth example of how to fine-tune a model for automatic speech recognition, take a look at this blog [post](https://huggingface.co/blog/fine-tune-wav2vec2-english) for English ASR and this [post](https://huggingface.co/blog/fine-tune-xlsr-wav2vec2) for multilingual ASR.", "source_file": "transformers/tasks/asr.md", "section_heading": "Train", "char_start": 12111, "char_end": 12642, "token_estimate": 132, "prev_chunk_id": 372, "next_chunk_id": 374, "url": "https://huggingface.co/docs/transformers/tasks/asr", "doc_title": "Automatic speech recognition" }, { "chunk_id": 374, "text": "## Inference\n\nGreat, now that you've fine-tuned a model, you can use it for inference!\n\nLoad an audio file you'd like to run inference on. Remember to resample the sampling rate of the audio file to match the sampling rate of the model if you need to!\n\n```py\n>>> from datasets import load_dataset, Audio\n\n>>> dataset = load_dataset(\"PolyAI/minds14\", \"en-US\", split=\"train\")\n>>> dataset = dataset.cast_column(\"audio\", Audio(sampling_rate=16000))\n>>> sampling_rate = dataset.features[\"audio\"].sampling_rate\n>>> audio_file = dataset[0][\"audio\"][\"path\"]\n```\n\nThe simplest way to try out your fine-tuned model for inference is to use it in a [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline). Instantiate a `pipeline` for automatic speech recognition with your model, and pass your audio file to it:", "source_file": "transformers/tasks/asr.md", "section_heading": "Inference", "char_start": 12644, "char_end": 13476, "token_estimate": 208, "prev_chunk_id": 373, "next_chunk_id": 375, "url": "https://huggingface.co/docs/transformers/tasks/asr", "doc_title": "Automatic speech recognition" }, { "chunk_id": 375, "text": "```py\n>>> from transformers import pipeline\n\n>>> transcriber = pipeline(\"automatic-speech-recognition\", model=\"stevhliu/my_awesome_asr_minds_model\")\n>>> transcriber(audio_file)\n{'text': 'I WOUD LIKE O SET UP JOINT ACOUNT WTH Y PARTNER'}\n```\n\nThe transcription is decent, but it could be better! Try finetuning your model on more examples to get even better results!\n\nYou can also manually replicate the results of the `pipeline` if you'd like:\n\nLoad a processor to preprocess the audio file and transcription and return the `input` as PyTorch tensors:\n\n```py\n>>> from transformers import AutoProcessor\n\n>>> processor = AutoProcessor.from_pretrained(\"stevhliu/my_awesome_asr_mind_model\")\n>>> inputs = processor(dataset[0][\"audio\"][\"array\"], sampling_rate=sampling_rate, return_tensors=\"pt\")\n```\n\nPass your inputs to the model and return the logits:", "source_file": "transformers/tasks/asr.md", "section_heading": "Inference", "char_start": 13478, "char_end": 14325, "token_estimate": 211, "prev_chunk_id": 374, "next_chunk_id": 376, "url": "https://huggingface.co/docs/transformers/tasks/asr", "doc_title": "Automatic speech recognition" }, { "chunk_id": 376, "text": "```py\n>>> from transformers import AutoModelForCTC\n\n>>> model = AutoModelForCTC.from_pretrained(\"stevhliu/my_awesome_asr_mind_model\")\n>>> with torch.no_grad():\n... logits = model(**inputs).logits\n```\n\nGet the predicted `input_ids` with the highest probability, and use the processor to decode the predicted `input_ids` back into text:\n\n```py\n>>> import torch\n\n>>> predicted_ids = torch.argmax(logits, dim=-1)\n>>> transcription = processor.batch_decode(predicted_ids)\n>>> transcription\n['I WOUL LIKE O SET UP JOINT ACOUNT WTH Y PARTNER']\n```", "source_file": "transformers/tasks/asr.md", "section_heading": "Inference", "char_start": 14327, "char_end": 14871, "token_estimate": 136, "prev_chunk_id": 375, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/tasks/asr", "doc_title": "Automatic speech recognition" }, { "chunk_id": 377, "text": "# Parallelism methods\n\nMulti-GPU setups are effective for accelerating training and fitting large models in memory that otherwise wouldn't fit on a single GPU. It relies on parallelizing the workload across GPUs. There are several types of parallelism such as data parallelism, tensor parallelism, pipeline parallelism, and model parallelism. Each type of parallelism splits the workload differently, whether it's the data or the model.\n\nThis guide will discuss the various parallelism methods, combining them, and choosing an appropriate strategy for your setup. For more details about distributed training, refer to the [Accelerate](https://hf.co/docs/accelerate/index) documentation.\n\nFor a comprehensive guide on scaling large language models, check out the [Ultrascale Playbook](https://huggingface.co/spaces/nanotron/ultrascale-playbook), which provides detailed strategies and best practices for training at scale.", "source_file": "transformers/perf_train_gpu_many.md", "section_heading": "Parallelism methods", "char_start": 0, "char_end": 921, "token_estimate": 230, "prev_chunk_id": null, "next_chunk_id": 378, "url": "https://huggingface.co/docs/transformers/perf_train_gpu_many", "doc_title": "Parallelism methods" }, { "chunk_id": 378, "text": "## Scalability strategy\n\nUse the [Model Memory Calculator](https://huggingface.co/spaces/hf-accelerate/model-memory-usage) to calculate how much memory a model requires. Then refer to the table below to select a strategy based on your setup.\n\n| setup | scenario | strategy |\n|---|---|---|\n| single node/multi-GPU | fits on single GPU | DistributedDataParallel or ZeRO |\n| | doesn't fit on single GPU | PipelineParallel, ZeRO or TensorParallel |\n| | largest model layer doesn't fit | TensorParallel or ZeRO |\n| multi-node/multi-GPU | fast inter-node connectivity (NVLink or NVSwitch) | ZeRO or 3D parallelism (PipelineParallel, TensorParallel, DataParallel) |\n| | slow inter-node connectivity | ZeRO or 3D parallelism (PipelineParallel, TensorParallel, DataParallel) |", "source_file": "transformers/perf_train_gpu_many.md", "section_heading": "Scalability strategy", "char_start": 923, "char_end": 1693, "token_estimate": 192, "prev_chunk_id": 377, "next_chunk_id": 379, "url": "https://huggingface.co/docs/transformers/perf_train_gpu_many", "doc_title": "Parallelism methods" }, { "chunk_id": 379, "text": "## Data parallelism\n\nData parallelism evenly distributes data across multiple GPUs. Each GPU holds a copy of the model and concurrently processes their portion of the data. At the end, the results from each GPU are synchronized and combined.\n\nData parallelism significantly reduces training time by processing data in parallel, and it is scalable to the number of GPUs available. However, synchronizing results from each GPU can add overhead.\n\nThere are two types of data parallelism, DataParallel (DP) and DistributedDataParallel (DDP).", "source_file": "transformers/perf_train_gpu_many.md", "section_heading": "Data parallelism", "char_start": 1695, "char_end": 2232, "token_estimate": 134, "prev_chunk_id": 378, "next_chunk_id": 380, "url": "https://huggingface.co/docs/transformers/perf_train_gpu_many", "doc_title": "Parallelism methods" }, { "chunk_id": 380, "text": "### DataParallel\n\n[DataParallel](https://pytorch.org/docs/stable/generated/torch.nn.DataParallel.html) supports distributed training on a *single machine* with multiple GPUs.\n\n1. The default GPU, `GPU 0`, reads a batch of data and sends a mini batch of it to the other GPUs.\n2. An up-to-date model is replicated from `GPU 0` to the other GPUs.\n3. A `forward` pass is performed on each GPU and their outputs are sent to `GPU 0` to compute the loss.\n4. The loss is distributed from `GPU 0` to the other GPUs for the `backward` pass.\n5. The gradients from each GPU are sent back to `GPU 0` and averaged.", "source_file": "transformers/perf_train_gpu_many.md", "section_heading": "DataParallel", "char_start": 2234, "char_end": 2834, "token_estimate": 150, "prev_chunk_id": 379, "next_chunk_id": 381, "url": "https://huggingface.co/docs/transformers/perf_train_gpu_many", "doc_title": "Parallelism methods" }, { "chunk_id": 381, "text": "### DistributedDataParallel\n\n[DistributedDataParallel](https://pytorch.org/docs/main/notes/ddp.html) supports distributed training across *multiple machines* with multiple GPUs.\n\n1. The main process replicates the model from the default GPU, `GPU 0`, to each GPU.\n2. Each GPU directly processes a mini batch of data.\n3. The local gradients are averaged across all GPUs during the `backward` pass.\n\nDDP is recommended because it reduces communication overhead between GPUs, efficiently utilizes each GPU, and scales to more than one machine.", "source_file": "transformers/perf_train_gpu_many.md", "section_heading": "DistributedDataParallel", "char_start": 2836, "char_end": 3376, "token_estimate": 135, "prev_chunk_id": 380, "next_chunk_id": 382, "url": "https://huggingface.co/docs/transformers/perf_train_gpu_many", "doc_title": "Parallelism methods" }, { "chunk_id": 382, "text": "### ZeRO data parallelism\n\n[Zero Redundancy Optimizer](https://www.deepspeed.ai/tutorials/zero/) is a more memory efficient type of data parallelism. It significantly improves memory efficiency by partitioning parameters, gradients, and optimizer states across data parallel processes to reduce memory usage. There are three ZeRO stages:\n\n- Stage 1 partitions the optimizer states\n- Stage 2 partitions the optimizer and gradient states\n- Stage 3 partitions the optimizer, gradient, and parameters", "source_file": "transformers/perf_train_gpu_many.md", "section_heading": "ZeRO data parallelism", "char_start": 3378, "char_end": 3874, "token_estimate": 124, "prev_chunk_id": 381, "next_chunk_id": 383, "url": "https://huggingface.co/docs/transformers/perf_train_gpu_many", "doc_title": "Parallelism methods" }, { "chunk_id": 383, "text": "## Model parallelism\n\nModel parallelism distributes a model across multiple GPUs. There are several ways to split a model, but the typical method distributes the model layers across GPUs. On the `forward` pass, the first GPU processes a batch of data and passes it to the next group of layers on the next GPU. For the `backward` pass, the data is sent backward from the final layer to the first layer.\n\nModel parallelism is a useful strategy for training models that are too large to fit into the memory of a single GPU. However, GPU utilization is unbalanced because only one GPU is active at a time. Passing results between GPUs also adds communication overhead and it can be a bottleneck.", "source_file": "transformers/perf_train_gpu_many.md", "section_heading": "Model parallelism", "char_start": 3883, "char_end": 4574, "token_estimate": 172, "prev_chunk_id": 382, "next_chunk_id": 384, "url": "https://huggingface.co/docs/transformers/perf_train_gpu_many", "doc_title": "Parallelism methods" }, { "chunk_id": 384, "text": "## Pipeline parallelism\n\nPipeline parallelism is conceptually very similar to model parallelism, but it's more efficient because it reduces the amount of idle GPU time. Instead of waiting for each GPU to finish processing a batch of data, pipeline parallelism creates *micro-batches* of data. As soon as one micro-batch is finished, it is passed to the next GPU. This way, each GPU can concurrently process part of the data without waiting for the other GPU to completely finish processing a mini batch of data.\n\nPipeline parallelism shares the same advantages as model parallelism, but it optimizes GPU utilization and reduces idle time. But pipeline parallelism can be more complex because models may need to be rewritten as a sequence of [nn.Sequential](https://pytorch.org/docs/stable/generated/torch.nn.Sequential.html) modules and it also isn't possible to completely reduce idle time because the last `forward` pass must also wait for the `backward` pass to finish.", "source_file": "transformers/perf_train_gpu_many.md", "section_heading": "Pipeline parallelism", "char_start": 4576, "char_end": 5548, "token_estimate": 243, "prev_chunk_id": 383, "next_chunk_id": 385, "url": "https://huggingface.co/docs/transformers/perf_train_gpu_many", "doc_title": "Parallelism methods" }, { "chunk_id": 385, "text": "## Tensor parallelism\n\nTensor parallelism distributes large tensor computations across multiple GPUs. The tensors are sliced horizontally or vertically and each slice is processed by a separate GPU. Each GPU performs its calculations on its tensor slice and the results are synchronized at the end to reconstruct the final result.\n\nTensor parallelism is effective for training large models that don't fit into the memory of a single GPU. It is also faster and more efficient because each GPU can process its tensor slice in parallel, and it can be combined with other parallelism methods. Like other parallelism methods though, tensor parallelism adds communication overhead between GPUs.\n\nRefer to the [Tensor parallelism](./perf_infer_gpu_multi) guide to learn how to use it for inference.", "source_file": "transformers/perf_train_gpu_many.md", "section_heading": "Tensor parallelism", "char_start": 5550, "char_end": 6341, "token_estimate": 197, "prev_chunk_id": 384, "next_chunk_id": 386, "url": "https://huggingface.co/docs/transformers/perf_train_gpu_many", "doc_title": "Parallelism methods" }, { "chunk_id": 386, "text": "## Hybrid parallelism\n\nParallelism methods can be combined to achieve even greater memory savings and more efficiently train models with billions of parameters.", "source_file": "transformers/perf_train_gpu_many.md", "section_heading": "Hybrid parallelism", "char_start": 6343, "char_end": 6503, "token_estimate": 40, "prev_chunk_id": 385, "next_chunk_id": 387, "url": "https://huggingface.co/docs/transformers/perf_train_gpu_many", "doc_title": "Parallelism methods" }, { "chunk_id": 387, "text": "### Data parallelism and pipeline parallelism\n\nData and pipeline parallelism distributes the data across GPUs and divides each mini batch of data into micro-batches to achieve pipeline parallelism.\n\nEach data parallel rank treats the process as if there were only one GPU instead of two, but GPUs 0 and 1 can offload micro-batches of data to GPUs 2 and 3 and reduce idle time.\n\nThis approach optimizes parallel data processing by reducing idle GPU utilization.", "source_file": "transformers/perf_train_gpu_many.md", "section_heading": "Data parallelism and pipeline parallelism", "char_start": 6505, "char_end": 6965, "token_estimate": 115, "prev_chunk_id": 386, "next_chunk_id": 388, "url": "https://huggingface.co/docs/transformers/perf_train_gpu_many", "doc_title": "Parallelism methods" }, { "chunk_id": 388, "text": "### ZeRO data parallelism, pipeline parallelism, and model parallelism (3D parallelism)\n\nData, pipeline and model parallelism combine to form [3D parallelism](https://www.microsoft.com/en-us/research/blog/deepspeed-extreme-scale-model-training-for-everyone/) to optimize memory and compute efficiency.\n\nMemory efficiency is achieved by splitting the model across GPUs and also dividing it into stages to create a pipeline. This allows GPUs to work in parallel on micro-batches of data, reducing the memory usage of the model, optimizer, and activations.\n\nCompute efficiency is enabled by ZeRO data parallelism where each GPU only stores a slice of the model, optimizer, and activations. This allows higher communication bandwidth between data parallel nodes because communication can occur independently or in parallel with the other pipeline stages.\n\nThis approach is scalable to extremely large models with trillions of parameters.", "source_file": "transformers/perf_train_gpu_many.md", "section_heading": "ZeRO data parallelism, pipeline parallelism, and model parallelism (3D parallelism)", "char_start": 6974, "char_end": 7907, "token_estimate": 233, "prev_chunk_id": 387, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/perf_train_gpu_many", "doc_title": "Parallelism methods" }, { "chunk_id": 389, "text": "# Overview\n\nQuantization lowers the memory requirements of loading and using a model by storing the weights in a lower precision while trying to preserve as much accuracy as possible. Weights are typically stored in full-precision (fp32) floating point representations, but half-precision (fp16 or bf16) are increasingly popular data types given the large size of models today. Some quantization methods can reduce the precision even further to integer representations, like int8 or int4.\n\nTransformers supports many quantization methods, each with their pros and cons, so you can pick the best one for your specific use case. Some methods require calibration for greater accuracy and extreme compression (1-2 bits), while other methods work out of the box with on-the-fly quantization.\n\nUse the Space below to help you pick a quantization method depending on your hardware and number of bits to quantize to.", "source_file": "transformers/quantization/overview.md", "section_heading": "Overview", "char_start": 0, "char_end": 908, "token_estimate": 227, "prev_chunk_id": null, "next_chunk_id": 390, "url": "https://huggingface.co/docs/transformers/quantization/overview", "doc_title": "Overview" }, { "chunk_id": 390, "text": "| Quantization Method | On the fly quantization | CPU | CUDA GPU | ROCm GPU | Metal (Apple Silicon) | Intel GPU | Torch compile() | Bits | PEFT Fine Tuning | Serializable with \ud83e\udd17Transformers | \ud83e\udd17Transformers Support | Link to library |\n|-------------------------------------------|----------------------|-----------------|----------|-----------|------------------------------------|-----------------|-----------------|--------------|------------------|-----------------------------|-------------------------|---------------------------------------------|\n| [AQLM](./aqlm) | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udfe2 | 1/2 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe2 | https://github.com/Vahe1994/AQLM |\n| [AutoRound](./auto_round) | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udd34 | 2/3/4/8 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udfe2 | https://github.com/intel/auto-round |\n| [AWQ](./awq) | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udfe2 | ? | 4 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe2 | https://github.com/casper-hansen/AutoAWQ |\n| [bitsandbytes](./bitsandbytes) | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe1 | \ud83d\udfe1 | \ud83d\udfe2 | \ud83d\udfe2 | 4/8 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe2 | https://github.com/bitsandbytes-foundation/bitsandbytes |\n| [compressed-tensors](./compressed_tensors) | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udd34 | 1/8 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe2 | https://github.com/neuralmagic/compressed-tensors |\n| [EETQ](./eetq) | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udd34 | ? | 8 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe2 | https://github.com/NetEase-FuXi/EETQ |\n| [Four Over Six](./fouroversix) | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udfe2 | 4 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udfe2 | https://github.com/mit-han-lab/fouroversix |\n| [FP-Quant](./fp_quant) | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udfe2 | 4 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udfe2 | https://github.com/IST-DASLab/FP-Quant |\n| [GGUF / GGML (llama.cpp)](../gguf) | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udd34 | 1/8 | \ud83d\udd34 | [See Notes](../gguf) | [See Notes](../gguf) | https://github.com/ggerganov/llama.cpp |\n| [GPT-QModel](./gptq) | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udd34 | 2/3/4/8 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe2 | https://github.com/ModelCloud/GPTQModel |\n| [HIGGS](./higgs) | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udfe2 | 2/4 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udfe2 | https://github.com/HanGuo97/flute |\n| [HQQ](./hqq) | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udfe2 | 1/8 | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udfe2 | https://github.com/mobiusml/hqq/ |\n| [Metal](./metal) | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udd34 | 2/4/8 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udfe2 | [Hub Kernels](https://huggingface.co/kernels-community/mlx-quantization-metal-kernels) |\n| [optimum-quanto](./quanto) | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe2 | 2/4/8 | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udfe2 | https://github.com/huggingface/optimum-quanto |\n| [SINQ](./sinq) | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe1 | \ud83d\udfe1 | \ud83d\udfe1 | \ud83d\udfe1 | 2/3/4/6/8 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udfe2 | https://github.com/huawei-csl/SINQ |\n| [FBGEMM_FP8](./fbgemm_fp8) | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udd34 | 8 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udfe2 | https://github.com/pytorch/FBGEMM |\n| [torchao](./torchao) | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udfe1 | \ud83d\udfe2 | | 4/8 | | \ud83d\udfe2\ud83d\udd34 | \ud83d\udfe2 | https://github.com/pytorch/ao |\n| [VPTQ](./vptq) | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udfe1 | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udfe2 | 1/8 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udfe2 | https://github.com/microsoft/VPTQ |\n| [FINEGRAINED_FP8](./finegrained_fp8) | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udd34 | 8 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udfe2 | Built-in |\n| [SpQR](./spqr) | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udfe2 | 3 | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udfe2 | https://github.com/Vahe1994/SpQR/ |\n| [Quark](./quark) | \ud83d\udd34 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe2 | \ud83d\udfe2 | ? | 2/4/6/8/9/16 | \ud83d\udd34 | \ud83d\udd34 | \ud83d\udfe2 | https://quark.docs.amd.com/latest/ |", "source_file": "transformers/quantization/overview.md", "section_heading": "Overview", "char_start": 910, "char_end": 7972, "token_estimate": 1765, "prev_chunk_id": 389, "next_chunk_id": 391, "url": "https://huggingface.co/docs/transformers/quantization/overview", "doc_title": "Overview" }, { "chunk_id": 391, "text": "## Resources\n\nIf you are new to quantization, we recommend checking out these beginner-friendly quantization courses in collaboration with DeepLearning.AI.\n\n* [Quantization Fundamentals with Hugging Face](https://www.deeplearning.ai/short-courses/quantization-fundamentals-with-hugging-face/)\n* [Quantization in Depth](https://www.deeplearning.ai/short-courses/quantization-in-depth)", "source_file": "transformers/quantization/overview.md", "section_heading": "Resources", "char_start": 7974, "char_end": 8357, "token_estimate": 95, "prev_chunk_id": 390, "next_chunk_id": 392, "url": "https://huggingface.co/docs/transformers/quantization/overview", "doc_title": "Overview" }, { "chunk_id": 392, "text": "## User-Friendly Quantization Tools\n\nIf you are looking for a user-friendly quantization experience, you can use the following community spaces and notebooks:\n\n* [Bitsandbytes Space](https://huggingface.co/spaces/bnb-community/bnb-my-repo)\n* [GGUF Space](https://huggingface.co/spaces/ggml-org/gguf-my-repo)\n* [MLX Space](https://huggingface.co/spaces/mlx-community/mlx-my-repo)\n* [AutoQuant Notebook](https://colab.research.google.com/drive/1b6nqC7UZVt8bx4MksX7s656GXPM-eWw4?usp=sharing#scrollTo=ZC9Nsr9u5WhN)", "source_file": "transformers/quantization/overview.md", "section_heading": "User-Friendly Quantization Tools", "char_start": 8359, "char_end": 8869, "token_estimate": 127, "prev_chunk_id": 391, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/quantization/overview", "doc_title": "Overview" }, { "chunk_id": 393, "text": "# Bitsandbytes\n\nThe [bitsandbytes](https://github.com/bitsandbytes-foundation/bitsandbytes) library provides quantization tools for LLMs through a lightweight Python wrapper around hardware accelerator functions. It enables working with large models using limited computational resources by reducing their memory footprint.\n\nAt its core, bitsandbytes provides:\n\n- **Quantized Linear Layers**: `Linear8bitLt` and `Linear4bit` layers that replace standard PyTorch linear layers with memory-efficient quantized alternatives\n- **Optimized Optimizers**: 8-bit versions of common optimizers through its `optim` module, enabling training of large models with reduced memory requirements\n- **Matrix Multiplication**: Optimized matrix multiplication operations that leverage the quantized format\n\nbitsandbytes offers two main quantization features:", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "Bitsandbytes", "char_start": 0, "char_end": 839, "token_estimate": 209, "prev_chunk_id": null, "next_chunk_id": 394, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 394, "text": "1. **LLM.int8()** - An 8-bit quantization method that makes inference more accessible without significant performance degradation. Unlike naive quantization, [LLM.int8()](https://hf.co/papers/2208.07339) dynamically preserves higher precision for critical computations, preventing information loss in sensitive parts of the model.\n\n2. **QLoRA** - A 4-bit quantization technique that compresses models even further while maintaining trainability by inserting a small set of trainable low-rank adaptation (LoRA) weights.\n\n> **Note:** For a user-friendly quantization experience, you can use the `bitsandbytes` [community space](https://huggingface.co/spaces/bnb-community/bnb-my-repo).\n\nRun the command below to install bitsandbytes.\n\n```bash\npip install --upgrade transformers accelerate bitsandbytes\n```\n\nTo compile from source, follow the instructions in the [bitsandbytes installation guide](https://huggingface.co/docs/bitsandbytes/main/en/installation).", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "Bitsandbytes", "char_start": 841, "char_end": 1798, "token_estimate": 239, "prev_chunk_id": 393, "next_chunk_id": 395, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 395, "text": "## Hardware Compatibility\n\nbitsandbytes is supported on NVIDIA GPUs for CUDA versions 11.8 - 13.0, Intel XPU, Intel Gaudi (HPU), and CPU. There is an ongoing effort to support additional platforms. If you're interested in providing feedback or testing, check out the [bitsandbytes repository](https://github.com/bitsandbytes-foundation/bitsandbytes) for more information.", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "Hardware Compatibility", "char_start": 1800, "char_end": 2171, "token_estimate": 92, "prev_chunk_id": 394, "next_chunk_id": 396, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 396, "text": "### NVIDIA GPUs (CUDA)\n\nThis backend is supported on Linux x86-64, Linux aarch64, and Windows platforms.\n\n| Feature | Minimum Hardware Requirement |\n|---------|-------------------------------|\n| 8-bit optimizers | NVIDIA Pascal (GTX 10X0 series, P100) or newer GPUs * |\n| LLM.int8() | NVIDIA Turing (RTX 20X0 series, T4) or newer GPUs |\n| NF4/FP4 quantization | NVIDIA Pascal (GTX 10X0 series, P100) or newer GPUs * |", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "NVIDIA GPUs (CUDA)", "char_start": 2173, "char_end": 2590, "token_estimate": 104, "prev_chunk_id": 395, "next_chunk_id": 397, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 397, "text": "### Intel GPUs (XPU)\n\nThis backend is supported on Linux x86-64 and Windows x86-64 platforms.", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "Intel GPUs (XPU)", "char_start": 2592, "char_end": 2685, "token_estimate": 23, "prev_chunk_id": 396, "next_chunk_id": 398, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 398, "text": "### Intel Gaudi (HPU)\n\nThis backend is supported on Linux x86-64 for Gaudi2 and Gaudi3.", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "Intel Gaudi (HPU)", "char_start": 2687, "char_end": 2774, "token_estimate": 21, "prev_chunk_id": 397, "next_chunk_id": 399, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 399, "text": "### CPU\n\nThis backend is supported on Linux x86-64, Linux aarch64, and Windows x86-64 platforms.", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "CPU", "char_start": 2776, "char_end": 2872, "token_estimate": 24, "prev_chunk_id": 398, "next_chunk_id": 400, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 400, "text": "## Quantization Examples\n\nQuantize a model by passing a [BitsAndBytesConfig](/docs/transformers/v5.6.2/en/main_classes/quantization#transformers.BitsAndBytesConfig) to [from_pretrained()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel.from_pretrained). This works for any model in any modality, as long as it supports [Accelerate](https://huggingface.co/docs/accelerate/index) and contains [torch.nn.Linear](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html) layers.\n\nQuantizing a model in 8-bit halves the memory-usage, and for large models, set `device_map=\"auto\"` to efficiently distribute the weights across all available GPUs.\n\n```py\nfrom transformers import AutoModelForCausalLM, BitsAndBytesConfig\n\nquantization_config = BitsAndBytesConfig(load_in_8bit=True)\n\nmodel_8bit = AutoModelForCausalLM.from_pretrained(\n \"bigscience/bloom-1b7\", \n device_map=\"auto\",\n quantization_config=quantization_config\n)\n```", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "Quantization Examples", "char_start": 2874, "char_end": 3836, "token_estimate": 240, "prev_chunk_id": 399, "next_chunk_id": 401, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 401, "text": "By default, all other modules such as [torch.nn.LayerNorm](https://pytorch.org/docs/stable/generated/torch.nn.LayerNorm.html) are set to the default torch dtype. You can change the data type of these modules with the `dtype` parameter. Setting `dtype=\"auto\"` loads the model in the data type defined in a model's `config.json` file.\n\n```py\nimport torch\nfrom transformers import AutoModelForCausalLM, BitsAndBytesConfig\n\nquantization_config = BitsAndBytesConfig(load_in_8bit=True)\n\nmodel_8bit = AutoModelForCausalLM.from_pretrained(\n \"facebook/opt-350m\", \n device_map=\"auto\",\n quantization_config=quantization_config, \n dtype=\"auto\"\n)\nmodel_8bit.model.decoder.layers[-1].final_layer_norm.weight.dtype\n```", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "Quantization Examples", "char_start": 3838, "char_end": 4553, "token_estimate": 178, "prev_chunk_id": 400, "next_chunk_id": 402, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 402, "text": "Once a model is quantized to 8-bit, you can't push the quantized weights to the Hub unless you're using the latest version of Transformers and bitsandbytes. If you have the latest versions, then you can push the 8-bit model to the Hub with [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.utils.PushToHubMixin.push_to_hub). The quantization config.json file is pushed first, followed by the quantized model weights.\n\n```py\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig\n\nquantization_config = BitsAndBytesConfig(load_in_8bit=True)\n\nmodel = AutoModelForCausalLM.from_pretrained(\n \"bigscience/bloom-560m\", \n device_map=\"auto\",\n quantization_config=quantization_config\n)\n\nmodel.push_to_hub(\"bloom-560m-8bit\")\n```\n\nQuantizing a model in 4-bit reduces your memory-usage by 4x, and for large models, set `device_map=\"auto\"` to efficiently distribute the weights across all available GPUs.", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "Quantization Examples", "char_start": 4555, "char_end": 5508, "token_estimate": 238, "prev_chunk_id": 401, "next_chunk_id": 403, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 403, "text": "```py\nfrom transformers import AutoModelForCausalLM, BitsAndBytesConfig\n\nquantization_config = BitsAndBytesConfig(load_in_4bit=True)\n\nmodel_4bit = AutoModelForCausalLM.from_pretrained(\n \"bigscience/bloom-1b7\",\n device_map=\"auto\",\n quantization_config=quantization_config\n)\n```\n\nBy default, all other modules such as [torch.nn.LayerNorm](https://pytorch.org/docs/stable/generated/torch.nn.LayerNorm.html) are converted to `torch.float16`. You can change the data type of these modules with the `dtype` parameter. Setting `dtype=\"auto\"` loads the model in the data type defined in a model's `config.json` file.\n\n```py\nimport torch\nfrom transformers import AutoModelForCausalLM, BitsAndBytesConfig\n\nquantization_config = BitsAndBytesConfig(load_in_4bit=True)\n\nmodel_4bit = AutoModelForCausalLM.from_pretrained(\n \"facebook/opt-350m\",\n device_map=\"auto\",\n quantization_config=quantization_config, \n dtype=\"auto\"\n)\nmodel_4bit.model.decoder.layers[-1].final_layer_norm.weight.dtype\n```", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "Quantization Examples", "char_start": 5510, "char_end": 6509, "token_estimate": 249, "prev_chunk_id": 402, "next_chunk_id": 404, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 404, "text": "Make sure you have the latest bitsandbytes version so you can serialize 4-bit models and push them to the Hub with [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.utils.PushToHubMixin.push_to_hub). Use [save_pretrained()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel.save_pretrained) to save the 4-bit model locally. \n\n```py\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig\n\nquantization_config = BitsAndBytesConfig(load_in_4bit=True)\n\nmodel = AutoModelForCausalLM.from_pretrained(\n \"bigscience/bloom-560m\", \n device_map=\"auto\",\n quantization_config=quantization_config\n)\n\nmodel.push_to_hub(\"bloom-560m-4bit\")\n```\n\n> [!WARNING]\n> 8 and 4-bit training is only supported for training *extra* parameters.\n\nCheck your memory footprint with `get_memory_footprint`.\n\n```py\nprint(model.get_memory_footprint())\n```", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "Quantization Examples", "char_start": 6511, "char_end": 7420, "token_estimate": 227, "prev_chunk_id": 403, "next_chunk_id": 405, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 405, "text": "Load quantized models with [from_pretrained()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) without a `quantization_config`.\n\n```py\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\nmodel = AutoModelForCausalLM.from_pretrained(\"{your_username}/bloom-560m-8bit\", device_map=\"auto\")\n```", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "Quantization Examples", "char_start": 7422, "char_end": 7767, "token_estimate": 86, "prev_chunk_id": 404, "next_chunk_id": 406, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 406, "text": "## LLM.int8\n\nThis section explores some of the specific features of 8-bit quantization, such as offloading, outlier thresholds, skipping module conversion, and finetuning.", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "LLM.int8", "char_start": 7769, "char_end": 7940, "token_estimate": 42, "prev_chunk_id": 405, "next_chunk_id": 407, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 407, "text": "### Offloading\n\n8-bit models can offload weights between the CPU and GPU to fit very large models into memory. The weights dispatched to the CPU are stored in **float32** and aren't converted to 8-bit. For example, enable offloading for [bigscience/bloom-1b7](https://huggingface.co/bigscience/bloom-1b7) through [BitsAndBytesConfig](/docs/transformers/v5.6.2/en/main_classes/quantization#transformers.BitsAndBytesConfig).\n\n```py\nfrom transformers import AutoModelForCausalLM, BitsAndBytesConfig\n\nquantization_config = BitsAndBytesConfig(llm_int8_enable_fp32_cpu_offload=True)\n```\n\nDesign a custom device map to fit everything on your GPU except for the `lm_head`, which is dispatched to the CPU.\n\n```py\ndevice_map = {\n \"transformer.word_embeddings\": 0,\n \"transformer.word_embeddings_layernorm\": 0,\n \"lm_head\": \"cpu\",\n \"transformer.h\": 0,\n \"transformer.ln_f\": 0,\n}\n```\n\nNow load your model with the custom `device_map` and `quantization_config`.", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "Offloading", "char_start": 7942, "char_end": 8902, "token_estimate": 240, "prev_chunk_id": 406, "next_chunk_id": 408, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 408, "text": "```py\nmodel_8bit = AutoModelForCausalLM.from_pretrained(\n \"bigscience/bloom-1b7\",\n dtype=\"auto\",\n device_map=device_map,\n quantization_config=quantization_config,\n)\n```", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "Offloading", "char_start": 8904, "char_end": 9084, "token_estimate": 45, "prev_chunk_id": 407, "next_chunk_id": 409, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 409, "text": "### Outlier threshold\n\nAn \"outlier\" is a hidden state value greater than a certain threshold, and these values are computed in fp16. While the values are usually normally distributed ([-3.5, 3.5]), this distribution can be very different for large models ([-60, 6] or [6, 60]). 8-bit quantization works well for values ~5, but beyond that, there is a significant performance penalty. A good default threshold value is 6, but a lower threshold may be needed for more unstable models (small models or finetuning).\n\nTo find the best threshold for your model, experiment with the `llm_int8_threshold` parameter in [BitsAndBytesConfig](/docs/transformers/v5.6.2/en/main_classes/quantization#transformers.BitsAndBytesConfig). For example, setting the threshold to `0.0` significantly speeds up inference at the potential cost of some accuracy loss.", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "Outlier threshold", "char_start": 9086, "char_end": 9928, "token_estimate": 210, "prev_chunk_id": 408, "next_chunk_id": 410, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 410, "text": "```py\nfrom transformers import AutoModelForCausalLM, BitsAndBytesConfig\n\nmodel_id = \"bigscience/bloom-1b7\"\n\nquantization_config = BitsAndBytesConfig(\n llm_int8_threshold=0.0,\n llm_int8_enable_fp32_cpu_offload=True\n)\n\nmodel_8bit = AutoModelForCausalLM.from_pretrained(\n model_id,\n dtype=\"auto\",\n device_map=device_map,\n quantization_config=quantization_config,\n)\n```", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "Outlier threshold", "char_start": 9930, "char_end": 10313, "token_estimate": 95, "prev_chunk_id": 409, "next_chunk_id": 411, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 411, "text": "### Skip module conversion\n\nFor some models, like [Jukebox](model_doc/jukebox), you don't need to quantize every module to 8-bit because it can actually cause instability. With Jukebox, there are several `lm_head` modules that should be skipped using the `llm_int8_skip_modules` parameter in [BitsAndBytesConfig](/docs/transformers/v5.6.2/en/main_classes/quantization#transformers.BitsAndBytesConfig).\n\n```py\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig\n\nmodel_id = \"bigscience/bloom-1b7\"\n\nquantization_config = BitsAndBytesConfig(\n llm_int8_skip_modules=[\"lm_head\"],\n)\n\nmodel_8bit = AutoModelForCausalLM.from_pretrained(\n model_id,\n dtype=\"auto\",\n device_map=\"auto\",\n quantization_config=quantization_config,\n)\n```", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "Skip module conversion", "char_start": 10315, "char_end": 11081, "token_estimate": 191, "prev_chunk_id": 410, "next_chunk_id": 412, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 412, "text": "### Finetuning\n\nThe [PEFT](https://github.com/huggingface/peft) library supports fine-tuning large models like [flan-t5-large](https://huggingface.co/google/flan-t5-large) and [facebook/opt-6.7b](https://huggingface.co/facebook/opt-6.7b) with 8-bit quantization. You don't need to pass the `device_map` parameter for training because it automatically loads your model on a GPU. However, you can still customize the device map with the `device_map` parameter (`device_map=\"auto\"` should only be used for inference).", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "Finetuning", "char_start": 11083, "char_end": 11597, "token_estimate": 128, "prev_chunk_id": 411, "next_chunk_id": 413, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 413, "text": "## QLoRA\n\nThis section explores some of the specific features of 4-bit quantization, such as changing the compute data type, the Normal Float 4 (NF4) data type, and nested quantization.", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "QLoRA", "char_start": 11599, "char_end": 11784, "token_estimate": 46, "prev_chunk_id": 412, "next_chunk_id": 414, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 414, "text": "### Compute data type\n\nChange the data type from float32 (the default value) to bf16 in [BitsAndBytesConfig](/docs/transformers/v5.6.2/en/main_classes/quantization#transformers.BitsAndBytesConfig) to speedup computation.\n\n```py\nimport torch\nfrom transformers import BitsAndBytesConfig\n\nquantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16)\n```", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "Compute data type", "char_start": 11786, "char_end": 12174, "token_estimate": 97, "prev_chunk_id": 413, "next_chunk_id": 415, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 415, "text": "### Normal Float 4 (NF4)\n\nNF4 is a 4-bit data type from the [QLoRA](https://hf.co/papers/2305.14314) paper, adapted for weights initialized from a normal distribution. You should use NF4 for training 4-bit base models.\n\n```py\nfrom transformers import BitsAndBytesConfig\n\nnf4_config = BitsAndBytesConfig(\n load_in_4bit=True,\n bnb_4bit_quant_type=\"nf4\",\n)\n\nmodel_nf4 = AutoModelForCausalLM.from_pretrained(model_id, dtype=\"auto\", quantization_config=nf4_config)\n```\n\nFor inference, the `bnb_4bit_quant_type` does not have a huge impact on performance. However, to remain consistent with the model weights, you should use the `bnb_4bit_compute_dtype` and `dtype` values.", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "Normal Float 4 (NF4)", "char_start": 12176, "char_end": 12849, "token_estimate": 168, "prev_chunk_id": 414, "next_chunk_id": 416, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 416, "text": "### Nested quantization\n\nNested quantization can save additional memory at no additional performance cost. This feature performs a second quantization of the already quantized weights to save an additional 0.4 bits/parameter. For example, with nested quantization, you can finetune a [Llama-13b](https://huggingface.co/meta-llama/Llama-2-13b) model on a 16GB NVIDIA T4 GPU with a sequence length of 1024, a batch size of 1, and enable gradient accumulation with 4 steps.\n\n```py\nfrom transformers import BitsAndBytesConfig\n\ndouble_quant_config = BitsAndBytesConfig(\n load_in_4bit=True,\n bnb_4bit_use_double_quant=True,\n)\n\nmodel_double_quant = AutoModelForCausalLM.from_pretrained(\"meta-llama/Llama-2-13b-chat-hf\", dtype=\"auto\", quantization_config=double_quant_config)\n```", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "Nested quantization", "char_start": 12851, "char_end": 13628, "token_estimate": 194, "prev_chunk_id": 415, "next_chunk_id": 417, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 417, "text": "## Dequantizing bitsandbytes models\n\nOnce quantized, you can [dequantize()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel.dequantize) a model to the original precision but this may result in some quality loss. Make sure you have enough GPU memory to fit the dequantized model.\n\n```python\nfrom transformers import AutoModelForCausalLM, BitsAndBytesConfig, AutoTokenizer\n\nmodel = AutoModelForCausalLM.from_pretrained(\"facebook/opt-125m\", BitsAndBytesConfig(load_in_4bit=True))\nmodel.dequantize()\n```", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "Dequantizing bitsandbytes models", "char_start": 13630, "char_end": 14158, "token_estimate": 132, "prev_chunk_id": 416, "next_chunk_id": 418, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 418, "text": "## Resources\n\nLearn more about the details of 8-bit quantization in [A Gentle Introduction to 8-bit Matrix Multiplication for transformers at scale using Hugging Face Transformers, Accelerate and bitsandbytes](https://huggingface.co/blog/hf-bitsandbytes-integration).\n\nTry 4-bit quantization in this [notebook](https://colab.research.google.com/drive/1ge2F1QSK8Q7h0hn3YKuBCOAS0bK8E0wf) and learn more about its details in [Making LLMs even more accessible with bitsandbytes, 4-bit quantization and QLoRA](https://huggingface.co/blog/4bit-transformers-bitsandbytes).", "source_file": "transformers/quantization/bitsandbytes.md", "section_heading": "Resources", "char_start": 14160, "char_end": 14725, "token_estimate": 141, "prev_chunk_id": 417, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/quantization/bitsandbytes", "doc_title": "Bitsandbytes" }, { "chunk_id": 419, "text": "# GPTQ\n\nThe [GPT-QModel](https://github.com/ModelCloud/GPTQModel) project (Python package `gptqmodel`) implements the GPTQ algorithm, a post-training quantization technique where each row of the weight matrix is quantized independently to find a version of the weights that minimizes the error. These weights are quantized to int4, but they're restored to fp16 on the fly during inference. This can save memory usage by 4x because the int4 weights are dequantized in a fused kernel rather than a GPU's global memory. Inference is also faster because a lower bitwidth takes less time to communicate.\n\nAutoGPTQ is no longer supported in Transformers. Install GPT-QModel instead.\n\nInstall Accelerate, Transformers and Optimum first.\n\n```bash\npip install --upgrade accelerate optimum transformers\n```\n\nThen run the command below to install GPT-QModel.\n\n```bash\npip install gptqmodel --no-build-isolation\n```", "source_file": "transformers/quantization/gptq.md", "section_heading": "GPTQ", "char_start": 0, "char_end": 903, "token_estimate": 225, "prev_chunk_id": null, "next_chunk_id": 420, "url": "https://huggingface.co/docs/transformers/quantization/gptq", "doc_title": "GPTQ" }, { "chunk_id": 420, "text": "Create a [GPTQConfig](/docs/transformers/v5.6.2/en/main_classes/quantization#transformers.GPTQConfig) class and set the number of bits to quantize to, a dataset to calbrate the weights for quantization, and a tokenizer to prepare the dataset.\n\n```py\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, GPTQConfig\n\ntokenizer = AutoTokenizer.from_pretrained(\"facebook/opt-125m\")\ngptq_config = GPTQConfig(bits=4, dataset=\"c4\", tokenizer=tokenizer)\n```\n\nYou can pass your own dataset as a list of strings, but it is highly recommended to use the same dataset from the GPTQ paper.\n\n```py\ndataset = [\"gptqmodel is an easy-to-use model quantization library with user-friendly apis, based on the GPTQ algorithm.\"]\ngptq_config = GPTQConfig(bits=4, dataset=dataset, tokenizer=tokenizer)\n```", "source_file": "transformers/quantization/gptq.md", "section_heading": "GPTQ", "char_start": 905, "char_end": 1695, "token_estimate": 197, "prev_chunk_id": 419, "next_chunk_id": 421, "url": "https://huggingface.co/docs/transformers/quantization/gptq", "doc_title": "GPTQ" }, { "chunk_id": 421, "text": "Load a model to quantize and pass [GPTQConfig](/docs/transformers/v5.6.2/en/main_classes/quantization#transformers.GPTQConfig) to [from_pretrained()](/docs/transformers/v5.6.2/en/model_doc/auto#transformers.AutoModel.from_pretrained). Set `device_map=\"auto\"` to automatically offload the model to a CPU to help fit the model in memory, and allow the model modules to be moved between the CPU and GPU for quantization.\n\n```py\nquantized_model = AutoModelForCausalLM.from_pretrained(\"facebook/opt-125m\", device_map=\"auto\", quantization_config=gptq_config)\n```\n\nIf you're running out of memory because a dataset is too large (disk offloading is not supported), try passing the `max_memory` parameter to allocate the amount of memory to use on your device (GPU and CPU).\n\n```py\nquantized_model = AutoModelForCausalLM.from_pretrained(\n \"facebook/opt-125m\",\n device_map=\"auto\",\n max_memory={0: \"30GiB\", 1: \"46GiB\", \"cpu\": \"30GiB\"},\n quantization_config=gptq_config\n)\n```", "source_file": "transformers/quantization/gptq.md", "section_heading": "GPTQ", "char_start": 1697, "char_end": 2672, "token_estimate": 243, "prev_chunk_id": 420, "next_chunk_id": 422, "url": "https://huggingface.co/docs/transformers/quantization/gptq", "doc_title": "GPTQ" }, { "chunk_id": 422, "text": "> [!WARNING]\n> Depending on your hardware, it can take some time to quantize a model from scratch. It can take ~5 minutes to quantize the [facebook/opt-350m](https://huggingface.co/facebook/opt-350m) model on a free-tier Google Colab GPU, but it'll take ~4 hours to quantize a 175B parameter model on a NVIDIA A100. Before you quantize a model, it is a good idea to check the Hub if a GPTQ-quantized version of the model already exists.\n\nOnce a model is quantized, you can use [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.utils.PushToHubMixin.push_to_hub) to push the model and tokenizer to the Hub where it can be easily shared and accessed. This saves the [GPTQConfig](/docs/transformers/v5.6.2/en/main_classes/quantization#transformers.GPTQConfig).\n\n```py\nquantized_model.push_to_hub(\"opt-125m-gptq\")\ntokenizer.push_to_hub(\"opt-125m-gptq\")\n```", "source_file": "transformers/quantization/gptq.md", "section_heading": "GPTQ", "char_start": 2674, "char_end": 3552, "token_estimate": 219, "prev_chunk_id": 421, "next_chunk_id": 423, "url": "https://huggingface.co/docs/transformers/quantization/gptq", "doc_title": "GPTQ" }, { "chunk_id": 423, "text": "[save_pretrained()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel.save_pretrained) saves a quantized model locally. If the model was quantized with the `device_map` parameter, make sure to move the entire model to a GPU or CPU before saving it. The example below saves the model on a CPU.\n\n```py\nquantized_model.save_pretrained(\"opt-125m-gptq\")\ntokenizer.save_pretrained(\"opt-125m-gptq\")", "source_file": "transformers/quantization/gptq.md", "section_heading": "GPTQ", "char_start": 3554, "char_end": 3972, "token_estimate": 104, "prev_chunk_id": 422, "next_chunk_id": 424, "url": "https://huggingface.co/docs/transformers/quantization/gptq", "doc_title": "GPTQ" }, { "chunk_id": 424, "text": "# if quantized with device_map set\nquantized_model.to(\"cpu\")\nquantized_model.save_pretrained(\"opt-125m-gptq\")\n```\n\nReload a quantized model with [from_pretrained()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel.from_pretrained), and set `device_map=\"auto\"` to automatically distribute the model on all available GPUs to load the model faster without using more memory than needed.\n\n```py\nfrom transformers import AutoModelForCausalLM\n\nmodel = AutoModelForCausalLM.from_pretrained(\"{your_username}/opt-125m-gptq\", device_map=\"auto\")\n```", "source_file": "transformers/quantization/gptq.md", "section_heading": "if quantized with device_map set", "char_start": 3974, "char_end": 4540, "token_estimate": 141, "prev_chunk_id": 423, "next_chunk_id": 425, "url": "https://huggingface.co/docs/transformers/quantization/gptq", "doc_title": "GPTQ" }, { "chunk_id": 425, "text": "## Marlin\n\n[Marlin](https://github.com/IST-DASLab/marlin) is a 4-bit only CUDA GPTQ kernel, highly optimized for the NVIDIA A100 GPU (Ampere) architecture. Loading, dequantization, and execution of post-dequantized weights are highly parallelized, offering a substantial inference improvement versus the original CUDA GPTQ kernel. Marlin is only available for quantized inference and does not support model quantization.\n\nMarlin inference can be activated with the `backend` parameter in [GPTQConfig](/docs/transformers/v5.6.2/en/main_classes/quantization#transformers.GPTQConfig).\n\n```py\n\nfrom transformers import AutoModelForCausalLM, GPTQConfig\n\nmodel = AutoModelForCausalLM.from_pretrained(\"{your_username}/opt-125m-gptq\", device_map=\"auto\", quantization_config=GPTQConfig(bits=4, backend=\"marlin\"))\n```", "source_file": "transformers/quantization/gptq.md", "section_heading": "Marlin", "char_start": 4542, "char_end": 5349, "token_estimate": 201, "prev_chunk_id": 424, "next_chunk_id": 426, "url": "https://huggingface.co/docs/transformers/quantization/gptq", "doc_title": "GPTQ" }, { "chunk_id": 426, "text": "## GPT-QModel\n\nGPT-QModel is the actively maintained backend for GPTQ in Transformers. It was originally forked from AutoGPTQ, but has since diverged with significant improvements such as faster quantization, lower memory usage, and more accurate defaults.\n\nGPT-QModel provides asymmetric quantization which can potentially lower quantization errors compared to symmetric quantization. It is not backward compatible with legacy AutoGPTQ checkpoints, and not all kernels (Marlin) support asymmetric quantization.\n\nGPT-QModel also has broader support for the latest LLM models, multimodal models (Qwen2-VL and Ovis1.6-VL), platforms (Linux, macOS, Windows 11), and hardware (AMD ROCm, Apple Silicon, Intel/AMD CPUs, and Intel Datacenter Max/Arc GPUs, etc.).\n\nThe Marlin kernels are also updated for A100 GPUs and other kernels are updated to include auto-padding for legacy models and models with non-uniform in/out-features.", "source_file": "transformers/quantization/gptq.md", "section_heading": "GPT-QModel", "char_start": 5351, "char_end": 6274, "token_estimate": 230, "prev_chunk_id": 425, "next_chunk_id": 427, "url": "https://huggingface.co/docs/transformers/quantization/gptq", "doc_title": "GPTQ" }, { "chunk_id": 427, "text": "## Resources\n\nRun the GPTQ quantization with PEFT [notebook](https://colab.research.google.com/drive/1_TIrmuKOFhuRRiTWN94iLKUFu6ZX4ceb?usp=sharing) for a hands-on experience.", "source_file": "transformers/quantization/gptq.md", "section_heading": "Resources", "char_start": 6276, "char_end": 6450, "token_estimate": 43, "prev_chunk_id": 426, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/quantization/gptq", "doc_title": "GPTQ" }, { "chunk_id": 428, "text": "# Configuration\n\nThe base class [PreTrainedConfig](/docs/transformers/v5.6.2/en/main_classes/configuration#transformers.PreTrainedConfig) implements the common methods for loading/saving a configuration\neither from a local file or directory, or from a pretrained model configuration provided by the library (downloaded\nfrom HuggingFace's AWS S3 repository).\n\nEach derived config class implements model specific attributes. Common attributes present in all config classes are:\n`hidden_size`, `num_attention_heads`, and `num_hidden_layers`. Text models further implement:\n`vocab_size`.", "source_file": "transformers/main_classes/configuration.md", "section_heading": "Configuration", "char_start": 0, "char_end": 583, "token_estimate": 145, "prev_chunk_id": null, "next_chunk_id": 429, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 429, "text": "## PreTrainedConfig[[transformers.PreTrainedConfig]]", "source_file": "transformers/main_classes/configuration.md", "section_heading": "PreTrainedConfig[[transformers.PreTrainedConfig]]", "char_start": 585, "char_end": 637, "token_estimate": 13, "prev_chunk_id": 428, "next_chunk_id": 430, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 430, "text": "#### transformers.PreTrainedConfig[[transformers.PreTrainedConfig]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/configuration_utils.py#L121)\n\nBase class for all configuration classes. Handles a few parameters common to all models' configurations as well as\nmethods for loading/downloading/saving configurations.\n\nA configuration file can be loaded and saved to disk. Loading the configuration file and using this file to\ninitialize a model does **not** load the model weights. It only affects the model's configuration.\n\nClass attributes (overridden by derived classes):", "source_file": "transformers/main_classes/configuration.md", "section_heading": "transformers.PreTrainedConfig[[transformers.PreTrainedConfig]]", "char_start": 639, "char_end": 1248, "token_estimate": 152, "prev_chunk_id": 429, "next_chunk_id": 431, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 431, "text": "- **model_type** (`str`) -- An identifier for the model type, serialized into the JSON file, and used to recreate\n the correct object in [AutoConfig](/docs/transformers/v5.6.2/en/model_doc/auto#transformers.AutoConfig).\n- **has_no_defaults_at_init** (`bool`) -- Whether the config class can be initialized without providing input arguments.\n Some configurations requires inputs to be defined at init and have no default values, usually these are composite configs,\n (but not necessarily) such as [EncoderDecoderConfig](/docs/transformers/v5.6.2/en/model_doc/encoder-decoder#transformers.EncoderDecoderConfig) or [~RagConfig](/docs/transformers/v5.6.2/en/model_doc/rag#transformers.RagConfig). They have to be initialized from\n two or more configs of type [PreTrainedConfig](/docs/transformers/v5.6.2/en/main_classes/configuration#transformers.PreTrainedConfig).\n- **keys_to_ignore_at_inference** (`list[str]`) -- A list of keys to ignore by default when looking at dictionary\n outputs of the model during inference.\n- **attribute_map** (`dict[str, str]`) -- A dict that maps model specific attribute names to the standardized\n naming of attributes.\n- **base_model_tp_plan** (`dict[str, Any]`) -- A dict that maps sub-modules FQNs of a base model to a tensor\n parallel plan applied to the sub-module when `model.tensor_parallel` is called.\n- **base_model_pp_plan** (`dict[str, tuple[list[str]]]`) -- A dict that maps child-modules of a base model to a\n pipeline parallel plan that enables users to place the child-module on the appropriate device.", "source_file": "transformers/main_classes/configuration.md", "section_heading": "transformers.PreTrainedConfig[[transformers.PreTrainedConfig]]", "char_start": 1250, "char_end": 2804, "token_estimate": 388, "prev_chunk_id": 430, "next_chunk_id": 432, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 432, "text": "Common attributes (present in all subclasses):\n\n- **vocab_size** (`int`) -- The number of tokens in the vocabulary, which is also the first dimension of the\n embeddings matrix (this attribute may be missing for models that don't have a text modality like ViT).\n- **hidden_size** (`int`) -- The hidden size of the model.\n- **num_attention_heads** (`int`) -- The number of attention heads used in the multi-head attention layers of the\n model.\n- **num_hidden_layers** (`int`) -- The number of blocks in the model.\n\nSetting parameters for sequence generation in the model config is deprecated. For backward compatibility, loading\nsome of them will still be possible, but attempting to overwrite them will throw an exception -- you should set\nthem in a [~transformers.GenerationConfig]. Check the documentation of [~transformers.GenerationConfig] for more\ninformation about the individual parameters.", "source_file": "transformers/main_classes/configuration.md", "section_heading": "transformers.PreTrainedConfig[[transformers.PreTrainedConfig]]", "char_start": 2806, "char_end": 3704, "token_estimate": 224, "prev_chunk_id": 431, "next_chunk_id": 433, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 433, "text": "push_to_hubtransformers.PreTrainedConfig.push_to_hubhttps://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/utils/hub.py#L720[{\"name\": \"repo_id\", \"val\": \": str\"}, {\"name\": \"commit_message\", \"val\": \": str | None = None\"}, {\"name\": \"commit_description\", \"val\": \": str | None = None\"}, {\"name\": \"private\", \"val\": \": bool | None = None\"}, {\"name\": \"token\", \"val\": \": bool | str | None = None\"}, {\"name\": \"revision\", \"val\": \": str | None = None\"}, {\"name\": \"create_pr\", \"val\": \": bool = False\"}, {\"name\": \"max_shard_size\", \"val\": \": int | str | None = '50GB'\"}, {\"name\": \"tags\", \"val\": \": list[str] | None = None\"}]- **repo_id** (`str`) --\n The name of the repository you want to push your config to. It should contain your organization name\n when pushing to a given organization.\n- **commit_message** (`str`, *optional*) --\n Message to commit while pushing. Will default to `\"Upload config\"`.\n- **commit_description** (`str`, *optional*) --\n The description of the commit that will be created\n- **private** (`bool`, *optional*) --\n Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.\n- **token** (`bool` or `str`, *optional*) --\n The token to use as HTTP bearer authorization for remote files. If `True` (default), will use the token generated\n when running `hf auth login` (stored in `~/.huggingface`).\n- **revision** (`str`, *optional*) --\n Branch to push the uploaded files to.\n- **create_pr** (`bool`, *optional*, defaults to `False`) --\n Whether or not to create a PR with the uploaded files or directly commit.\n- **max_shard_size** (`int` or `str`, *optional*, defaults to `\"50GB\"`) --\n Only applicable for models. The maximum size for a checkpoint before being sharded. Checkpoints shard\n will then be each of size lower than this size. If expressed as a string, needs to be digits followed\n by a unit (like `\"5MB\"`).\n- **tags** (`list[str]`, *optional*) --\n List of tags to push on the Hub.0", "source_file": "transformers/main_classes/configuration.md", "section_heading": "transformers.PreTrainedConfig[[transformers.PreTrainedConfig]]", "char_start": 3706, "char_end": 5754, "token_estimate": 512, "prev_chunk_id": 432, "next_chunk_id": 434, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 434, "text": "Upload the configuration file to the \ud83e\udd17 Model Hub.\n\nExamples:\n\n```python\nfrom transformers import AutoConfig\n\nconfig = AutoConfig.from_pretrained(\"google-bert/bert-base-cased\")", "source_file": "transformers/main_classes/configuration.md", "section_heading": "transformers.PreTrainedConfig[[transformers.PreTrainedConfig]]", "char_start": 5756, "char_end": 5931, "token_estimate": 43, "prev_chunk_id": 433, "next_chunk_id": 435, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 435, "text": "# Push the config to your namespace with the name \"my-finetuned-bert\".\nconfig.push_to_hub(\"my-finetuned-bert\")", "source_file": "transformers/main_classes/configuration.md", "section_heading": "Push the config to your namespace with the name \"my-finetuned-bert\".", "char_start": 5933, "char_end": 6043, "token_estimate": 27, "prev_chunk_id": 434, "next_chunk_id": 436, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 436, "text": "# Push the config to an organization with the name \"my-finetuned-bert\".\nconfig.push_to_hub(\"huggingface/my-finetuned-bert\")\n```\n\n**Parameters:**\n\nname_or_path (`str`, *optional*, defaults to `\"\"`) : Store the string that was passed to [PreTrainedModel.from_pretrained()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) as `pretrained_model_name_or_path` if the configuration was created with such a method.\n\noutput_hidden_states (`bool`, *optional*, defaults to `False`) : Whether or not the model should return all hidden-states.\n\noutput_attentions (`bool`, *optional*, defaults to `False`) : Whether or not the model should returns all attentions.\n\nreturn_dict (`bool`, *optional*, defaults to `True`) : Whether or not the model should return a [ModelOutput](/docs/transformers/v5.6.2/en/main_classes/output#transformers.utils.ModelOutput) instead of a plain tuple.", "source_file": "transformers/main_classes/configuration.md", "section_heading": "Push the config to an organization with the name \"my-finetuned-bert\".", "char_start": 6045, "char_end": 6958, "token_estimate": 228, "prev_chunk_id": 435, "next_chunk_id": 437, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 437, "text": "is_encoder_decoder (`bool`, *optional*, defaults to `False`) : Whether the model is used as an encoder/decoder or not.\n\nchunk_size_feed_forward (`int`, *optional*, defaults to `0`) : The chunk size of all feed forward layers in the residual attention blocks. A chunk size of `0` means that the feed forward layer is not chunked. A chunk size of n means that the feed forward layer processes `n` \"`.\n\nreturn_unused_kwargs (`bool`, *optional*, defaults to `False`) : If `False`, then this function returns just the final configuration object. If `True`, then this functions returns a `Tuple(config, unused_kwargs)` where *unused_kwargs* is a dictionary consisting of the key/value pairs whose keys are not configuration attributes: i.e., the part of `kwargs` which has not been used to update `config` and is otherwise ignored.\n\nsubfolder (`str`, *optional*, defaults to `\"\"`) : In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can specify the folder name here.", "source_file": "transformers/main_classes/configuration.md", "section_heading": "Push the config to an organization with the name \"my-finetuned-bert\".", "char_start": 0, "char_end": 1010, "token_estimate": 252, "prev_chunk_id": 436, "next_chunk_id": 438, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 438, "text": "kwargs (`dict[str, Any]`, *optional*) : The values in kwargs of any keys which are configuration attributes will be used to override the loaded values. Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled by the `return_unused_kwargs` keyword parameter.\n\n**Returns:**\n\n`[PreTrainedConfig](/docs/transformers/v5.6.2/en/main_classes/configuration#transformers.PreTrainedConfig)`\n\nThe configuration object instantiated from this pretrained model.", "source_file": "transformers/main_classes/configuration.md", "section_heading": "Push the config to an organization with the name \"my-finetuned-bert\".", "char_start": 7975, "char_end": 8461, "token_estimate": 121, "prev_chunk_id": 437, "next_chunk_id": 439, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 439, "text": "#### get_config_dict[[transformers.PreTrainedConfig.get_config_dict]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/configuration_utils.py#L655)\n\nFrom a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a\n[PreTrainedConfig](/docs/transformers/v5.6.2/en/main_classes/configuration#transformers.PreTrainedConfig) using `from_dict`.\n\n**Parameters:**\n\npretrained_model_name_or_path (`str` or `os.PathLike`) : The identifier of the pre-trained checkpoint from which we want the dictionary of parameters.\n\n**Returns:**\n\n``tuple[Dict, Dict]``\n\nThe dictionary(ies) that will be used to instantiate the configuration object.", "source_file": "transformers/main_classes/configuration.md", "section_heading": "get_config_dict[[transformers.PreTrainedConfig.get_config_dict]]", "char_start": 8462, "char_end": 9165, "token_estimate": 175, "prev_chunk_id": 438, "next_chunk_id": 440, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 440, "text": "#### get_text_config[[transformers.PreTrainedConfig.get_text_config]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/configuration_utils.py#L1205)\n\nReturns the text config related to the text input (encoder) or text output (decoder) of the model. The\n`decoder` and `encoder` input arguments can be used to specify which end of the model we are interested in,\nwhich is useful on models that have both text input and output modalities.\n\nThere are three possible outcomes of using this method:\n1. On most models, it returns the original config instance itself.\n2. On newer (2024+) composite models, it returns the text section of the config, which is nested under a set\n of valid names.\n3. On older (2023-) composite models, it discards decoder-only parameters when `encoder=True` and vice-versa.\n\n**Parameters:**\n\ndecoder (`Optional[bool]`, *optional*) : If set to `True`, then only search for decoder config names.", "source_file": "transformers/main_classes/configuration.md", "section_heading": "get_text_config[[transformers.PreTrainedConfig.get_text_config]]", "char_start": 9166, "char_end": 10117, "token_estimate": 237, "prev_chunk_id": 439, "next_chunk_id": 441, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 441, "text": "encoder (`Optional[bool]`, *optional*) : If set to `True`, then only search for encoder config names.", "source_file": "transformers/main_classes/configuration.md", "section_heading": "get_text_config[[transformers.PreTrainedConfig.get_text_config]]", "char_start": 10119, "char_end": 10220, "token_estimate": 25, "prev_chunk_id": 440, "next_chunk_id": 442, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 442, "text": "#### register_for_auto_class[[transformers.PreTrainedConfig.register_for_auto_class]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/configuration_utils.py#L1167)\n\nRegister this class with a given auto class. This should only be used for custom configurations as the ones in\nthe library are already mapped with `AutoConfig`.\n\n**Parameters:**\n\nauto_class (`str` or `type`, *optional*, defaults to `\"AutoConfig\"`) : The auto class to register this new configuration with.", "source_file": "transformers/main_classes/configuration.md", "section_heading": "register_for_auto_class[[transformers.PreTrainedConfig.register_for_auto_class]]", "char_start": 10221, "char_end": 10726, "token_estimate": 126, "prev_chunk_id": 441, "next_chunk_id": 443, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 443, "text": "#### save_pretrained[[transformers.PreTrainedConfig.save_pretrained]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/configuration_utils.py#L482)\n\nSave a configuration object to the directory `save_directory`, so that it can be re-loaded using the\n[from_pretrained()](/docs/transformers/v5.6.2/en/main_classes/configuration#transformers.PreTrainedConfig.from_pretrained) class method.\n\n**Parameters:**\n\nsave_directory (`str` or `os.PathLike`) : Directory where the configuration JSON file will be saved (will be created if it does not exist).\n\npush_to_hub (`bool`, *optional*, defaults to `False`) : Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the repository you want to push to with `repo_id` (will default to the name of `save_directory` in your namespace).", "source_file": "transformers/main_classes/configuration.md", "section_heading": "save_pretrained[[transformers.PreTrainedConfig.save_pretrained]]", "char_start": 10727, "char_end": 11575, "token_estimate": 212, "prev_chunk_id": 442, "next_chunk_id": 444, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 444, "text": "kwargs (`dict[str, Any]`, *optional*) : Additional key word arguments passed along to the [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.utils.PushToHubMixin.push_to_hub) method.", "source_file": "transformers/main_classes/configuration.md", "section_heading": "save_pretrained[[transformers.PreTrainedConfig.save_pretrained]]", "char_start": 11577, "char_end": 11785, "token_estimate": 52, "prev_chunk_id": 443, "next_chunk_id": 445, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 445, "text": "#### to_dict[[transformers.PreTrainedConfig.to_dict]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/configuration_utils.py#L994)\n\nSerializes this instance to a Python dictionary.\n\n**Returns:**\n\n``dict[str, Any]``\n\nDictionary of all the attributes that make up this configuration instance.", "source_file": "transformers/main_classes/configuration.md", "section_heading": "to_dict[[transformers.PreTrainedConfig.to_dict]]", "char_start": 11786, "char_end": 12111, "token_estimate": 81, "prev_chunk_id": 444, "next_chunk_id": 446, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 446, "text": "#### to_diff_dict[[transformers.PreTrainedConfig.to_diff_dict]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/configuration_utils.py#L935)\n\nRemoves all attributes from the configuration that correspond to the default config attributes for\nbetter readability, while always retaining the `config` attribute from the class. Serializes to a\nPython dictionary.\n\n**Returns:**\n\n`dict[str, Any]`\n\nDictionary of all the attributes that make up this configuration instance.", "source_file": "transformers/main_classes/configuration.md", "section_heading": "to_diff_dict[[transformers.PreTrainedConfig.to_diff_dict]]", "char_start": 12112, "char_end": 12612, "token_estimate": 125, "prev_chunk_id": 445, "next_chunk_id": 447, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 447, "text": "#### to_json_file[[transformers.PreTrainedConfig.to_json_file]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/configuration_utils.py#L1063)\n\nSave this instance to a JSON file.\n\n**Parameters:**\n\njson_file_path (`str` or `os.PathLike`) : Path to the JSON file in which this configuration instance's parameters will be saved.\n\nuse_diff (`bool`, *optional*, defaults to `True`) : If set to `True`, only the difference between the config instance and the default `PreTrainedConfig()` is serialized to JSON file.", "source_file": "transformers/main_classes/configuration.md", "section_heading": "to_json_file[[transformers.PreTrainedConfig.to_json_file]]", "char_start": 12613, "char_end": 13156, "token_estimate": 135, "prev_chunk_id": 446, "next_chunk_id": 448, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 448, "text": "#### to_json_string[[transformers.PreTrainedConfig.to_json_string]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/configuration_utils.py#L1041)\n\nSerializes this instance to a JSON string.\n\n**Parameters:**\n\nuse_diff (`bool`, *optional*, defaults to `True`) : If set to `True`, only the difference between the config instance and the default `PreTrainedConfig()` is serialized to JSON string.\n\n**Returns:**\n\n``str``\n\nString containing all the attributes that make up this configuration instance in JSON format.", "source_file": "transformers/main_classes/configuration.md", "section_heading": "to_json_string[[transformers.PreTrainedConfig.to_json_string]]", "char_start": 13157, "char_end": 13702, "token_estimate": 136, "prev_chunk_id": 447, "next_chunk_id": 449, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 449, "text": "#### update[[transformers.PreTrainedConfig.update]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/configuration_utils.py#L1077)\n\nUpdates attributes of this class with attributes from `config_dict`.\n\n**Parameters:**\n\nconfig_dict (`dict[str, Any]`) : Dictionary of attributes that should be updated for this class.", "source_file": "transformers/main_classes/configuration.md", "section_heading": "update[[transformers.PreTrainedConfig.update]]", "char_start": 13703, "char_end": 14052, "token_estimate": 87, "prev_chunk_id": 448, "next_chunk_id": 450, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 450, "text": "#### update_from_string[[transformers.PreTrainedConfig.update_from_string]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/configuration_utils.py#L1087)\n\nUpdates attributes of this class with attributes from `update_str`.\n\nThe expected format is ints, floats and strings as is, and for booleans use `true` or `false`. For example:\n\"n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index\"\n\nThe keys to change have to already exist in the config object.\n\n**Parameters:**\n\nupdate_str (`str`) : String with attributes that should be updated for this class.", "source_file": "transformers/main_classes/configuration.md", "section_heading": "update_from_string[[transformers.PreTrainedConfig.update_from_string]]", "char_start": 14053, "char_end": 14660, "token_estimate": 151, "prev_chunk_id": 449, "next_chunk_id": 451, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 451, "text": "#### validate[[transformers.PreTrainedConfig.validate]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/huggingface_hub/dataclasses.py#L247)\n\nRun class validators on the instance.", "source_file": "transformers/main_classes/configuration.md", "section_heading": "validate[[transformers.PreTrainedConfig.validate]]", "char_start": 14661, "char_end": 14862, "token_estimate": 50, "prev_chunk_id": 450, "next_chunk_id": 452, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 452, "text": "#### validate_architecture[[transformers.PreTrainedConfig.validate_architecture]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/configuration_utils.py#L434)\n\nPart of `@strict`-powered validation. Validates the architecture of the config.", "source_file": "transformers/main_classes/configuration.md", "section_heading": "validate_architecture[[transformers.PreTrainedConfig.validate_architecture]]", "char_start": 14863, "char_end": 15137, "token_estimate": 68, "prev_chunk_id": 451, "next_chunk_id": 453, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 453, "text": "#### validate_layer_type[[transformers.PreTrainedConfig.validate_layer_type]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/configuration_utils.py#L462)\n\nCheck that `layer_types` is correctly defined.", "source_file": "transformers/main_classes/configuration.md", "section_heading": "validate_layer_type[[transformers.PreTrainedConfig.validate_layer_type]]", "char_start": 15138, "char_end": 15375, "token_estimate": 59, "prev_chunk_id": 452, "next_chunk_id": 454, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 454, "text": "#### validate_token_ids[[transformers.PreTrainedConfig.validate_token_ids]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/configuration_utils.py#L447)\n\nPart of `@strict`-powered validation. Validates the contents of the special tokens.", "source_file": "transformers/main_classes/configuration.md", "section_heading": "validate_token_ids[[transformers.PreTrainedConfig.validate_token_ids]]", "char_start": 15376, "char_end": 15648, "token_estimate": 68, "prev_chunk_id": 453, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/main_classes/configuration", "doc_title": "Configuration" }, { "chunk_id": 455, "text": "# Models\n\nThe base class [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel) implements the common methods for loading/saving a model either from a local\nfile or directory, or from a pretrained model configuration provided by the library (downloaded from HuggingFace's Hub).\n\n[PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel) also implements a few methods which are common among all the models to:\n\n- resize the input token embeddings when new tokens are added to the vocabulary\n\nThe other methods that are common to each model are defined in [ModuleUtilsMixin](/docs/transformers/v5.6.2/en/main_classes/model#transformers.modeling_utils.ModuleUtilsMixin) and [GenerationMixin](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationMixin).", "source_file": "transformers/main_classes/model.md", "section_heading": "Models", "char_start": 0, "char_end": 856, "token_estimate": 214, "prev_chunk_id": null, "next_chunk_id": 456, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 456, "text": "## PreTrainedModel[[transformers.PreTrainedModel]]", "source_file": "transformers/main_classes/model.md", "section_heading": "PreTrainedModel[[transformers.PreTrainedModel]]", "char_start": 858, "char_end": 908, "token_estimate": 12, "prev_chunk_id": 455, "next_chunk_id": 457, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 457, "text": "#### transformers.PreTrainedModel[[transformers.PreTrainedModel]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L1128)\n\nBase class for all models.\n\n[PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel) takes care of storing the configuration of the models and handles methods for loading,\ndownloading and saving models as well as a few methods common to all models to:\n\n- resize the input embeddings\n\nClass attributes (overridden by derived classes):", "source_file": "transformers/main_classes/model.md", "section_heading": "transformers.PreTrainedModel[[transformers.PreTrainedModel]]", "char_start": 910, "char_end": 1457, "token_estimate": 136, "prev_chunk_id": 456, "next_chunk_id": 458, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 458, "text": "- **config_class** ([PreTrainedConfig](/docs/transformers/v5.6.2/en/main_classes/configuration#transformers.PreTrainedConfig)) -- A subclass of [PreTrainedConfig](/docs/transformers/v5.6.2/en/main_classes/configuration#transformers.PreTrainedConfig) to use as configuration class\n for this model architecture.\n- **base_model_prefix** (`str`) -- A string indicating the attribute associated to the base model in derived\n classes of the same architecture adding modules on top of the base model.\n- **main_input_name** (`str`) -- The name of the principal input to the model (often `input_ids` for NLP\n models, `pixel_values` for vision models and `input_values` for speech models).\n- **can_record_outputs** (dict):", "source_file": "transformers/main_classes/model.md", "section_heading": "transformers.PreTrainedModel[[transformers.PreTrainedModel]]", "char_start": 1459, "char_end": 2174, "token_estimate": 178, "prev_chunk_id": 457, "next_chunk_id": 459, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 459, "text": "push_to_hubtransformers.PreTrainedModel.push_to_hubhttps://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/utils/hub.py#L720[{\"name\": \"repo_id\", \"val\": \": str\"}, {\"name\": \"commit_message\", \"val\": \": str | None = None\"}, {\"name\": \"commit_description\", \"val\": \": str | None = None\"}, {\"name\": \"private\", \"val\": \": bool | None = None\"}, {\"name\": \"token\", \"val\": \": bool | str | None = None\"}, {\"name\": \"revision\", \"val\": \": str | None = None\"}, {\"name\": \"create_pr\", \"val\": \": bool = False\"}, {\"name\": \"max_shard_size\", \"val\": \": int | str | None = '50GB'\"}, {\"name\": \"tags\", \"val\": \": list[str] | None = None\"}]- **repo_id** (`str`) --\n The name of the repository you want to push your model to. It should contain your organization name\n when pushing to a given organization.\n- **commit_message** (`str`, *optional*) --\n Message to commit while pushing. Will default to `\"Upload model\"`.\n- **commit_description** (`str`, *optional*) --\n The description of the commit that will be created\n- **private** (`bool`, *optional*) --\n Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.\n- **token** (`bool` or `str`, *optional*) --\n The token to use as HTTP bearer authorization for remote files. If `True` (default), will use the token generated\n when running `hf auth login` (stored in `~/.huggingface`).\n- **revision** (`str`, *optional*) --\n Branch to push the uploaded files to.\n- **create_pr** (`bool`, *optional*, defaults to `False`) --\n Whether or not to create a PR with the uploaded files or directly commit.\n- **max_shard_size** (`int` or `str`, *optional*, defaults to `\"50GB\"`) --\n Only applicable for models. The maximum size for a checkpoint before being sharded. Checkpoints shard\n will then be each of size lower than this size. If expressed as a string, needs to be digits followed\n by a unit (like `\"5MB\"`).\n- **tags** (`list[str]`, *optional*) --\n List of tags to push on the Hub.0", "source_file": "transformers/main_classes/model.md", "section_heading": "transformers.PreTrainedModel[[transformers.PreTrainedModel]]", "char_start": 2176, "char_end": 4221, "token_estimate": 511, "prev_chunk_id": 458, "next_chunk_id": 460, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 460, "text": "Upload the model file to the \ud83e\udd17 Model Hub.\n\nExamples:\n\n```python\nfrom transformers import AutoModel\n\nmodel = AutoModel.from_pretrained(\"google-bert/bert-base-cased\")", "source_file": "transformers/main_classes/model.md", "section_heading": "transformers.PreTrainedModel[[transformers.PreTrainedModel]]", "char_start": 4223, "char_end": 4387, "token_estimate": 41, "prev_chunk_id": 459, "next_chunk_id": 461, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 461, "text": "# Push the model to your namespace with the name \"my-finetuned-bert\".\nmodel.push_to_hub(\"my-finetuned-bert\")", "source_file": "transformers/main_classes/model.md", "section_heading": "Push the model to your namespace with the name \"my-finetuned-bert\".", "char_start": 4389, "char_end": 4497, "token_estimate": 27, "prev_chunk_id": 460, "next_chunk_id": 462, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 462, "text": "# Push the model to an organization with the name \"my-finetuned-bert\".\nmodel.push_to_hub(\"huggingface/my-finetuned-bert\")\n```\n\n**Parameters:**\n\nrepo_id (`str`) : The name of the repository you want to push your model to. It should contain your organization name when pushing to a given organization.\n\ncommit_message (`str`, *optional*) : Message to commit while pushing. Will default to `\"Upload model\"`.\n\ncommit_description (`str`, *optional*) : The description of the commit that will be created\n\nprivate (`bool`, *optional*) : Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.\n\ntoken (`bool` or `str`, *optional*) : The token to use as HTTP bearer authorization for remote files. If `True` (default), will use the token generated when running `hf auth login` (stored in `~/.huggingface`).\n\nrevision (`str`, *optional*) : Branch to push the uploaded files to.", "source_file": "transformers/main_classes/model.md", "section_heading": "Push the model to an organization with the name \"my-finetuned-bert\".", "char_start": 4499, "char_end": 5485, "token_estimate": 246, "prev_chunk_id": 461, "next_chunk_id": 463, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 463, "text": "create_pr (`bool`, *optional*, defaults to `False`) : Whether or not to create a PR with the uploaded files or directly commit.\n\nmax_shard_size (`int` or `str`, *optional*, defaults to `\"50GB\"`) : Only applicable for models. The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size lower than this size. If expressed as a string, needs to be digits followed by a unit (like `\"5MB\"`).\n\ntags (`list[str]`, *optional*) : List of tags to push on the Hub.", "source_file": "transformers/main_classes/model.md", "section_heading": "Push the model to an organization with the name \"my-finetuned-bert\".", "char_start": 5487, "char_end": 5980, "token_estimate": 123, "prev_chunk_id": 462, "next_chunk_id": 464, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 464, "text": "#### add_model_tags[[transformers.PreTrainedModel.add_model_tags]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L1452)\n\nAdd custom tags into the model that gets pushed to the Hugging Face Hub. Will\nnot overwrite existing tags in the model.\n\nExamples:\n\n```python\nfrom transformers import AutoModel\n\nmodel = AutoModel.from_pretrained(\"google-bert/bert-base-cased\")\n\nmodel.add_model_tags([\"custom\", \"custom-bert\"])", "source_file": "transformers/main_classes/model.md", "section_heading": "add_model_tags[[transformers.PreTrainedModel.add_model_tags]]", "char_start": 5981, "char_end": 6448, "token_estimate": 116, "prev_chunk_id": 463, "next_chunk_id": 465, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 465, "text": "# Push the model to your namespace with the name \"my-custom-bert\".\nmodel.push_to_hub(\"my-custom-bert\")\n```\n\n**Parameters:**\n\ntags (`Union[list[str], str]`) : The desired tags to inject in the model", "source_file": "transformers/main_classes/model.md", "section_heading": "Push the model to your namespace with the name \"my-custom-bert\".", "char_start": 6450, "char_end": 6647, "token_estimate": 49, "prev_chunk_id": 464, "next_chunk_id": 466, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 466, "text": "#### can_generate[[transformers.PreTrainedModel.can_generate]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L1563)\n\nReturns whether this model can generate sequences with `.generate()` from the `GenerationMixin`.\n\nUnder the hood, on classes where this function returns True, some generation-specific changes are triggered:\nfor instance, the model instance will have a populated `generation_config` attribute.\n\n**Returns:**\n\n``bool``\n\nWhether this model can generate sequences with `.generate()`.", "source_file": "transformers/main_classes/model.md", "section_heading": "can_generate[[transformers.PreTrainedModel.can_generate]]", "char_start": 6648, "char_end": 7199, "token_estimate": 137, "prev_chunk_id": 465, "next_chunk_id": 467, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 467, "text": "#### dequantize[[transformers.PreTrainedModel.dequantize]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L1434)\n\nPotentially dequantize the model in case it has been quantized by a quantization method that support\ndequantization.", "source_file": "transformers/main_classes/model.md", "section_heading": "dequantize[[transformers.PreTrainedModel.dequantize]]", "char_start": 7200, "char_end": 7484, "token_estimate": 71, "prev_chunk_id": 466, "next_chunk_id": 468, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 468, "text": "#### disable_input_require_grads[[transformers.PreTrainedModel.disable_input_require_grads]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L2215)\n\nRemoves the `_require_grads_hook`.", "source_file": "transformers/main_classes/model.md", "section_heading": "disable_input_require_grads[[transformers.PreTrainedModel.disable_input_require_grads]]", "char_start": 7485, "char_end": 7721, "token_estimate": 59, "prev_chunk_id": 467, "next_chunk_id": 469, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 469, "text": "#### enable_input_require_grads[[transformers.PreTrainedModel.enable_input_require_grads]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L2171)\n\nEnables the gradients for the input embeddings. This is useful for fine-tuning adapter weights while keeping\nthe model weights fixed.", "source_file": "transformers/main_classes/model.md", "section_heading": "enable_input_require_grads[[transformers.PreTrainedModel.enable_input_require_grads]]", "char_start": 7722, "char_end": 8055, "token_estimate": 83, "prev_chunk_id": 468, "next_chunk_id": 470, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 470, "text": "#### from_pretrained[[transformers.PreTrainedModel.from_pretrained]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L3729)\n\nInstantiate a pretrained pytorch model from a pre-trained model configuration.\n\nThe model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated). To train\nthe model, you should first set it back in training mode with `model.train()`.\n\nThe warning *Weights from XXX not initialized from pretrained model* means that the weights of XXX do not come\npretrained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning\ntask.\n\nThe warning *Weights from XXX not used in YYY* means that the layer XXX is not used by YYY, therefore those\nweights are discarded.\n\nActivate the special [\"offline-mode\"](https://huggingface.co/transformers/installation.html#offline-mode) to\nuse this method in a firewalled environment.\n\nExamples:", "source_file": "transformers/main_classes/model.md", "section_heading": "from_pretrained[[transformers.PreTrainedModel.from_pretrained]]", "char_start": 8056, "char_end": 9028, "token_estimate": 243, "prev_chunk_id": 469, "next_chunk_id": 471, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 471, "text": "```python\n>>> from transformers import BertConfig, BertModel\n\n>>> # Download model and configuration from huggingface.co and cache.\n>>> model = BertModel.from_pretrained(\"google-bert/bert-base-uncased\")\n>>> # Model was saved using *save_pretrained('./test/saved_model/')* (for example purposes, not runnable).\n>>> model = BertModel.from_pretrained(\"./test/saved_model/\")\n>>> # Update configuration during loading.\n>>> model = BertModel.from_pretrained(\"google-bert/bert-base-uncased\", output_attentions=True)\n>>> assert model.config.output_attentions == True\n```\n\n**Parameters:**", "source_file": "transformers/main_classes/model.md", "section_heading": "from_pretrained[[transformers.PreTrainedModel.from_pretrained]]", "char_start": 9030, "char_end": 9609, "token_estimate": 144, "prev_chunk_id": 470, "next_chunk_id": 472, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 472, "text": "pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*) : Can be either: - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co. - A path to a *directory* containing model weights saved using [save_pretrained()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel.save_pretrained), e.g., `./my_model_directory/`. - `None` if you are both providing the configuration and state dictionary (resp. with keyword arguments `config` and `state_dict`).\n\nmodel_args (sequence of positional arguments, *optional*) : All remaining positional arguments will be passed to the underlying model's `__init__` method.", "source_file": "transformers/main_classes/model.md", "section_heading": "from_pretrained[[transformers.PreTrainedModel.from_pretrained]]", "char_start": 9611, "char_end": 10287, "token_estimate": 169, "prev_chunk_id": 471, "next_chunk_id": 473, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 473, "text": "config (`Union[PreTrainedConfig, str, os.PathLike]`, *optional*) : Can be either: - an instance of a class derived from [PreTrainedConfig](/docs/transformers/v5.6.2/en/main_classes/configuration#transformers.PreTrainedConfig), - a string or path valid as input to [from_pretrained()](/docs/transformers/v5.6.2/en/main_classes/configuration#transformers.PreTrainedConfig.from_pretrained). Configuration for the model to use instead of an automatically loaded configuration. Configuration can be automatically loaded when: - The model is a model provided by the library (loaded with the *model id* string of a pretrained model). - The model was saved using [save_pretrained()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel.save_pretrained) and is reloaded by supplying the save directory. - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a configuration JSON file named *config.json* is found in the directory.", "source_file": "transformers/main_classes/model.md", "section_heading": "from_pretrained[[transformers.PreTrainedModel.from_pretrained]]", "char_start": 10289, "char_end": 11274, "token_estimate": 246, "prev_chunk_id": 472, "next_chunk_id": 474, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 474, "text": "state_dict (`dict[str, torch.Tensor]`, *optional*) : A state dictionary to use instead of a state dictionary loaded from saved weights file. This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using [save_pretrained()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel.save_pretrained) and [from_pretrained()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) is not a simpler option.\n\ncache_dir (`Union[str, os.PathLike]`, *optional*) : Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used.", "source_file": "transformers/main_classes/model.md", "section_heading": "from_pretrained[[transformers.PreTrainedModel.from_pretrained]]", "char_start": 11276, "char_end": 12019, "token_estimate": 185, "prev_chunk_id": 473, "next_chunk_id": 475, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 475, "text": "ignore_mismatched_sizes (`bool`, *optional*, defaults to `False`) : Whether or not to raise an error if some of the weights from the checkpoint do not have the same size as the weights of the model (if for instance, you are instantiating a model with 10 labels from a checkpoint with 3 labels).\n\nforce_download (`bool`, *optional*, defaults to `False`) : Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist.\n\nproxies (`dict[str, str]`, *optional*) : A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.\n\noutput_loading_info(`bool`, *optional*, defaults to `False`) : Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.\n\nlocal_files_only(`bool`, *optional*, defaults to `False`) : Whether or not to only look at local files (i.e., do not try to download the model).", "source_file": "transformers/main_classes/model.md", "section_heading": "from_pretrained[[transformers.PreTrainedModel.from_pretrained]]", "char_start": 12021, "char_end": 13034, "token_estimate": 253, "prev_chunk_id": 474, "next_chunk_id": 476, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 476, "text": "token (`str` or `bool`, *optional*) : The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use the token generated when running `hf auth login` (stored in `~/.huggingface`).\n\nrevision (`str`, *optional*, defaults to `\"main\"`) : The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git. To test a pull request you made on the Hub, you can pass `revision=\"refs/pr/\"`.", "source_file": "transformers/main_classes/model.md", "section_heading": "from_pretrained[[transformers.PreTrainedModel.from_pretrained]]", "char_start": 13036, "char_end": 13621, "token_estimate": 146, "prev_chunk_id": 475, "next_chunk_id": 477, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 477, "text": "attn_implementation (`str`, *optional*) : The attention implementation to use in the model (if relevant). Can be any of - `\"eager\"` (manual implementation of the attention) - `\"sdpa\"` (using [`F.scaled_dot_product_attention`](https://pytorch.org/docs/master/generated/torch.nn.functional.scaled_dot_product_attention.html)) - `\"flash_attention_2\"` (using [Dao-AILab/flash-attention](https://github.com/Dao-AILab/flash-attention)) - `\"flash_attention_3\"` (using [Dao-AILab/flash-attention/hopper](https://github.com/Dao-AILab/flash-attention/tree/main/hopper)) - `\"flash_attention_4\"` (using [Dao-AILab/flash-attention/flash_attn/cute](https://github.com/Dao-AILab/flash-attention/tree/main/flash_attn/cute)). By default, if available, SDPA will be used. The default is otherwise the manual `\"eager\"` implementation. Accept HF kernel references in the form: /[@][:] - and are any non-\"/\" and non-\":\" sequences. - \"@\" is optional (branch, tag, or commit-ish), e.g. \"@main\", \"@v1.2.0\", \"@abc123\". - \":\" is optional and selects a function inside the kernel repo. - Both options can appear together and in this order only: @revision first, then :kernel_name. - We intentionally allow a leading \"|\" prefix (e.g., \"flash|...\") because the code strips it before loading; '|' is not excluded in the character classes here. Examples that match: \"org/model\" \"org/model@main\" \"org/model:custom_kernel\" \"org/model@v1.2.3:custom_kernel\"", "source_file": "transformers/main_classes/model.md", "section_heading": "from_pretrained[[transformers.PreTrainedModel.from_pretrained]]", "char_start": 13625, "char_end": 15052, "token_estimate": 356, "prev_chunk_id": 476, "next_chunk_id": 478, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 478, "text": "experts_implementation (`str`, *optional*) : The experts implementation to use in the model (if relevant). Can be any of: - `\"eager\"` (sequential implementation of the experts matrix multiplications). - `\"batched_mm\"` (using [`torch.bmm`](https://pytorch.org/docs/stable/generated/torch.bmm.html)). - `\"grouped_mm\"` (using [`torch.nn.functional.grouped_mm`](https://docs.pytorch.org/docs/main/generated/torch.nn.functional.grouped_mm.html)). By default, if the model supports it, `\"grouped_mm\"` will be used. The default is otherwise the manual `\"eager\"` implementation.", "source_file": "transformers/main_classes/model.md", "section_heading": "from_pretrained[[transformers.PreTrainedModel.from_pretrained]]", "char_start": 15054, "char_end": 15626, "token_estimate": 143, "prev_chunk_id": 477, "next_chunk_id": 479, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 479, "text": "#### get_compiled_call[[transformers.PreTrainedModel.get_compiled_call]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L4576)\n\nReturn a `torch.compile`'d version of `self.__call__`. This is useful to dynamically choose between\nnon-compiled/compiled `forward` during inference, especially to switch between prefill (where we don't\nwant to use compiled version to avoid recomputing the graph with new shapes) and iterative decoding\n(where we want the speed-ups of compiled version with static shapes).", "source_file": "transformers/main_classes/model.md", "section_heading": "get_compiled_call[[transformers.PreTrainedModel.get_compiled_call]]", "char_start": 15627, "char_end": 16181, "token_estimate": 138, "prev_chunk_id": 478, "next_chunk_id": 480, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 480, "text": "#### get_decoder[[transformers.PreTrainedModel.get_decoder]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L2288)\n\nBest-effort lookup of the *decoder* module.\n\nOrder of attempts (covers ~85 % of current usages):\n\n1. `self.decoder/self.language_model/self.text_model`\n2. `self.base_model` (many wrappers store the decoder here)\n3. `self.base_model.get_decoder()` (nested wrappers)\n4. fallback: raise for the few exotic models that need a bespoke rule", "source_file": "transformers/main_classes/model.md", "section_heading": "get_decoder[[transformers.PreTrainedModel.get_decoder]]", "char_start": 16182, "char_end": 16706, "token_estimate": 131, "prev_chunk_id": 479, "next_chunk_id": 481, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 481, "text": "#### get_encoder[[transformers.PreTrainedModel.get_encoder]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L2230)\n\nBest-effort lookup of the *encoder* module. If provided with `modality` argument,\nit looks for a modality-specific encoder in multimodal models (e.g. \"image_encoder\")\nBy default the function returns model's text encoder if any, and otherwise returns `self`.\n\nPossible `modality` values are \"image\", \"video\" and \"audio\".", "source_file": "transformers/main_classes/model.md", "section_heading": "get_encoder[[transformers.PreTrainedModel.get_encoder]]", "char_start": 16707, "char_end": 17196, "token_estimate": 122, "prev_chunk_id": 480, "next_chunk_id": 482, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 482, "text": "#### get_expanded_tied_weights_keys[[transformers.PreTrainedModel.get_expanded_tied_weights_keys]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L2439)\n\nReturn the expanded tied weight keys (in case they contain modules or regex patterns) for only the current\nmodel, or recursively for all submodels if `all_submodels=True` (i.e. it will re-check the config values for all\nsubmodels).\n\nFor almost all models, we only require to tie the embeddings, so the model has an internal property\n`_tied_weights_keys = {\"lm_head.weight\": \"model.embed_tokens.weight\"}`. In this case, the mapping is already\n\"expanded\", i.e. it already contains full parameters, and this function will simply return a copy of the property.\nFor more complex patterns, e.g. for `DFineForObjectDetection`, we have the following attribute", "source_file": "transformers/main_classes/model.md", "section_heading": "get_expanded_tied_weights_keys[[transformers.PreTrainedModel.get_expanded_tied_weights_keys]]", "char_start": 17197, "char_end": 18056, "token_estimate": 214, "prev_chunk_id": 481, "next_chunk_id": 483, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 483, "text": "```\n_tied_weights_keys = {\n r\"bbox_embed.(?![0])\\d+\": \"bbox_embed.0\",\n r\"class_embed.(?![0])\\d+\": \"class_embed.0\",\n \"model.decoder.class_embed\": \"class_embed\",\n \"model.decoder.bbox_embed\": \"bbox_embed\",\n}\n```\n\nIn this case, the function looks up all the model's parameters and buffers, and matches all the params,", "source_file": "transformers/main_classes/model.md", "section_heading": "get_expanded_tied_weights_keys[[transformers.PreTrainedModel.get_expanded_tied_weights_keys]]", "char_start": 18058, "char_end": 18383, "token_estimate": 81, "prev_chunk_id": 482, "next_chunk_id": 484, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 484, "text": "returning the following:\n```\n{\n 'bbox_embed.1.layers.0.bias': 'bbox_embed.0.layers.0.bias',\n 'bbox_embed.1.layers.0.weight': 'bbox_embed.0.layers.0.weight',\n 'bbox_embed.1.layers.1.bias': 'bbox_embed.0.layers.1.bias',\n 'bbox_embed.1.layers.1.weight': 'bbox_embed.0.layers.1.weight',\n 'bbox_embed.1.layers.2.bias': 'bbox_embed.0.layers.2.bias',\n 'bbox_embed.1.layers.2.weight': 'bbox_embed.0.layers.2.weight',\n 'bbox_embed.2.layers.0.bias': 'bbox_embed.0.layers.0.bias',\n 'bbox_embed.2.layers.0.weight': 'bbox_embed.0.layers.0.weight',\n ...\n 'class_embed.1.bias': 'class_embed.0.bias',\n 'class_embed.1.weight': 'class_embed.0.weight',\n 'class_embed.2.bias': 'class_embed.0.bias',\n 'class_embed.2.weight': 'class_embed.0.weight',\n ...\n 'model.decoder.class_embed.0.bias': 'class_embed.0.bias',\n 'model.decoder.class_embed.0.weight': 'class_embed.0.weight',\n 'model.decoder.class_embed.1.bias': 'class_embed.0.bias',\n 'model.decoder.class_embed.1.weight': 'class_embed.0.weight',\n ...\n 'model.decoder.bbox_embed.0.layers.0.bias': 'bbox_embed.0.layers.0.bias',\n 'model.decoder.bbox_embed.0.layers.0.weight': 'bbox_embed.0.layers.0.weight',\n 'model.decoder.bbox_embed.0.layers.1.bias': 'bbox_embed.0.layers.1.bias',\n 'model.decoder.bbox_embed.0.layers.1.weight': 'bbox_embed.0.layers.1.weight',\n ...\n}\n```", "source_file": "transformers/main_classes/model.md", "section_heading": "get_expanded_tied_weights_keys[[transformers.PreTrainedModel.get_expanded_tied_weights_keys]]", "char_start": 18385, "char_end": 19757, "token_estimate": 343, "prev_chunk_id": 483, "next_chunk_id": 485, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 485, "text": "i.e. all the parameters matching the regex and modules patterns in `_tied_weights_keys`", "source_file": "transformers/main_classes/model.md", "section_heading": "get_expanded_tied_weights_keys[[transformers.PreTrainedModel.get_expanded_tied_weights_keys]]", "char_start": 19759, "char_end": 19846, "token_estimate": 21, "prev_chunk_id": 484, "next_chunk_id": 486, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 486, "text": "#### get_memory_footprint[[transformers.PreTrainedModel.get_memory_footprint]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L3517)\n\nGet the memory footprint of a model. This will return the memory footprint of the current model in bytes.\nUseful to benchmark the memory footprint of the current model and design some tests. Solution inspired from the\nPyTorch discussions: https://discuss.pytorch.org/t/gpu-memory-that-model-uses/56822/2\n\n**Parameters:**\n\nreturn_buffers (`bool`, *optional*, defaults to `True`) : Whether to return the size of the buffer tensors in the computation of the memory footprint. Buffers are tensors that do not require gradients and not registered as parameters. E.g. mean and std in batch norm layers. Please see: https://discuss.pytorch.org/t/what-pytorch-means-by-buffers/120266/2", "source_file": "transformers/main_classes/model.md", "section_heading": "get_memory_footprint[[transformers.PreTrainedModel.get_memory_footprint]]", "char_start": 19847, "char_end": 20712, "token_estimate": 216, "prev_chunk_id": 485, "next_chunk_id": 487, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 487, "text": "#### get_parameter_or_buffer[[transformers.PreTrainedModel.get_parameter_or_buffer]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L4745)\n\nReturn the parameter or buffer given by `target` if it exists, otherwise throw an error. This combines\n`get_parameter()` and `get_buffer()` in a single handy function. If the target is an `_extra_state` attribute,\nit will return the extra state provided by the module. Note that it only work if `target` is a leaf of the model.", "source_file": "transformers/main_classes/model.md", "section_heading": "get_parameter_or_buffer[[transformers.PreTrainedModel.get_parameter_or_buffer]]", "char_start": 20713, "char_end": 21234, "token_estimate": 130, "prev_chunk_id": 486, "next_chunk_id": 488, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 488, "text": "#### gradient_checkpointing_disable[[transformers.PreTrainedModel.gradient_checkpointing_disable]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L3189)\n\nDeactivates gradient checkpointing for the current model.", "source_file": "transformers/main_classes/model.md", "section_heading": "gradient_checkpointing_disable[[transformers.PreTrainedModel.gradient_checkpointing_disable]]", "char_start": 21235, "char_end": 21500, "token_estimate": 66, "prev_chunk_id": 487, "next_chunk_id": 489, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 489, "text": "#### gradient_checkpointing_enable[[transformers.PreTrainedModel.gradient_checkpointing_enable]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L3125)\n\nActivates gradient checkpointing for the current model.\n\nWe pass the `__call__` method of the modules instead of `forward` because `__call__` attaches all the hooks of\nthe module. https://discuss.pytorch.org/t/any-different-between-model-input-and-model-forward-input/3690/2\n\n**Parameters:**\n\ngradient_checkpointing_kwargs (dict, *optional*) : Additional keyword arguments passed along to the `torch.utils.checkpoint.checkpoint` function.", "source_file": "transformers/main_classes/model.md", "section_heading": "gradient_checkpointing_enable[[transformers.PreTrainedModel.gradient_checkpointing_enable]]", "char_start": 21501, "char_end": 22145, "token_estimate": 161, "prev_chunk_id": 488, "next_chunk_id": 490, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 490, "text": "#### init_weights[[transformers.PreTrainedModel.init_weights]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L3113)\n\nInitialize and tie the weights if needed. If using a custom `PreTrainedModel`, you need to implement any\ninitialization logic in `_init_weights`.", "source_file": "transformers/main_classes/model.md", "section_heading": "init_weights[[transformers.PreTrainedModel.init_weights]]", "char_start": 22146, "char_end": 22463, "token_estimate": 79, "prev_chunk_id": 489, "next_chunk_id": 491, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 491, "text": "#### initialize_weights[[transformers.PreTrainedModel.initialize_weights]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L2411)\n\nThis is equivalent to calling `self.apply(self._initialize_weights)`, but correctly handles composite models.\nThis function dynamically dispatches the correct `init_weights` function to the modules as we advance in the\nmodule graph along the recursion. It can handle an arbitrary number of sub-models. Without it, every composite\nmodel would have to recurse a second time on all sub-models explicitly in the outer-most `_init_weights`, which\nis extremely error prone and inefficient.", "source_file": "transformers/main_classes/model.md", "section_heading": "initialize_weights[[transformers.PreTrainedModel.initialize_weights]]", "char_start": 22464, "char_end": 23131, "token_estimate": 166, "prev_chunk_id": 490, "next_chunk_id": 492, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 492, "text": "#### kernelize[[transformers.PreTrainedModel.kernelize]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L4530)\n\nTemporarily register hidden kernel wrappers so `kernelize` can discover and replace them.", "source_file": "transformers/main_classes/model.md", "section_heading": "kernelize[[transformers.PreTrainedModel.kernelize]]", "char_start": 23132, "char_end": 23387, "token_estimate": 63, "prev_chunk_id": 491, "next_chunk_id": 493, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 493, "text": "#### mark_tied_weights_as_initialized[[transformers.PreTrainedModel.mark_tied_weights_as_initialized]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L4717)\n\nAdds the `_is_hf_initialized` flag on parameters that will be tied, in order to avoid initializing them\nlater as they will be tied (overwritten) anyway.\nThis is very important as most embeddings are tied, and they are huge params (vocabularies are often 256k), so\nrunning inits on them is very costly.", "source_file": "transformers/main_classes/model.md", "section_heading": "mark_tied_weights_as_initialized[[transformers.PreTrainedModel.mark_tied_weights_as_initialized]]", "char_start": 23388, "char_end": 23901, "token_estimate": 128, "prev_chunk_id": 492, "next_chunk_id": 494, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 494, "text": "#### named_non_persistent_buffers[[transformers.PreTrainedModel.named_non_persistent_buffers]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L4769)\n\nSimilar to `named_buffers`, but only yield non-persistent ones. It is handy as it's not perfectly straightforward\nto know if they are persistent or not", "source_file": "transformers/main_classes/model.md", "section_heading": "named_non_persistent_buffers[[transformers.PreTrainedModel.named_non_persistent_buffers]]", "char_start": 23902, "char_end": 24257, "token_estimate": 88, "prev_chunk_id": 493, "next_chunk_id": 495, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 495, "text": "#### post_init[[transformers.PreTrainedModel.post_init]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L1326)\n\nA method executed at the end of each Transformer model initialization, to execute code that needs the model's\nmodules properly initialized (such as weight initialization).\nIt is also used to obtain all correct static properties (parallelism plans, tied_weights_keys, _keep_in_fp32_modules, etc)\ncorrectly in the case of composite models (that is, the top level model should know about those properties from its children).", "source_file": "transformers/main_classes/model.md", "section_heading": "post_init[[transformers.PreTrainedModel.post_init]]", "char_start": 24258, "char_end": 24845, "token_estimate": 146, "prev_chunk_id": 494, "next_chunk_id": 496, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 496, "text": "#### register_for_auto_class[[transformers.PreTrainedModel.register_for_auto_class]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L4415)\n\nRegister this class with a given auto class. This should only be used for custom models as the ones in the\nlibrary are already mapped with an auto class.\n\n**Parameters:**\n\nauto_class (`str` or `type`, *optional*, defaults to `\"AutoModel\"`) : The auto class to register this new model with.", "source_file": "transformers/main_classes/model.md", "section_heading": "register_for_auto_class[[transformers.PreTrainedModel.register_for_auto_class]]", "char_start": 24846, "char_end": 25329, "token_estimate": 120, "prev_chunk_id": 495, "next_chunk_id": 497, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 497, "text": "#### resize_token_embeddings[[transformers.PreTrainedModel.resize_token_embeddings]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L2648)\n\nResizes input token embeddings matrix of the model if `new_num_tokens != config.vocab_size`.\n\nTakes care of tying weights embeddings afterwards if the model class has a `tie_weights()` method.\n\n**Parameters:**\n\nnew_num_tokens (`int`, *optional*) : The new number of tokens in the embedding matrix. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end. If not provided or `None`, just returns a pointer to the input tokens `torch.nn.Embedding` module of the model without doing anything.", "source_file": "transformers/main_classes/model.md", "section_heading": "resize_token_embeddings[[transformers.PreTrainedModel.resize_token_embeddings]]", "char_start": 25330, "char_end": 26075, "token_estimate": 186, "prev_chunk_id": 496, "next_chunk_id": 498, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 498, "text": "pad_to_multiple_of (`int`, *optional*) : If set will pad the embedding matrix to a multiple of the provided value.If `new_num_tokens` is set to `None` will just pad the embedding to a multiple of `pad_to_multiple_of`. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128. For more details about this, or help on choosing the correct value for resizing, refer to this guide: https://docs.nvidia.com/deeplearning/performance/dl-performance-matrix-multiplication/index.html#requirements-tc", "source_file": "transformers/main_classes/model.md", "section_heading": "resize_token_embeddings[[transformers.PreTrainedModel.resize_token_embeddings]]", "char_start": 26077, "char_end": 26707, "token_estimate": 157, "prev_chunk_id": 497, "next_chunk_id": 499, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 499, "text": "mean_resizing (`bool`) : Whether to initialize the added embeddings from a multivariate normal distribution that has old embeddings' mean and covariance or to initialize them with a normal distribution that has a mean of zero and std equals `config.initializer_range`. Setting `mean_resizing` to `True` is useful when increasing the size of the embeddings of causal language models, where the generated tokens' probabilities won't be affected by the added embeddings because initializing the new embeddings with the old embeddings' mean will reduce the kl-divergence between the next token probability before and after adding the new embeddings. Refer to this article for more information: https://nlp.stanford.edu/~johnhew/vocab-expansion.html\n\n**Returns:**\n\n``torch.nn.Embedding``\n\nPointer to the input tokens Embeddings Module of the model.", "source_file": "transformers/main_classes/model.md", "section_heading": "resize_token_embeddings[[transformers.PreTrainedModel.resize_token_embeddings]]", "char_start": 26709, "char_end": 27553, "token_estimate": 211, "prev_chunk_id": 498, "next_chunk_id": 500, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 500, "text": "#### save_pretrained[[transformers.PreTrainedModel.save_pretrained]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L3216)\n\nSave a model and its configuration file to a directory, so that it can be re-loaded using the\n[from_pretrained()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) class method.\n\n**Parameters:**\n\nsave_directory (`str` or `os.PathLike`) : Directory to which to save. Will be created if it doesn't exist.\n\nis_main_process (`bool`, *optional*, defaults to `True`) : Whether the process calling this is the main process or not. Useful when in distributed training like TPUs and need to call this function on all processes. In this case, set `is_main_process=True` only on the main process to avoid race conditions.", "source_file": "transformers/main_classes/model.md", "section_heading": "save_pretrained[[transformers.PreTrainedModel.save_pretrained]]", "char_start": 27554, "char_end": 28386, "token_estimate": 208, "prev_chunk_id": 499, "next_chunk_id": 501, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 501, "text": "state_dict (nested dictionary of `torch.Tensor`) : The state dictionary of the model to save. Will default to `self.state_dict()`, but can be used to only save parts of the model or if special precautions need to be taken when recovering the state dictionary of a model (like when using model parallelism).\n\npush_to_hub (`bool`, *optional*, defaults to `False`) : Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the repository you want to push to with `repo_id` (will default to the name of `save_directory` in your namespace).\n\nmax_shard_size (`int` or `str`, *optional*, defaults to `\"50GB\"`) : The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size lower than this size. If expressed as a string, needs to be digits followed by a unit (like `\"5MB\"`). If a single weight of the model is bigger than `max_shard_size`, it will be in its own checkpoint shard which will be bigger than `max_shard_size`.", "source_file": "transformers/main_classes/model.md", "section_heading": "save_pretrained[[transformers.PreTrainedModel.save_pretrained]]", "char_start": 28388, "char_end": 29386, "token_estimate": 249, "prev_chunk_id": 500, "next_chunk_id": 502, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 502, "text": "variant (`str`, *optional*) : If specified, weights are saved in the format model..safetensors.\n\ntoken (`str` or `bool`, *optional*) : The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use the token generated when running `hf auth login` (stored in `~/.huggingface`).\n\nsave_peft_format (`bool`, *optional*, defaults to `True`) : For backward compatibility with PEFT library, in case adapter weights are attached to the model, all keys of the state dict of adapters needs to be prepended with `base_model.model`. Advanced users can disable this behaviours by setting `save_peft_format` to `False`.\n\nsave_original_format (`bool`, *optional*, defaults to `True`) : For backward compatibility with the previous versions of `transformers` you can save the checkpoint with its reverse mapping. The reverse mapping needs to exists even if the model was loaded from a None legacy checkpoint.", "source_file": "transformers/main_classes/model.md", "section_heading": "save_pretrained[[transformers.PreTrainedModel.save_pretrained]]", "char_start": 29391, "char_end": 30322, "token_estimate": 232, "prev_chunk_id": 501, "next_chunk_id": 503, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 503, "text": "kwargs (`dict[str, Any]`, *optional*) : Additional key word arguments passed along to the [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.utils.PushToHubMixin.push_to_hub) method.", "source_file": "transformers/main_classes/model.md", "section_heading": "save_pretrained[[transformers.PreTrainedModel.save_pretrained]]", "char_start": 30324, "char_end": 30532, "token_estimate": 52, "prev_chunk_id": 502, "next_chunk_id": 504, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 504, "text": "#### set_attn_implementation[[transformers.PreTrainedModel.set_attn_implementation]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L2025)\n\nSet the requested `attn_implementation` for this model.\n\n**Parameters:**\n\nattn_implementation (`str` or `dict`) : The attention implementation to set for this model. It can be either a `str`, in which case it will be dispatched to all submodels if relevant, or a `dict` where keys are the sub_configs name, in which case each submodel will dispatch the corresponding value.\n\nallow_all_kernels (`bool`, optional) : Whether to load kernels from unverified hub repos, if `attn_implementation` is a custom kernel outside of the `kernels-community` hub repository.", "source_file": "transformers/main_classes/model.md", "section_heading": "set_attn_implementation[[transformers.PreTrainedModel.set_attn_implementation]]", "char_start": 30533, "char_end": 31286, "token_estimate": 188, "prev_chunk_id": 503, "next_chunk_id": 505, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 505, "text": "#### set_decoder[[transformers.PreTrainedModel.set_decoder]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L2311)\n\nSymmetric setter. Mirrors the lookup logic used in `get_decoder`.", "source_file": "transformers/main_classes/model.md", "section_heading": "set_decoder[[transformers.PreTrainedModel.set_decoder]]", "char_start": 31287, "char_end": 31522, "token_estimate": 58, "prev_chunk_id": 504, "next_chunk_id": 506, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 506, "text": "#### set_encoder[[transformers.PreTrainedModel.set_encoder]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L2262)\n\nSymmetric setter. Mirrors the lookup logic used in `get_encoder`.", "source_file": "transformers/main_classes/model.md", "section_heading": "set_encoder[[transformers.PreTrainedModel.set_encoder]]", "char_start": 31523, "char_end": 31758, "token_estimate": 58, "prev_chunk_id": 505, "next_chunk_id": 507, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 507, "text": "#### set_experts_implementation[[transformers.PreTrainedModel.set_experts_implementation]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L2127)\n\nSet the requested `experts_implementation` for this model.\n\n**Parameters:**\n\nexperts_implementation (`str` or `dict`) : The experts implementation to set for this model. It can be either a `str`, in which case it will be dispatched to all submodels if relevant, or a `dict` where keys are the sub_configs name, in which case each submodel will dispatch the corresponding value.", "source_file": "transformers/main_classes/model.md", "section_heading": "set_experts_implementation[[transformers.PreTrainedModel.set_experts_implementation]]", "char_start": 31759, "char_end": 32336, "token_estimate": 144, "prev_chunk_id": 506, "next_chunk_id": 508, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 508, "text": "#### set_use_kernels[[transformers.PreTrainedModel.set_use_kernels]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L3690)\n\nSet whether or not to use the `kernels` library to kernelize some layers of the model.\n\n**Parameters:**\n\nuse_kernels (`bool`) : Whether or not to use the `kernels` library to kernelize some layers of the model.\n\nkernel_config (`KernelConfig`, *optional*) : The kernel configuration to use to kernelize the model. If `None`, the default kernel mapping will be used.", "source_file": "transformers/main_classes/model.md", "section_heading": "set_use_kernels[[transformers.PreTrainedModel.set_use_kernels]]", "char_start": 32337, "char_end": 32879, "token_estimate": 135, "prev_chunk_id": 507, "next_chunk_id": 509, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 509, "text": "#### tie_weights[[transformers.PreTrainedModel.tie_weights]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L2553)\n\nTie the model weights. If `recompute_mapping=False` (default when called internally), it will rely on the\n`model.all_tied_weights_keys` attribute, containing the `{target: source}` mapping for the tied params.\nIf `recompute_mapping=True`, it will re-check all internal submodels and their config to determine the params\nthat need to be tied. This is the default when `model.tie_weights()` is called on its own, outside of\n`__init__`, and `from_pretrained`, in case the config values were changed somewhere.\n\nNote that during `from_pretrained`, tying is *symmetric*: if the mapping says \"tie target -> source\" but\n`source` is missing in the checkpoint while `target` exists, we *swap* source and target so we can still\ntie everything to the parameter that actually exists.", "source_file": "transformers/main_classes/model.md", "section_heading": "tie_weights[[transformers.PreTrainedModel.tie_weights]]", "char_start": 32880, "char_end": 33821, "token_estimate": 235, "prev_chunk_id": 508, "next_chunk_id": 510, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 510, "text": "#### warn_if_padding_and_no_attention_mask[[transformers.PreTrainedModel.warn_if_padding_and_no_attention_mask]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L4437)\n\nShows a one-time warning if the input_ids appear to contain padding and no attention mask was given.\n\nCustom models should also include a `_supports_assign_param_buffer`, which determines if superfast init can apply\non the particular model. Signs that your model needs this are if `test_save_and_load_from_pretrained` fails. If so,\nset this to `False`.", "source_file": "transformers/main_classes/model.md", "section_heading": "warn_if_padding_and_no_attention_mask[[transformers.PreTrainedModel.warn_if_padding_and_no_attention_mask]]", "char_start": 33822, "char_end": 34396, "token_estimate": 143, "prev_chunk_id": 509, "next_chunk_id": 511, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 511, "text": "## ModuleUtilsMixin[[transformers.modeling_utils.ModuleUtilsMixin]]", "source_file": "transformers/main_classes/model.md", "section_heading": "ModuleUtilsMixin[[transformers.modeling_utils.ModuleUtilsMixin]]", "char_start": 34398, "char_end": 34465, "token_estimate": 16, "prev_chunk_id": 510, "next_chunk_id": 512, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 512, "text": "#### transformers.modeling_utils.ModuleUtilsMixin[[transformers.modeling_utils.ModuleUtilsMixin]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L882)\n\nA few utilities for `torch.nn.Modules`, to be used as a mixin.\n\nget_extended_attention_masktransformers.modeling_utils.ModuleUtilsMixin.get_extended_attention_maskhttps://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L946[{\"name\": \"attention_mask\", \"val\": \": Tensor\"}, {\"name\": \"input_shape\", \"val\": \": tuple\"}, {\"name\": \"dtype\", \"val\": \": torch.dtype | None = None\"}]- **attention_mask** (`torch.Tensor`) --\n Mask with ones indicating tokens to attend to, zeros for tokens to ignore.\n- **input_shape** (`tuple[int]`) --\n The shape of the input to the model.0`torch.Tensor` The extended attention mask, with a the same dtype as `attention_mask.dtype`.\n\nMakes broadcastable attention and causal masks so that future and masked tokens are ignored.\n\n**Parameters:**", "source_file": "transformers/main_classes/model.md", "section_heading": "transformers.modeling_utils.ModuleUtilsMixin[[transformers.modeling_utils.ModuleUtilsMixin]]", "char_start": 34467, "char_end": 35474, "token_estimate": 251, "prev_chunk_id": 511, "next_chunk_id": 513, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 513, "text": "attention_mask (`torch.Tensor`) : Mask with ones indicating tokens to attend to, zeros for tokens to ignore.\n\ninput_shape (`tuple[int]`) : The shape of the input to the model.\n\n**Returns:**\n\n`torch.Tensor` The extended attention mask, with a the same dtype as `attention_mask.dtype`.", "source_file": "transformers/main_classes/model.md", "section_heading": "transformers.modeling_utils.ModuleUtilsMixin[[transformers.modeling_utils.ModuleUtilsMixin]]", "char_start": 35476, "char_end": 35759, "token_estimate": 70, "prev_chunk_id": 512, "next_chunk_id": 514, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 514, "text": "#### invert_attention_mask[[transformers.modeling_utils.ModuleUtilsMixin.invert_attention_mask]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L902)\n\nInvert an attention mask (e.g., switches 0. and 1.).\n\n**Parameters:**\n\nencoder_attention_mask (`torch.Tensor`) : An attention mask.\n\n**Returns:**\n\n``torch.Tensor``\n\nThe inverted attention mask.", "source_file": "transformers/main_classes/model.md", "section_heading": "invert_attention_mask[[transformers.modeling_utils.ModuleUtilsMixin.invert_attention_mask]]", "char_start": 35760, "char_end": 36158, "token_estimate": 99, "prev_chunk_id": 513, "next_chunk_id": 515, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 515, "text": "#### num_parameters[[transformers.modeling_utils.ModuleUtilsMixin.num_parameters]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_utils.py#L995)\n\nGet number of (optionally, trainable or non-embeddings) parameters in the module.\n\n**Parameters:**\n\nonly_trainable (`bool`, *optional*, defaults to `False`) : Whether or not to return only the number of trainable parameters \n\nexclude_embeddings (`bool`, *optional*, defaults to `False`) : Whether or not to return only the number of non-embeddings parameters\n\n**Returns:**\n\n``int``\n\nThe number of parameters.", "source_file": "transformers/main_classes/model.md", "section_heading": "num_parameters[[transformers.modeling_utils.ModuleUtilsMixin.num_parameters]]", "char_start": 36159, "char_end": 36758, "token_estimate": 149, "prev_chunk_id": 514, "next_chunk_id": 516, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 516, "text": "## Pushing to the Hub[[transformers.utils.PushToHubMixin]]", "source_file": "transformers/main_classes/model.md", "section_heading": "Pushing to the Hub[[transformers.utils.PushToHubMixin]]", "char_start": 36760, "char_end": 36818, "token_estimate": 14, "prev_chunk_id": 515, "next_chunk_id": 517, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 517, "text": "#### transformers.utils.PushToHubMixin[[transformers.utils.PushToHubMixin]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/utils/hub.py#L626)\n\nA Mixin containing the functionality to push a model or tokenizer to the hub.", "source_file": "transformers/main_classes/model.md", "section_heading": "transformers.utils.PushToHubMixin[[transformers.utils.PushToHubMixin]]", "char_start": 36820, "char_end": 37076, "token_estimate": 64, "prev_chunk_id": 516, "next_chunk_id": 518, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 518, "text": "push_to_hubtransformers.utils.PushToHubMixin.push_to_hubhttps://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/utils/hub.py#L720[{\"name\": \"repo_id\", \"val\": \": str\"}, {\"name\": \"commit_message\", \"val\": \": str | None = None\"}, {\"name\": \"commit_description\", \"val\": \": str | None = None\"}, {\"name\": \"private\", \"val\": \": bool | None = None\"}, {\"name\": \"token\", \"val\": \": bool | str | None = None\"}, {\"name\": \"revision\", \"val\": \": str | None = None\"}, {\"name\": \"create_pr\", \"val\": \": bool = False\"}, {\"name\": \"max_shard_size\", \"val\": \": int | str | None = '50GB'\"}, {\"name\": \"tags\", \"val\": \": list[str] | None = None\"}]- **repo_id** (`str`) --\n The name of the repository you want to push your {object} to. It should contain your organization name\n when pushing to a given organization.\n- **commit_message** (`str`, *optional*) --\n Message to commit while pushing. Will default to `\"Upload {object}\"`.\n- **commit_description** (`str`, *optional*) --\n The description of the commit that will be created\n- **private** (`bool`, *optional*) --\n Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.\n- **token** (`bool` or `str`, *optional*) --\n The token to use as HTTP bearer authorization for remote files. If `True` (default), will use the token generated\n when running `hf auth login` (stored in `~/.huggingface`).\n- **revision** (`str`, *optional*) --\n Branch to push the uploaded files to.\n- **create_pr** (`bool`, *optional*, defaults to `False`) --\n Whether or not to create a PR with the uploaded files or directly commit.\n- **max_shard_size** (`int` or `str`, *optional*, defaults to `\"50GB\"`) --\n Only applicable for models. The maximum size for a checkpoint before being sharded. Checkpoints shard\n will then be each of size lower than this size. If expressed as a string, needs to be digits followed\n by a unit (like `\"5MB\"`).\n- **tags** (`list[str]`, *optional*) --\n List of tags to push on the Hub.0", "source_file": "transformers/main_classes/model.md", "section_heading": "transformers.utils.PushToHubMixin[[transformers.utils.PushToHubMixin]]", "char_start": 37078, "char_end": 39134, "token_estimate": 514, "prev_chunk_id": 517, "next_chunk_id": 519, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 519, "text": "Upload the {object_files} to the \ud83e\udd17 Model Hub.\n\nExamples:\n\n```python\nfrom transformers import {object_class}\n\n{object} = {object_class}.from_pretrained(\"google-bert/bert-base-cased\")", "source_file": "transformers/main_classes/model.md", "section_heading": "transformers.utils.PushToHubMixin[[transformers.utils.PushToHubMixin]]", "char_start": 39136, "char_end": 39317, "token_estimate": 45, "prev_chunk_id": 518, "next_chunk_id": 520, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 520, "text": "# Push the {object} to your namespace with the name \"my-finetuned-bert\".\n{object}.push_to_hub(\"my-finetuned-bert\")", "source_file": "transformers/main_classes/model.md", "section_heading": "Push the {object} to your namespace with the name \"my-finetuned-bert\".", "char_start": 39319, "char_end": 39433, "token_estimate": 28, "prev_chunk_id": 519, "next_chunk_id": 521, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 521, "text": "# Push the {object} to an organization with the name \"my-finetuned-bert\".\n{object}.push_to_hub(\"huggingface/my-finetuned-bert\")\n```\n\n**Parameters:**\n\nrepo_id (`str`) : The name of the repository you want to push your {object} to. It should contain your organization name when pushing to a given organization.\n\ncommit_message (`str`, *optional*) : Message to commit while pushing. Will default to `\"Upload {object}\"`.\n\ncommit_description (`str`, *optional*) : The description of the commit that will be created\n\nprivate (`bool`, *optional*) : Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.\n\ntoken (`bool` or `str`, *optional*) : The token to use as HTTP bearer authorization for remote files. If `True` (default), will use the token generated when running `hf auth login` (stored in `~/.huggingface`).\n\nrevision (`str`, *optional*) : Branch to push the uploaded files to.", "source_file": "transformers/main_classes/model.md", "section_heading": "Push the {object} to an organization with the name \"my-finetuned-bert\".", "char_start": 39435, "char_end": 40433, "token_estimate": 249, "prev_chunk_id": 520, "next_chunk_id": 522, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 522, "text": "create_pr (`bool`, *optional*, defaults to `False`) : Whether or not to create a PR with the uploaded files or directly commit.\n\nmax_shard_size (`int` or `str`, *optional*, defaults to `\"50GB\"`) : Only applicable for models. The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size lower than this size. If expressed as a string, needs to be digits followed by a unit (like `\"5MB\"`).\n\ntags (`list[str]`, *optional*) : List of tags to push on the Hub.", "source_file": "transformers/main_classes/model.md", "section_heading": "Push the {object} to an organization with the name \"my-finetuned-bert\".", "char_start": 5487, "char_end": 5980, "token_estimate": 123, "prev_chunk_id": 521, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/main_classes/model", "doc_title": "Models" }, { "chunk_id": 523, "text": "# Tokenizer\n\nA tokenizer is in charge of preparing the inputs for a model. The library contains tokenizers for all the models. Most\nof the tokenizers are available in two flavors: a full python implementation and a \"Fast\" implementation based on the\nRust library [\ud83e\udd17 Tokenizers](https://github.com/huggingface/tokenizers). The \"Fast\" implementations allows:\n\n1. a significant speed-up in particular when doing batched tokenization and\n2. additional methods to map between the original string (character and words) and the token space (e.g. getting the\n index of the token comprising a given character or the span of characters corresponding to a given token).", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Tokenizer", "char_start": 0, "char_end": 660, "token_estimate": 165, "prev_chunk_id": null, "next_chunk_id": 524, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 524, "text": "The base classes [PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend) and [PreTrainedTokenizerFast](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.TokenizersBackend)\nimplement the common methods for encoding string inputs in model inputs (see below) and instantiating/saving python and\n\"Fast\" tokenizers either from a local file or directory or from a pretrained tokenizer provided by the library\n(downloaded from HuggingFace's AWS S3 repository). They both rely on\n[PreTrainedTokenizerBase](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase) that contains the common methods.\n\n[PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend) and [PreTrainedTokenizerFast](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.TokenizersBackend) thus implement the main\nmethods for using all the tokenizers:", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Tokenizer", "char_start": 662, "char_end": 1628, "token_estimate": 241, "prev_chunk_id": 523, "next_chunk_id": 525, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 525, "text": "- Tokenizing (splitting strings in sub-word token strings), converting tokens strings to ids and back, and\n encoding/decoding (i.e., tokenizing and converting to integers).\n- Adding new tokens to the vocabulary in a way that is independent of the underlying structure (BPE, SentencePiece...).\n- Managing special tokens (like mask, beginning-of-sentence, etc.): adding them, assigning them to attributes in the\n tokenizer for easy access and making sure they are not split during tokenization.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Tokenizer", "char_start": 1630, "char_end": 2124, "token_estimate": 123, "prev_chunk_id": 524, "next_chunk_id": 526, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 526, "text": "[BatchEncoding](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.BatchEncoding) holds the output of the\n[PreTrainedTokenizerBase](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase)'s encoding methods (`__call__`,\n`encode_plus` and `batch_encode_plus`) and is derived from a Python dictionary. When the tokenizer is a pure python\ntokenizer, this class behaves just like a standard python dictionary and holds the various model inputs computed by\nthese methods (`input_ids`, `attention_mask`...). When the tokenizer is a \"Fast\" tokenizer (i.e., backed by\nHuggingFace [tokenizers library](https://github.com/huggingface/tokenizers)), this class provides in addition\nseveral advanced alignment methods which can be used to map between the original string (character and words) and the\ntoken space (e.g., getting the index of the token comprising a given character or the span of characters corresponding\nto a given token).", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Tokenizer", "char_start": 2126, "char_end": 3104, "token_estimate": 244, "prev_chunk_id": 525, "next_chunk_id": 527, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 527, "text": "## Multimodal Tokenizer\n\nApart from that each tokenizer can be a \"multimodal\" tokenizer which means that the tokenizer will hold all relevant special tokens\nas part of tokenizer attributes for easier access. For example, if the tokenizer is loaded from a vision-language model like LLaVA, you will\nbe able to access `tokenizer.image_token_id` to obtain the special image token used as a placeholder.\n\nTo enable extra special tokens for any type of tokenizer, you have to add the following lines and save the tokenizer. Extra special tokens do not\nhave to be modality related and can be anything that the model often needs access to. In the below code, tokenizer at `output_dir` will have direct access\nto three more special tokens. \n\n```python\nvision_tokenizer = AutoTokenizer.from_pretrained(\n \"llava-hf/llava-1.5-7b-hf\",\n extra_special_tokens={\"image_token\": \"\", \"boi_token\": \"\", \"eoi_token\": \"\"}\n)\nprint(vision_tokenizer.image_token, vision_tokenizer.image_token_id)\n(\"\", 32000)\n```", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Multimodal Tokenizer", "char_start": 3106, "char_end": 4098, "token_estimate": 248, "prev_chunk_id": 526, "next_chunk_id": 528, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 528, "text": "## PreTrainedTokenizer[[transformers.PythonBackend]]", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "PreTrainedTokenizer[[transformers.PythonBackend]]", "char_start": 4100, "char_end": 4152, "token_estimate": 13, "prev_chunk_id": 527, "next_chunk_id": 529, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 529, "text": "#### transformers.PythonBackend[[transformers.PythonBackend]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_python.py#L400)\n\nBase class for all slow tokenizers.\n\nInherits from [PreTrainedTokenizerBase](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase).\n\nHandle all the shared methods for tokenization and special tokens as well as methods downloading/caching/loading\npretrained tokenizers as well as adding tokens to the vocabulary.\n\nThis class also contain the added tokens in a unified way on top of all tokenizers so we don't have to handle the\nspecific vocabulary augmentation methods of the various underlying dictionary structures (BPE, sentencepiece...).\n\nClass attributes (overridden by derived classes)", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 4154, "char_end": 4960, "token_estimate": 201, "prev_chunk_id": 528, "next_chunk_id": 530, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 530, "text": "- **vocab_files_names** (`dict[str, str]`) -- A dictionary with, as keys, the `__init__` keyword name of each\n vocabulary file required by the model, and as associated values, the filename for saving the associated file\n (string).\n- **pretrained_vocab_files_map** (`dict[str, dict[str, str]]`) -- A dictionary of dictionaries, with the\n high-level keys being the `__init__` keyword name of each vocabulary file required by the model, the\n low-level being the `short-cut-names` of the pretrained models with, as associated values, the `url` to the\n associated pretrained vocabulary file.\n- **model_input_names** (`list[str]`) -- A list of inputs expected in the forward pass of the model.\n- **padding_side** (`str`) -- The default value for the side on which the model should have padding applied.\n Should be `'right'` or `'left'`.\n- **truncation_side** (`str`) -- The default value for the side on which the model should have truncation\n applied. Should be `'right'` or `'left'`.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 4962, "char_end": 5948, "token_estimate": 246, "prev_chunk_id": 529, "next_chunk_id": 531, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 531, "text": "__call__transformers.PythonBackend.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L2415[{\"name\": \"text\", \"val\": \": TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None\"}, {\"name\": \"text_pair\", \"val\": \": TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None\"}, {\"name\": \"text_target\", \"val\": \": TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None\"}, {\"name\": \"text_pair_target\", \"val\": \": TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None\"}, {\"name\": \"add_special_tokens\", \"val\": \": bool = True\"}, {\"name\": \"padding\", \"val\": \": bool | str | PaddingStrategy = False\"}, {\"name\": \"truncation\", \"val\": \": bool | str | TruncationStrategy | None = None\"}, {\"name\": \"max_length\", \"val\": \": int | None = None\"}, {\"name\": \"stride\", \"val\": \": int = 0\"}, {\"name\": \"is_split_into_words\", \"val\": \": bool = False\"}, {\"name\": \"pad_to_multiple_of\", \"val\": \": int | None = None\"}, {\"name\": \"padding_side\", \"val\": \": str | None = None\"}, {\"name\": \"return_tensors\", \"val\": \": str | TensorType | None = None\"}, {\"name\": \"return_token_type_ids\", \"val\": \": bool | None = None\"}, {\"name\": \"return_attention_mask\", \"val\": \": bool | None = None\"}, {\"name\": \"return_overflowing_tokens\", \"val\": \": bool = False\"}, {\"name\": \"return_special_tokens_mask\", \"val\": \": bool = False\"}, {\"name\": \"return_offsets_mapping\", \"val\": \": bool = False\"}, {\"name\": \"return_length\", \"val\": \": bool = False\"}, {\"name\": \"verbose\", \"val\": \": bool = True\"}, {\"name\": \"tokenizer_kwargs\", \"val\": \": dict[str, Any] | None = None\"}, {\"name\": \"**kwargs\", \"val\": \"\"}]- **text** (`str`, `list[str]`, `list[list[str]]`, *optional*) --\n The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings\n (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set\n `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).\n- **text_pair** (`str`, `list[str]`, `list[list[str]]`, *optional*) --\n The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings\n (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set\n `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).\n- **text_target** (`str`, `list[str]`, `list[list[str]]`, *optional*) --\n The sequence or batch of sequences to be encoded as target texts. Each sequence can be a string or a\n list of strings (pretokenized string). If the sequences are provided as list of strings (pretokenized),\n you must set `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).\n- **text_pair_target** (`str`, `list[str]`, `list[list[str]]`, *optional*) --\n The sequence or batch of sequences to be encoded as target texts. Each sequence can be a string or a\n list of strings (pretokenized string). If the sequences are provided as list of strings (pretokenized),\n you must set `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).\n- **tokenizer_kwargs** (`dict[str, Any]`, *optional*) --\n Additional kwargs to pass to the tokenizer. These will be merged with the explicit parameters and\n other kwargs, with explicit parameters taking precedence.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 5950, "char_end": 9346, "token_estimate": 849, "prev_chunk_id": 530, "next_chunk_id": 532, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 532, "text": "- **add_special_tokens** (`bool`, *optional*, defaults to `True`) --\n Whether or not to add special tokens when encoding the sequences. This will use the underlying\n `PretrainedTokenizerBase.build_inputs_with_special_tokens` function, which defines which tokens are\n automatically added to the input ids. This is useful if you want to add `bos` or `eos` tokens\n automatically.\n- **padding** (`bool`, `str` or [PaddingStrategy](/docs/transformers/v5.6.2/en/internal/file_utils#transformers.utils.PaddingStrategy), *optional*, defaults to `False`) --\n Activates and controls padding. Accepts the following values:", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 9348, "char_end": 9964, "token_estimate": 154, "prev_chunk_id": 531, "next_chunk_id": 533, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 533, "text": "- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single\n sequence is provided).\n - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n- **truncation** (`bool`, `str` or [TruncationStrategy](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.tokenization_utils_base.TruncationStrategy), *optional*, defaults to `False`) --\n Activates and controls truncation. Accepts the following values:", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 9968, "char_end": 10665, "token_estimate": 174, "prev_chunk_id": 532, "next_chunk_id": 534, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 534, "text": "- `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or\n to the maximum acceptable input length for the model if that argument is not provided. This will\n truncate token by token, removing a token from the longest sequence in the pair if a pair of\n sequences (or a batch of pairs) is provided.\n - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the\n maximum acceptable input length for the model if that argument is not provided. This will only\n truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the\n maximum acceptable input length for the model if that argument is not provided. This will only\n truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n- **max_length** (`int`, *optional*) --\n Controls the maximum length to use by one of the truncation/padding parameters.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 10669, "char_end": 11906, "token_estimate": 309, "prev_chunk_id": 533, "next_chunk_id": 535, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 535, "text": "If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n- **stride** (`int`, *optional*, defaults to 0) --\n If set to a number along with `max_length`, the overflowing tokens returned when\n `return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence\n returned to provide some overlap between truncated and overflowing sequences. The value of this\n argument defines the number of overlapping tokens.\n- **is_split_into_words** (`bool`, *optional*, defaults to `False`) --\n Whether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the\n tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace)\n which it will tokenize. This is useful for NER or token classification.\n- **pad_to_multiple_of** (`int`, *optional*) --\n If set will pad the sequence to a multiple of the provided value. Requires `padding` to be activated.\n This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability\n `>= 7.5` (Volta).\n- **padding_side** (`str`, *optional*) --\n The side on which the model should have padding applied. Should be selected between ['right', 'left'].\n Default value is picked from the class attribute of the same name.\n- **return_tensors** (`str` or [TensorType](/docs/transformers/v5.6.2/en/internal/file_utils#transformers.TensorType), *optional*) --\n If set, will return tensors instead of list of python integers. Acceptable values are:", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 11910, "char_end": 13644, "token_estimate": 434, "prev_chunk_id": 534, "next_chunk_id": 536, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 536, "text": "- `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return Numpy `np.ndarray` objects.\n\n- **return_token_type_ids** (`bool`, *optional*) --\n Whether to return token type IDs. If left to the default, will return the token type IDs according to\n the specific tokenizer's default, defined by the `return_outputs` attribute.\n\n [What are token type IDs?](../glossary#token-type-ids)\n- **return_attention_mask** (`bool`, *optional*) --\n Whether to return the attention mask. If left to the default, will return the attention mask according\n to the specific tokenizer's default, defined by the `return_outputs` attribute.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 13648, "char_end": 14276, "token_estimate": 157, "prev_chunk_id": 535, "next_chunk_id": 537, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 537, "text": "[What are attention masks?](../glossary#attention-mask)\n- **return_overflowing_tokens** (`bool`, *optional*, defaults to `False`) --\n Whether or not to return overflowing token sequences. If a pair of sequences of input ids (or a batch\n of pairs) is provided with `truncation_strategy = longest_first` or `True`, an error is raised instead\n of returning overflowing tokens.\n- **return_special_tokens_mask** (`bool`, *optional*, defaults to `False`) --\n Whether or not to return special tokens mask information.\n- **return_offsets_mapping** (`bool`, *optional*, defaults to `False`) --\n Whether or not to return `(char_start, char_end)` for each token.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 14280, "char_end": 14936, "token_estimate": 164, "prev_chunk_id": 536, "next_chunk_id": 538, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 538, "text": "This is only available on fast tokenizers inheriting from [PreTrainedTokenizerFast](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.TokenizersBackend), if using\n Python's tokenizer, this method will raise `NotImplementedError`.\n- **return_length** (`bool`, *optional*, defaults to `False`) --\n Whether or not to return the lengths of the encoded inputs.\n- **verbose** (`bool`, *optional*, defaults to `True`) --\n Whether or not to print more information and warnings.\n- ****kwargs** -- passed to the `self.tokenize()` method0[BatchEncoding](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.BatchEncoding)A [BatchEncoding](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.BatchEncoding) with the following fields:\n\n- **input_ids** -- List of token ids to be fed to a model.\n\n [What are input IDs?](../glossary#input-ids)", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 14940, "char_end": 15813, "token_estimate": 218, "prev_chunk_id": 537, "next_chunk_id": 539, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 539, "text": "- **token_type_ids** -- List of token type ids to be fed to a model (when `return_token_type_ids=True` or\n if *\"token_type_ids\"* is in `self.model_input_names`).\n\n [What are token type IDs?](../glossary#token-type-ids)\n\n- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when\n `return_attention_mask=True` or if *\"attention_mask\"* is in `self.model_input_names`).\n\n [What are attention masks?](../glossary#attention-mask)\n\n- **overflowing_tokens** -- List of overflowing tokens sequences (when a `max_length` is specified and\n `return_overflowing_tokens=True`).\n- **num_truncated_tokens** -- Number of tokens truncated (when a `max_length` is specified and\n `return_overflowing_tokens=True`).\n- **special_tokens_mask** -- List of 0s and 1s, with 1 specifying added special tokens and 0 specifying\n regular sequence tokens (when `add_special_tokens=True` and `return_special_tokens_mask=True`).\n- **length** -- The length of the inputs (when `return_length=True`)", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 15815, "char_end": 16833, "token_estimate": 254, "prev_chunk_id": 538, "next_chunk_id": 540, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 540, "text": "Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of\nsequences.\n\n**Parameters:**\n\nmodel_max_length (`int`, *optional*) : The maximum length (in number of tokens) for the inputs to the transformer model. When the tokenizer is loaded with [from_pretrained()](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.from_pretrained), this will be set to the value stored for the associated model in `max_model_input_sizes` (see above). If no value is provided, will default to VERY_LARGE_INTEGER (`int(1e30)`).\n\npadding_side (`str`, *optional*) : The side on which the model should have padding applied. Should be selected between ['right', 'left']. Default value is picked from the class attribute of the same name.\n\ntruncation_side (`str`, *optional*) : The side on which the model should have truncation applied. Should be selected between ['right', 'left']. Default value is picked from the class attribute of the same name.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 16835, "char_end": 17851, "token_estimate": 254, "prev_chunk_id": 539, "next_chunk_id": 541, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 541, "text": "chat_template (`str`, *optional*) : A Jinja template string that will be used to format lists of chat messages. See https://huggingface.co/docs/transformers/chat_templating for a full description.\n\nmodel_input_names (`list[string]`, *optional*) : The list of inputs accepted by the forward pass of the model (like `\"token_type_ids\"` or `\"attention_mask\"`). Default value is picked from the class attribute of the same name.\n\nbos_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing the beginning of a sentence.\n\neos_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing the end of a sentence.\n\nunk_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing an out-of-vocabulary token.\n\nsep_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token separating two different sentences in the same input (used by BERT for instance).", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 17853, "char_end": 18781, "token_estimate": 232, "prev_chunk_id": 540, "next_chunk_id": 542, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 542, "text": "pad_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by attention mechanisms or loss computation.\n\ncls_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing the class of the input (used by BERT for instance).\n\nmask_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing a masked token (used by masked-language modeling pretraining objectives, like BERT). Will be associated to `self.mask_token` and `self.mask_token_id`.\n\nextra_special_tokens (list of `str` or `tokenizers.AddedToken`, *optional*) : A list of extra model-specific special tokens. Add them here to ensure they are skipped when decoding with `skip_special_tokens` is set to True. If they are not part of the vocabulary, they will be added at the end of the vocabulary.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 18783, "char_end": 19684, "token_estimate": 225, "prev_chunk_id": 541, "next_chunk_id": 543, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 543, "text": "split_special_tokens (`bool`, *optional*, defaults to `False`) : Whether or not the special tokens should be split during the tokenization process. Passing will affect the internal state of the tokenizer. The default behavior is to not split special tokens. This means that if `` is the `bos_token`, then `tokenizer.tokenize(\"\") = ['`]. Otherwise, if `split_special_tokens=True`, then `tokenizer.tokenize(\"\")` will be give `['']`.\n\n**Returns:**\n\n`[BatchEncoding](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.BatchEncoding)`\n\nA [BatchEncoding](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.BatchEncoding) with the following fields:\n\n- **input_ids** -- List of token ids to be fed to a model.\n\n [What are input IDs?](../glossary#input-ids)\n\n- **token_type_ids** -- List of token type ids to be fed to a model (when `return_token_type_ids=True` or\n if *\"token_type_ids\"* is in `self.model_input_names`).\n\n [What are token type IDs?](../glossary#token-type-ids)", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 19686, "char_end": 20685, "token_estimate": 249, "prev_chunk_id": 542, "next_chunk_id": 544, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 544, "text": "- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when\n `return_attention_mask=True` or if *\"attention_mask\"* is in `self.model_input_names`).\n\n [What are attention masks?](../glossary#attention-mask)\n\n- **overflowing_tokens** -- List of overflowing tokens sequences (when a `max_length` is specified and\n `return_overflowing_tokens=True`).\n- **num_truncated_tokens** -- Number of tokens truncated (when a `max_length` is specified and\n `return_overflowing_tokens=True`).\n- **special_tokens_mask** -- List of 0s and 1s, with 1 specifying added special tokens and 0 specifying\n regular sequence tokens (when `add_special_tokens=True` and `return_special_tokens_mask=True`).\n- **length** -- The length of the inputs (when `return_length=True`)", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 16037, "char_end": 16833, "token_estimate": 199, "prev_chunk_id": 543, "next_chunk_id": 545, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 545, "text": "#### add_tokens[[transformers.PythonBackend.add_tokens]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L1213)\n\n#TODO remove this from here! PreTrainedTOkeniuzerBase should be agnostic of AddedToken.\n\nAdd a list of new tokens. If the new tokens are not in the vocabulary, they are added to the end. Added tokens and\ntokens from the vocabulary of the tokenization algorithm are therefore not treated in the same way.\n\nExamples:\n\n```python", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "add_tokens[[transformers.PythonBackend.add_tokens]]", "char_start": 21484, "char_end": 21984, "token_estimate": 125, "prev_chunk_id": 544, "next_chunk_id": 546, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 546, "text": "# Let's see how to increase the vocabulary of Bert model and tokenizer\ntokenizer = BertTokenizerFast.from_pretrained(\"google-bert/bert-base-uncased\")\nmodel = BertModel.from_pretrained(\"google-bert/bert-base-uncased\")\n\nnum_added_toks = tokenizer.add_tokens([\"new_tok1\", \"my_new-tok2\"])\nprint(\"We have added\", num_added_toks, \"tokens\")", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Let's see how to increase the vocabulary of Bert model and tokenizer", "char_start": 21985, "char_end": 22318, "token_estimate": 83, "prev_chunk_id": 545, "next_chunk_id": 547, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 547, "text": "# Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e., the length of the tokenizer.\nmodel.resize_token_embeddings(len(tokenizer))\n```\n\n**Parameters:**\n\nnew_tokens (`str`, `tokenizers.AddedToken` or a sequence of *str* or `tokenizers.AddedToken`) : Tokens are only added if they are not already in the vocabulary. `tokenizers.AddedToken` wraps a string token to let you personalize its behavior: whether this token should only match against a single word, whether this token should strip all potential whitespaces on the left side, whether this token should strip all potential whitespaces on the right side, etc.\n\nspecial_tokens (`bool`, *optional*, defaults to `False`) : Specifies if the token is special. This mostly changes the normalization behavior See details for `tokenizers.AddedToken` in HuggingFace tokenizers library.\n\n**Returns:**\n\n``int``\n\nNumber of tokens added to the vocabulary.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e., the length of the tokenizer.", "char_start": 22319, "char_end": 23254, "token_estimate": 233, "prev_chunk_id": 546, "next_chunk_id": 548, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 548, "text": "#### add_special_tokens[[transformers.PythonBackend.add_special_tokens]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L1106)\n\nAdd a dictionary of special tokens (eos, pad, cls, etc.) to the encoder and link them to class attributes. If\nspecial tokens are NOT in the vocabulary, they are added to it (indexed starting from the last index of the\ncurrent vocabulary).\n\nWhen adding new tokens to the vocabulary, you should make sure to also resize the token embedding matrix of the\nmodel so that its embedding matrix matches the tokenizer.\n\nIn order to do that, please use the [resize_token_embeddings()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel.resize_token_embeddings) method.\n\nUsing `add_special_tokens` will ensure your special tokens can be used in several ways:", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "add_special_tokens[[transformers.PythonBackend.add_special_tokens]]", "char_start": 23255, "char_end": 24119, "token_estimate": 216, "prev_chunk_id": 547, "next_chunk_id": 549, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 549, "text": "- Special tokens can be skipped when decoding using `skip_special_tokens = True`.\n- Special tokens are carefully handled by the tokenizer (they are never split), similar to `AddedTokens`.\n- You can easily refer to special tokens using tokenizer class attributes like `tokenizer.cls_token`. This\n makes it easy to develop model-agnostic training and fine-tuning scripts.\n\nWhen possible, special tokens are already registered for provided pretrained models (for instance\n[BertTokenizer](/docs/transformers/v5.6.2/en/model_doc/squeezebert#transformers.BertTokenizer) `cls_token` is already registered to be `'[CLS]'` and XLM's one is also registered to be\n`''`).\n\nExamples:\n\n```python", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "add_special_tokens[[transformers.PythonBackend.add_special_tokens]]", "char_start": 24121, "char_end": 24803, "token_estimate": 170, "prev_chunk_id": 548, "next_chunk_id": 550, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 550, "text": "# Let's see how to add a new classification token to GPT-2\ntokenizer = GPT2Tokenizer.from_pretrained(\"openai-community/gpt2\")\nmodel = GPT2Model.from_pretrained(\"openai-community/gpt2\")\n\nspecial_tokens_dict = {\"cls_token\": \"\"}\n\nnum_added_toks = tokenizer.add_special_tokens(special_tokens_dict)\nprint(\"We have added\", num_added_toks, \"tokens\")", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Let's see how to add a new classification token to GPT-2", "char_start": 24804, "char_end": 25146, "token_estimate": 85, "prev_chunk_id": 549, "next_chunk_id": 551, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 551, "text": "# Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e., the length of the tokenizer.\nmodel.resize_token_embeddings(len(tokenizer))\n\nassert tokenizer.cls_token == \"\"\n```\n\n**Parameters:**\n\nspecial_tokens_dict (dictionary *str* to *str*, `tokenizers.AddedToken`, or `Sequence[Union[str, AddedToken]]`) : Keys should be in the list of predefined special attributes: [`bos_token`, `eos_token`, `unk_token`, `sep_token`, `pad_token`, `cls_token`, `mask_token`, `extra_special_tokens`]. Tokens are only added if they are not already in the vocabulary (tested by checking if the tokenizer assign the index of the `unk_token` to them).", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e., the length of the tokenizer.", "char_start": 25147, "char_end": 25813, "token_estimate": 166, "prev_chunk_id": 550, "next_chunk_id": 552, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 552, "text": "replace_extra_special_tokens (`bool`, *optional*, defaults to `True`) : If `True`, the existing list of extra special tokens will be replaced by the list provided in `special_tokens_dict`. Otherwise, `extra_special_tokens` will be extended. In the former case, the tokens will NOT be removed from the tokenizer's full vocabulary - they are only being flagged as non-special tokens. Remember, this only affects which tokens are skipped during decoding, not the `added_tokens_encoder` and `added_tokens_decoder`. This means that the previous `extra_special_tokens` are still added tokens, and will not be split by the model.\n\n**Returns:**\n\n``int``\n\nNumber of tokens added to the vocabulary.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e., the length of the tokenizer.", "char_start": 25815, "char_end": 26503, "token_estimate": 172, "prev_chunk_id": 551, "next_chunk_id": 553, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 553, "text": "#### apply_chat_template[[transformers.PythonBackend.apply_chat_template]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L2968)\n\nConverts a list of dictionaries with `\"role\"` and `\"content\"` keys to a list of token\nids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to\ndetermine the format and control tokens to use when converting.\n\n**Parameters:**\n\nconversation (Union[list[dict[str, str]], list[list[dict[str, str]]]]) : A list of dicts with \"role\" and \"content\" keys, representing the chat history so far.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "apply_chat_template[[transformers.PythonBackend.apply_chat_template]]", "char_start": 26504, "char_end": 27135, "token_estimate": 157, "prev_chunk_id": 552, "next_chunk_id": 554, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 554, "text": "tools (`list[Union[Dict, Callable]]`, *optional*) : A list of tools (callable functions) that will be accessible to the model. If the template does not support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema, giving the name, description and argument types for the tool. See our [tool use guide](https://huggingface.co/docs/transformers/en/chat_extras#passing-tools) for more information.\n\ndocuments (`list[dict[str, str]]`, *optional*) : A list of dicts representing documents that will be accessible to the model if it is performing RAG (retrieval-augmented generation). If the template does not support RAG, this argument will have no effect. We recommend that each document should be a dict containing \"title\" and \"text\" keys.\n\nchat_template (`str`, *optional*) : A Jinja template to use for this conversion. It is usually not necessary to pass anything to this argument, as the model's template will be used by default.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "apply_chat_template[[transformers.PythonBackend.apply_chat_template]]", "char_start": 27137, "char_end": 28110, "token_estimate": 243, "prev_chunk_id": 553, "next_chunk_id": 555, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 555, "text": "add_generation_prompt (bool, *optional*) : If this is set, a prompt with the token(s) that indicate the start of an assistant message will be appended to the formatted output. This is useful when you want to generate a response from the model. Note that this argument will be passed to the chat template, and so it must be supported in the template for this argument to have any effect.\n\ncontinue_final_message (bool, *optional*) : If this is set, the chat will be formatted so that the final message in the chat is open-ended, without any EOS tokens. The model will continue this message rather than starting a new one. This allows you to \"prefill\" part of the model's response for it. Cannot be used at the same time as `add_generation_prompt`.\n\ntokenize (`bool`, defaults to `True`) : Whether to tokenize the output. If `False`, the output will be a string.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "apply_chat_template[[transformers.PythonBackend.apply_chat_template]]", "char_start": 28112, "char_end": 28972, "token_estimate": 215, "prev_chunk_id": 554, "next_chunk_id": 556, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 556, "text": "padding (`bool`, `str` or [PaddingStrategy](/docs/transformers/v5.6.2/en/internal/file_utils#transformers.utils.PaddingStrategy), *optional*, defaults to `False`) : Select a strategy to pad the returned sequences (according to the model's padding side and padding index) among: - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths).\n\ntruncation (`bool`, defaults to `False`) : Whether to truncate sequences at the maximum length. Has no effect if tokenize is `False`.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "apply_chat_template[[transformers.PythonBackend.apply_chat_template]]", "char_start": 28974, "char_end": 29795, "token_estimate": 205, "prev_chunk_id": 555, "next_chunk_id": 557, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 557, "text": "max_length (`int`, *optional*) : Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is `False`. If not specified, the tokenizer's `max_length` attribute will be used as a default.\n\nreturn_tensors (`str` or [TensorType](/docs/transformers/v5.6.2/en/internal/file_utils#transformers.TensorType), *optional*) : If set, will return tensors of a particular framework. Has no effect if tokenize is `False`. Acceptable values are: - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return NumPy `np.ndarray` objects.\n\nreturn_dict (`bool`, defaults to `True`) : Whether to return a dictionary with named outputs. Has no effect if tokenize is `False`.\n\ntokenizer_kwargs (`dict[str : Any]`, *optional*): Additional kwargs to pass to the tokenizer.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "apply_chat_template[[transformers.PythonBackend.apply_chat_template]]", "char_start": 29797, "char_end": 30578, "token_estimate": 195, "prev_chunk_id": 556, "next_chunk_id": 558, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 558, "text": "return_assistant_tokens_mask (`bool`, defaults to `False`) : Whether to return a mask of the assistant generated tokens. For tokens generated by the assistant, the mask will contain 1. For user and system tokens, the mask will contain 0. This functionality is only available for chat templates that support it via the `{% generation %}` keyword.\n\n- ****kwargs** : Additional kwargs to pass to the template renderer. Will be accessible by the chat template.\n\n**Returns:**\n\n``Union[list[int], Dict]``\n\nA list of token ids representing the tokenized chat so far, including control tokens. This\noutput is ready to pass to the model, either directly or via methods like `generate()`. If `return_dict` is\nset, will return a dict of tokenizer outputs instead.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "apply_chat_template[[transformers.PythonBackend.apply_chat_template]]", "char_start": 30580, "char_end": 31332, "token_estimate": 188, "prev_chunk_id": 557, "next_chunk_id": 559, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 559, "text": "#### batch_decode[[transformers.PythonBackend.batch_decode]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L2880)\n\nConvert a list of lists of token ids into a list of strings by calling decode.\n\nThis method is provided for backwards compatibility. The `decode` method now handles batched input natively,\nso you can use `decode` directly instead of `batch_decode`.\n\n**Parameters:**\n\nsequences (`Union[list[int], list[list[int]], np.ndarray, torch.Tensor]`) : List of tokenized input ids. Can be obtained using the `__call__` method.\n\nskip_special_tokens (`bool`, *optional*, defaults to `False`) : Whether or not to remove special tokens in the decoding.\n\nclean_up_tokenization_spaces (`bool`, *optional*) : Whether or not to clean up the tokenization spaces. If `None`, will default to `self.clean_up_tokenization_spaces`.\n\nkwargs (additional keyword arguments, *optional*) : Will be passed to the underlying model specific decode method.\n\n**Returns:**", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "batch_decode[[transformers.PythonBackend.batch_decode]]", "char_start": 31333, "char_end": 32349, "token_estimate": 254, "prev_chunk_id": 558, "next_chunk_id": 560, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 560, "text": "``list[str]``\n\nThe list of decoded sentences.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "batch_decode[[transformers.PythonBackend.batch_decode]]", "char_start": 32351, "char_end": 32396, "token_estimate": 11, "prev_chunk_id": 559, "next_chunk_id": 561, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 561, "text": "#### decode[[transformers.PythonBackend.decode]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L2832)\n\nConverts a sequence of ids into a string, or a list of sequences into a list of strings,\nusing the tokenizer and vocabulary with options to remove special tokens and clean up\ntokenization spaces.\n\nSimilar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.\n\n**Parameters:**\n\ntoken_ids (`Union[int, list[int], list[list[int]], np.ndarray, torch.Tensor]`) : A single sequence or a batch (list of sequences) of tokenized input ids. Can be obtained using the `__call__` method.\n\nskip_special_tokens (`bool`, *optional*, defaults to `False`) : Whether or not to remove special tokens in the decoding.\n\nkwargs (additional keyword arguments, *optional*) : Will be passed to the underlying model specific decode method.\n\n**Returns:**\n\n``Union[str, list[str]]``", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "decode[[transformers.PythonBackend.decode]]", "char_start": 32397, "char_end": 33345, "token_estimate": 237, "prev_chunk_id": 560, "next_chunk_id": 562, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 562, "text": "The decoded string for a single sequence, or a list of decoded strings for a\nbatch of sequences.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "decode[[transformers.PythonBackend.decode]]", "char_start": 33347, "char_end": 33443, "token_estimate": 24, "prev_chunk_id": 561, "next_chunk_id": 563, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 563, "text": "#### encode[[transformers.PythonBackend.encode]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L2229)\n\nConverts a string to a sequence of ids (integer), using the tokenizer and vocabulary.\n\nSame as doing `self.convert_tokens_to_ids(self.tokenize(text))`.\n\n**Parameters:**\n\ntext (`str`, `list[str]` or `list[int]`) : The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids` method).\n\ntext_pair (`str`, `list[str]` or `list[int]`, *optional*) : Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids` method).", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "encode[[transformers.PythonBackend.encode]]", "char_start": 33444, "char_end": 34306, "token_estimate": 215, "prev_chunk_id": 562, "next_chunk_id": 564, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 564, "text": "add_special_tokens (`bool`, *optional*, defaults to `True`) : Whether or not to add special tokens when encoding the sequences. This will use the underlying `PretrainedTokenizerBase.build_inputs_with_special_tokens` function, which defines which tokens are automatically added to the input ids. This is useful if you want to add `bos` or `eos` tokens automatically.\n\npadding (`bool`, `str` or [PaddingStrategy](/docs/transformers/v5.6.2/en/internal/file_utils#transformers.utils.PaddingStrategy), *optional*, defaults to `False`) : Activates and controls padding. Accepts the following values: - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence is provided). - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths).", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "encode[[transformers.PythonBackend.encode]]", "char_start": 34309, "char_end": 35311, "token_estimate": 250, "prev_chunk_id": 563, "next_chunk_id": 565, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 565, "text": "truncation (`bool`, `str` or [TruncationStrategy](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.tokenization_utils_base.TruncationStrategy), *optional*, defaults to `False`) : Activates and controls truncation. Accepts the following values: - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size).", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "encode[[transformers.PythonBackend.encode]]", "char_start": 35313, "char_end": 36656, "token_estimate": 335, "prev_chunk_id": 564, "next_chunk_id": 566, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 566, "text": "max_length (`int`, *optional*) : Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated.\n\nstride (`int`, *optional*, defaults to 0) : If set to a number along with `max_length`, the overflowing tokens returned when `return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence returned to provide some overlap between truncated and overflowing sequences. The value of this argument defines the number of overlapping tokens.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "encode[[transformers.PythonBackend.encode]]", "char_start": 36658, "char_end": 37423, "token_estimate": 191, "prev_chunk_id": 565, "next_chunk_id": 567, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 567, "text": "is_split_into_words (`bool`, *optional*, defaults to `False`) : Whether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace) which it will tokenize. This is useful for NER or token classification.\n\npad_to_multiple_of (`int`, *optional*) : If set will pad the sequence to a multiple of the provided value. Requires `padding` to be activated. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).\n\npadding_side (`str`, *optional*) : The side on which the model should have padding applied. Should be selected between ['right', 'left']. Default value is picked from the class attribute of the same name.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "encode[[transformers.PythonBackend.encode]]", "char_start": 37425, "char_end": 38231, "token_estimate": 201, "prev_chunk_id": 566, "next_chunk_id": 568, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 568, "text": "return_tensors (`str` or [TensorType](/docs/transformers/v5.6.2/en/internal/file_utils#transformers.TensorType), *optional*) : If set, will return tensors instead of list of python integers. Acceptable values are: - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return Numpy `np.ndarray` objects. \n\n- ****kwargs** : Passed along to the `.tokenize()` method.\n\n**Returns:**\n\n``list[int]`, `torch.Tensor`, or `np.ndarray``\n\nThe tokenized ids of the text.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "encode[[transformers.PythonBackend.encode]]", "char_start": 38233, "char_end": 38696, "token_estimate": 115, "prev_chunk_id": 567, "next_chunk_id": 569, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 569, "text": "#### push_to_hub[[transformers.PythonBackend.push_to_hub]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/utils/hub.py#L720)\n\nUpload the tokenizer files to the \ud83e\udd17 Model Hub.\n\nExamples:\n\n```python\nfrom transformers import AutoTokenizer\n\ntokenizer = AutoTokenizer.from_pretrained(\"google-bert/bert-base-cased\")", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "push_to_hub[[transformers.PythonBackend.push_to_hub]]", "char_start": 38697, "char_end": 39040, "token_estimate": 85, "prev_chunk_id": 568, "next_chunk_id": 570, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 570, "text": "# Push the tokenizer to your namespace with the name \"my-finetuned-bert\".\ntokenizer.push_to_hub(\"my-finetuned-bert\")", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Push the tokenizer to your namespace with the name \"my-finetuned-bert\".", "char_start": 39042, "char_end": 39158, "token_estimate": 29, "prev_chunk_id": 569, "next_chunk_id": 571, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 571, "text": "# Push the tokenizer to an organization with the name \"my-finetuned-bert\".\ntokenizer.push_to_hub(\"huggingface/my-finetuned-bert\")\n```\n\n**Parameters:**\n\nrepo_id (`str`) : The name of the repository you want to push your tokenizer to. It should contain your organization name when pushing to a given organization.\n\ncommit_message (`str`, *optional*) : Message to commit while pushing. Will default to `\"Upload tokenizer\"`.\n\ncommit_description (`str`, *optional*) : The description of the commit that will be created\n\nprivate (`bool`, *optional*) : Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.\n\ntoken (`bool` or `str`, *optional*) : The token to use as HTTP bearer authorization for remote files. If `True` (default), will use the token generated when running `hf auth login` (stored in `~/.huggingface`).\n\nrevision (`str`, *optional*) : Branch to push the uploaded files to.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Push the tokenizer to an organization with the name \"my-finetuned-bert\".", "char_start": 39160, "char_end": 40162, "token_estimate": 250, "prev_chunk_id": 570, "next_chunk_id": 572, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 572, "text": "create_pr (`bool`, *optional*, defaults to `False`) : Whether or not to create a PR with the uploaded files or directly commit.\n\nmax_shard_size (`int` or `str`, *optional*, defaults to `\"50GB\"`) : Only applicable for models. The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size lower than this size. If expressed as a string, needs to be digits followed by a unit (like `\"5MB\"`).\n\ntags (`list[str]`, *optional*) : List of tags to push on the Hub.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Push the tokenizer to an organization with the name \"my-finetuned-bert\".", "char_start": 40164, "char_end": 40657, "token_estimate": 123, "prev_chunk_id": 571, "next_chunk_id": 573, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 573, "text": "#### build_inputs_with_special_tokens[[transformers.PythonBackend.build_inputs_with_special_tokens]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_python.py#L860)\n\nBuild model inputs from a sequence or a pair of sequences by adding special tokens.\n\nThis method dynamically builds inputs based on the tokenizer's `special_tokens_pattern`:\n- `\"none\"`: No special tokens\n- `\"cls_sep\"`: [CLS] seq0 [SEP] or [CLS] seq0 [SEP] seq1 [SEP]\n- `\"eos\"`: seq0 [EOS] or seq0 [EOS] seq1 [EOS]\n- `\"bos\"`: [BOS] seq0 or [BOS] seq0 [BOS] seq1\n- `\"bos_eos\"`: [BOS] seq0 [EOS] or [BOS] seq0 [EOS] seq1 [EOS]\n- `\"cls_double_sep\"`: [CLS] seq0 [SEP] or [CLS] seq0 [SEP] [SEP] seq1 [SEP]\n- `\"prefix_suffix\"`: ` seq0 [seq1] ` (custom prefix/suffix stored on the tokenizer)\n\n**Parameters:**\n\ntoken_ids_0 (`list[int]`) : List of IDs to which the special tokens will be added.\n\ntoken_ids_1 (`list[int]`, *optional*) : Optional second list of IDs for sequence pairs.\n\n**Returns:**\n\n``list[int]``", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "build_inputs_with_special_tokens[[transformers.PythonBackend.build_inputs_with_special_tokens]]", "char_start": 40658, "char_end": 41674, "token_estimate": 254, "prev_chunk_id": 572, "next_chunk_id": 574, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 574, "text": "List of input IDs with the appropriate special tokens.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "build_inputs_with_special_tokens[[transformers.PythonBackend.build_inputs_with_special_tokens]]", "char_start": 41676, "char_end": 41730, "token_estimate": 13, "prev_chunk_id": 573, "next_chunk_id": 575, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 575, "text": "#### create_token_type_ids_from_sequences[[transformers.PythonBackend.create_token_type_ids_from_sequences]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_python.py#L1292)\n\nCreate a mask from the two sequences passed to be used in a sequence-pair classification task.\n\nThis method dynamically builds the token type IDs based on the tokenizer's configuration attributes:\n- `token_type_ids_pattern`: Pattern to use (\"all_zeros\" or \"bert_style\")\n- `token_type_ids_include_special_tokens`: Whether to account for special tokens in length calculation\n\nExamples:\n```python", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "create_token_type_ids_from_sequences[[transformers.PythonBackend.create_token_type_ids_from_sequences]]", "char_start": 41731, "char_end": 42347, "token_estimate": 154, "prev_chunk_id": 574, "next_chunk_id": 576, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 576, "text": "# All zeros pattern (default, used by RoBERTa, BART, etc.)\ntokenizer.token_type_ids_pattern = \"all_zeros\"", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "All zeros pattern (default, used by RoBERTa, BART, etc.)", "char_start": 42348, "char_end": 42453, "token_estimate": 26, "prev_chunk_id": 575, "next_chunk_id": 577, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 577, "text": "# Returns: [0, 0, 0, ...] for both sequences", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Returns: [0, 0, 0, ...] for both sequences", "char_start": 42454, "char_end": 42498, "token_estimate": 11, "prev_chunk_id": 576, "next_chunk_id": 578, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 578, "text": "# BERT-style pattern (first sequence gets 0s, second gets 1s)\ntokenizer.token_type_ids_pattern = \"bert_style\"", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "BERT-style pattern (first sequence gets 0s, second gets 1s)", "char_start": 42500, "char_end": 42609, "token_estimate": 27, "prev_chunk_id": 577, "next_chunk_id": 579, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 579, "text": "# Returns: [0, 0, 0, ..., 1, 1, 1, ...] for sequence pairs\n```\n\n**Parameters:**\n\ntoken_ids_0 (`list[int]`) : List of IDs.\n\ntoken_ids_1 (`list[int]`, *optional*) : Optional second list of IDs for sequence pairs.\n\n**Returns:**\n\n``list[int]``\n\nToken type IDs according to the configured pattern.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Returns: [0, 0, 0, ..., 1, 1, 1, ...] for sequence pairs", "char_start": 42610, "char_end": 42902, "token_estimate": 73, "prev_chunk_id": 578, "next_chunk_id": 580, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 580, "text": "#### get_added_vocab[[transformers.PythonBackend.get_added_vocab]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_python.py#L488)\n\nReturns the added tokens in the vocabulary as a dictionary of token to index. Results might be different from\nthe fast call because for now we always add the tokens even if they are already in the vocabulary. This is\nsomething we should change.\n\n**Returns:**\n\n``dict[str, int]``\n\nThe added tokens.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "get_added_vocab[[transformers.PythonBackend.get_added_vocab]]", "char_start": 42903, "char_end": 43380, "token_estimate": 119, "prev_chunk_id": 579, "next_chunk_id": 581, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 581, "text": "#### get_special_tokens_mask[[transformers.PythonBackend.get_special_tokens_mask]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_python.py#L965)\n\nRetrieves sequence ids from a token list that has no special tokens added. This method is called when adding\nspecial tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.\n\nThis method dynamically builds the special tokens mask based on the tokenizer's `special_tokens_pattern`:\n- `\"none\"`: No special tokens (default, returns all 0s)\n- `\"cls_sep\"`: [CLS] seq0 [SEP] or [CLS] seq0 [SEP] seq1 [SEP]\n- `\"eos\"`: seq0 [EOS] or seq0 [EOS] seq1 [EOS]\n- `\"bos\"`: [BOS] seq0 or [BOS] seq0 [BOS] seq1\n- `\"bos_eos\"`: [BOS] seq0 [EOS] or [BOS] seq0 [EOS] seq1 [EOS]\n- `\"cls_double_sep\"`: [CLS] seq0 [SEP] or [CLS] seq0 [SEP] [SEP] seq1 [SEP]\n- `\"prefix_suffix\"`: ` seq0 [seq1] `\n\n**Parameters:**\n\ntoken_ids_0 (`list[int]`) : List of ids of the first sequence.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "get_special_tokens_mask[[transformers.PythonBackend.get_special_tokens_mask]]", "char_start": 43381, "char_end": 44343, "token_estimate": 240, "prev_chunk_id": 580, "next_chunk_id": 582, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 582, "text": "token_ids_1 (`list[int]`, *optional*) : List of ids of the second sequence.\n\nalready_has_special_tokens (`bool`, *optional*, defaults to `False`) : Whether or not the token list is already formatted with special tokens for the model.\n\n**Returns:**\n\n`A list of integers in the range [0, 1]`\n\n1 for a special token, 0 for a sequence token.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "get_special_tokens_mask[[transformers.PythonBackend.get_special_tokens_mask]]", "char_start": 44345, "char_end": 44682, "token_estimate": 84, "prev_chunk_id": 581, "next_chunk_id": 583, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 583, "text": "#### num_special_tokens_to_add[[transformers.PythonBackend.num_special_tokens_to_add]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_python.py#L602)\n\nReturns the number of added tokens when encoding a sequence with special tokens.\n\nThis encodes a dummy input and checks the number of added tokens, and is therefore not efficient. Do not put\nthis inside your training loop.\n\n**Parameters:**\n\npair (`bool`, *optional*, defaults to `False`) : Whether the number of added tokens should be computed in the case of a sequence pair or a single sequence.\n\n**Returns:**\n\n``int``\n\nNumber of special tokens added to sequences.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "num_special_tokens_to_add[[transformers.PythonBackend.num_special_tokens_to_add]]", "char_start": 44683, "char_end": 45348, "token_estimate": 166, "prev_chunk_id": 582, "next_chunk_id": 584, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 584, "text": "#### prepare_for_model[[transformers.PythonBackend.prepare_for_model]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_python.py#L1115)\n\nPrepares a sequence of input ids so it can be used by the model. Adds special tokens, truncates, and pads.\n\n**Parameters:**\n\nids : Tokenized input ids of the first sequence.\n\npair_ids : Tokenized input ids of the second sequence (optional).", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "prepare_for_model[[transformers.PythonBackend.prepare_for_model]]", "char_start": 45349, "char_end": 45774, "token_estimate": 106, "prev_chunk_id": 583, "next_chunk_id": 585, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 585, "text": "#### prepare_for_tokenization[[transformers.PythonBackend.prepare_for_tokenization]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_python.py#L836)\n\nPerforms any necessary transformations before tokenization.\n\nThis method should pop the arguments from kwargs and return the remaining `kwargs` as well. We test the\n`kwargs` at the end of the encoding process to be sure all the arguments have been used.\n\n**Parameters:**\n\ntext (`str`) : The text to prepare.\n\nis_split_into_words (`bool`, *optional*, defaults to `False`) : Whether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace) which it will tokenize. This is useful for NER or token classification.\n\nkwargs (`dict[str, Any]`, *optional*) : Keyword arguments to use for the tokenization.\n\n**Returns:**\n\n``tuple[str, dict[str, Any]]``\n\nThe prepared text and the unused kwargs.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "prepare_for_tokenization[[transformers.PythonBackend.prepare_for_tokenization]]", "char_start": 45775, "char_end": 46793, "token_estimate": 254, "prev_chunk_id": 584, "next_chunk_id": 586, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 586, "text": "#### save_vocabulary[[transformers.PythonBackend.save_vocabulary]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_python.py#L1356)\n\nDefault implementation for common vocabulary saving patterns.\nSaves self.encoder/self.vocab as JSON, optionally with self.bpe_ranks as merges.\nReturns empty tuple if no vocabulary exists.\n\nOverride this method if your tokenizer needs custom saving logic (e.g., SentencePiece models,\nmultiple vocabulary files, or special file formats).\n\n**Parameters:**\n\nsave_directory (`str`) : The directory in which to save the vocabulary.\n\nfilename_prefix (`str`, *optional*) : An optional prefix to add to the named of the saved files.\n\n**Returns:**\n\n``tuple[str, ...]``\n\nPaths to the files saved, or empty tuple if no files saved.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "save_vocabulary[[transformers.PythonBackend.save_vocabulary]]", "char_start": 46794, "char_end": 47594, "token_estimate": 200, "prev_chunk_id": 585, "next_chunk_id": 587, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 587, "text": "#### tokenize[[transformers.PythonBackend.tokenize]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_python.py#L625)\n\nConverts a string into a sequence of tokens, using the tokenizer.\n\n**Parameters:**\n\ntext : The sequence to be encoded.\n\n- ****kwargs** : Passed along to the model-specific `prepare_for_tokenization` preprocessing method.\n\n**Returns:**\n\nThe list of tokens.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "tokenize[[transformers.PythonBackend.tokenize]]", "char_start": 47595, "char_end": 48016, "token_estimate": 105, "prev_chunk_id": 586, "next_chunk_id": 588, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 588, "text": "#### truncate_sequences[[transformers.PythonBackend.truncate_sequences]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_python.py#L1225)\n\nTruncates sequences according to the specified strategy.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "truncate_sequences[[transformers.PythonBackend.truncate_sequences]]", "char_start": 48017, "char_end": 48260, "token_estimate": 60, "prev_chunk_id": 587, "next_chunk_id": 589, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 589, "text": "## PreTrainedTokenizerFast[[transformers.TokenizersBackend]]\n\nThe [PreTrainedTokenizerFast](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.TokenizersBackend) depend on the [tokenizers](https://huggingface.co/docs/tokenizers) library. The tokenizers obtained from the \ud83e\udd17 tokenizers library can be\nloaded very simply into \ud83e\udd17 transformers. Take a look at the [Using tokenizers from \ud83e\udd17 tokenizers](../fast_tokenizers) page to understand how this is done.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "PreTrainedTokenizerFast[[transformers.TokenizersBackend]]", "char_start": 48262, "char_end": 48727, "token_estimate": 116, "prev_chunk_id": 588, "next_chunk_id": 590, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 590, "text": "#### transformers.TokenizersBackend[[transformers.TokenizersBackend]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_tokenizers.py#L84)\n\nBase class for all fast tokenizers (wrapping HuggingFace tokenizers library).\n\nInherits from [PreTrainedTokenizerBase](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase).\n\nHandles all the shared methods for tokenization and special tokens, as well as methods for\ndownloading/caching/loading pretrained tokenizers, as well as adding tokens to the vocabulary.\n\nThis class also contains the added tokens in a unified way on top of all tokenizers so we don't have to handle the\nspecific vocabulary augmentation methods of the various underlying dictionary structures (BPE, sentencepiece...).\n\nClass attributes (overridden by derived classes)", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 48729, "char_end": 49602, "token_estimate": 218, "prev_chunk_id": 589, "next_chunk_id": 591, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 591, "text": "- **vocab_files_names** (`dict[str, str]`) -- A dictionary with, as keys, the `__init__` keyword name of each\n vocabulary file required by the model, and as associated values, the filename for saving the associated file\n (string).\n- **pretrained_vocab_files_map** (`dict[str, dict[str, str]]`) -- A dictionary of dictionaries, with the\n high-level keys being the `__init__` keyword name of each vocabulary file required by the model, the\n low-level being the `short-cut-names` of the pretrained models with, as associated values, the `url` to the\n associated pretrained vocabulary file.\n- **model_input_names** (`list[str]`) -- A list of inputs expected in the forward pass of the model.\n- **padding_side** (`str`) -- The default value for the side on which the model should have padding applied.\n Should be `'right'` or `'left'`.\n- **truncation_side** (`str`) -- The default value for the side on which the model should have truncation\n applied. Should be `'right'` or `'left'`.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 4962, "char_end": 5948, "token_estimate": 246, "prev_chunk_id": 590, "next_chunk_id": 592, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 592, "text": "__call__transformers.TokenizersBackend.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L2415[{\"name\": \"text\", \"val\": \": TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None\"}, {\"name\": \"text_pair\", \"val\": \": TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None\"}, {\"name\": \"text_target\", \"val\": \": TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None\"}, {\"name\": \"text_pair_target\", \"val\": \": TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None\"}, {\"name\": \"add_special_tokens\", \"val\": \": bool = True\"}, {\"name\": \"padding\", \"val\": \": bool | str | PaddingStrategy = False\"}, {\"name\": \"truncation\", \"val\": \": bool | str | TruncationStrategy | None = None\"}, {\"name\": \"max_length\", \"val\": \": int | None = None\"}, {\"name\": \"stride\", \"val\": \": int = 0\"}, {\"name\": \"is_split_into_words\", \"val\": \": bool = False\"}, {\"name\": \"pad_to_multiple_of\", \"val\": \": int | None = None\"}, {\"name\": \"padding_side\", \"val\": \": str | None = None\"}, {\"name\": \"return_tensors\", \"val\": \": str | TensorType | None = None\"}, {\"name\": \"return_token_type_ids\", \"val\": \": bool | None = None\"}, {\"name\": \"return_attention_mask\", \"val\": \": bool | None = None\"}, {\"name\": \"return_overflowing_tokens\", \"val\": \": bool = False\"}, {\"name\": \"return_special_tokens_mask\", \"val\": \": bool = False\"}, {\"name\": \"return_offsets_mapping\", \"val\": \": bool = False\"}, {\"name\": \"return_length\", \"val\": \": bool = False\"}, {\"name\": \"verbose\", \"val\": \": bool = True\"}, {\"name\": \"tokenizer_kwargs\", \"val\": \": dict[str, Any] | None = None\"}, {\"name\": \"**kwargs\", \"val\": \"\"}]- **text** (`str`, `list[str]`, `list[list[str]]`, *optional*) --\n The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings\n (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set\n `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).\n- **text_pair** (`str`, `list[str]`, `list[list[str]]`, *optional*) --\n The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings\n (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set\n `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).\n- **text_target** (`str`, `list[str]`, `list[list[str]]`, *optional*) --\n The sequence or batch of sequences to be encoded as target texts. Each sequence can be a string or a\n list of strings (pretokenized string). If the sequences are provided as list of strings (pretokenized),\n you must set `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).\n- **text_pair_target** (`str`, `list[str]`, `list[list[str]]`, *optional*) --\n The sequence or batch of sequences to be encoded as target texts. Each sequence can be a string or a\n list of strings (pretokenized string). If the sequences are provided as list of strings (pretokenized),\n you must set `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).\n- **tokenizer_kwargs** (`dict[str, Any]`, *optional*) --\n Additional kwargs to pass to the tokenizer. These will be merged with the explicit parameters and\n other kwargs, with explicit parameters taking precedence.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 50592, "char_end": 53992, "token_estimate": 850, "prev_chunk_id": 591, "next_chunk_id": 593, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 593, "text": "- **add_special_tokens** (`bool`, *optional*, defaults to `True`) --\n Whether or not to add special tokens when encoding the sequences. This will use the underlying\n `PretrainedTokenizerBase.build_inputs_with_special_tokens` function, which defines which tokens are\n automatically added to the input ids. This is useful if you want to add `bos` or `eos` tokens\n automatically.\n- **padding** (`bool`, `str` or [PaddingStrategy](/docs/transformers/v5.6.2/en/internal/file_utils#transformers.utils.PaddingStrategy), *optional*, defaults to `False`) --\n Activates and controls padding. Accepts the following values:", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 9348, "char_end": 9964, "token_estimate": 154, "prev_chunk_id": 592, "next_chunk_id": 594, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 594, "text": "- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single\n sequence is provided).\n - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n- **truncation** (`bool`, `str` or [TruncationStrategy](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.tokenization_utils_base.TruncationStrategy), *optional*, defaults to `False`) --\n Activates and controls truncation. Accepts the following values:", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 9968, "char_end": 10665, "token_estimate": 174, "prev_chunk_id": 593, "next_chunk_id": 595, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 595, "text": "- `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or\n to the maximum acceptable input length for the model if that argument is not provided. This will\n truncate token by token, removing a token from the longest sequence in the pair if a pair of\n sequences (or a batch of pairs) is provided.\n - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the\n maximum acceptable input length for the model if that argument is not provided. This will only\n truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the\n maximum acceptable input length for the model if that argument is not provided. This will only\n truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n- **max_length** (`int`, *optional*) --\n Controls the maximum length to use by one of the truncation/padding parameters.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 10669, "char_end": 11906, "token_estimate": 309, "prev_chunk_id": 594, "next_chunk_id": 596, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 596, "text": "If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n- **stride** (`int`, *optional*, defaults to 0) --\n If set to a number along with `max_length`, the overflowing tokens returned when\n `return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence\n returned to provide some overlap between truncated and overflowing sequences. The value of this\n argument defines the number of overlapping tokens.\n- **is_split_into_words** (`bool`, *optional*, defaults to `False`) --\n Whether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the\n tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace)\n which it will tokenize. This is useful for NER or token classification.\n- **pad_to_multiple_of** (`int`, *optional*) --\n If set will pad the sequence to a multiple of the provided value. Requires `padding` to be activated.\n This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability\n `>= 7.5` (Volta).\n- **padding_side** (`str`, *optional*) --\n The side on which the model should have padding applied. Should be selected between ['right', 'left'].\n Default value is picked from the class attribute of the same name.\n- **return_tensors** (`str` or [TensorType](/docs/transformers/v5.6.2/en/internal/file_utils#transformers.TensorType), *optional*) --\n If set, will return tensors instead of list of python integers. Acceptable values are:", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 11910, "char_end": 13644, "token_estimate": 434, "prev_chunk_id": 595, "next_chunk_id": 597, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 597, "text": "- `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return Numpy `np.ndarray` objects.\n\n- **return_token_type_ids** (`bool`, *optional*) --\n Whether to return token type IDs. If left to the default, will return the token type IDs according to\n the specific tokenizer's default, defined by the `return_outputs` attribute.\n\n [What are token type IDs?](../glossary#token-type-ids)\n- **return_attention_mask** (`bool`, *optional*) --\n Whether to return the attention mask. If left to the default, will return the attention mask according\n to the specific tokenizer's default, defined by the `return_outputs` attribute.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 13648, "char_end": 14276, "token_estimate": 157, "prev_chunk_id": 596, "next_chunk_id": 598, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 598, "text": "[What are attention masks?](../glossary#attention-mask)\n- **return_overflowing_tokens** (`bool`, *optional*, defaults to `False`) --\n Whether or not to return overflowing token sequences. If a pair of sequences of input ids (or a batch\n of pairs) is provided with `truncation_strategy = longest_first` or `True`, an error is raised instead\n of returning overflowing tokens.\n- **return_special_tokens_mask** (`bool`, *optional*, defaults to `False`) --\n Whether or not to return special tokens mask information.\n- **return_offsets_mapping** (`bool`, *optional*, defaults to `False`) --\n Whether or not to return `(char_start, char_end)` for each token.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 14280, "char_end": 14936, "token_estimate": 164, "prev_chunk_id": 597, "next_chunk_id": 599, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 599, "text": "This is only available on fast tokenizers inheriting from [PreTrainedTokenizerFast](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.TokenizersBackend), if using\n Python's tokenizer, this method will raise `NotImplementedError`.\n- **return_length** (`bool`, *optional*, defaults to `False`) --\n Whether or not to return the lengths of the encoded inputs.\n- **verbose** (`bool`, *optional*, defaults to `True`) --\n Whether or not to print more information and warnings.\n- ****kwargs** -- passed to the `self.tokenize()` method0[BatchEncoding](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.BatchEncoding)A [BatchEncoding](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.BatchEncoding) with the following fields:\n\n- **input_ids** -- List of token ids to be fed to a model.\n\n [What are input IDs?](../glossary#input-ids)", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 14940, "char_end": 15813, "token_estimate": 218, "prev_chunk_id": 598, "next_chunk_id": 600, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 600, "text": "- **token_type_ids** -- List of token type ids to be fed to a model (when `return_token_type_ids=True` or\n if *\"token_type_ids\"* is in `self.model_input_names`).\n\n [What are token type IDs?](../glossary#token-type-ids)\n\n- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when\n `return_attention_mask=True` or if *\"attention_mask\"* is in `self.model_input_names`).\n\n [What are attention masks?](../glossary#attention-mask)\n\n- **overflowing_tokens** -- List of overflowing tokens sequences (when a `max_length` is specified and\n `return_overflowing_tokens=True`).\n- **num_truncated_tokens** -- Number of tokens truncated (when a `max_length` is specified and\n `return_overflowing_tokens=True`).\n- **special_tokens_mask** -- List of 0s and 1s, with 1 specifying added special tokens and 0 specifying\n regular sequence tokens (when `add_special_tokens=True` and `return_special_tokens_mask=True`).\n- **length** -- The length of the inputs (when `return_length=True`)", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 15815, "char_end": 16833, "token_estimate": 254, "prev_chunk_id": 599, "next_chunk_id": 601, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 601, "text": "Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of\nsequences.\n\n**Parameters:**\n\nmodel_max_length (`int`, *optional*) : The maximum length (in number of tokens) for the inputs to the transformer model. When the tokenizer is loaded with [from_pretrained()](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.from_pretrained), this will be set to the value stored for the associated model in `max_model_input_sizes` (see above). If no value is provided, will default to VERY_LARGE_INTEGER (`int(1e30)`).\n\npadding_side (`str`, *optional*) : The side on which the model should have padding applied. Should be selected between ['right', 'left']. Default value is picked from the class attribute of the same name.\n\ntruncation_side (`str`, *optional*) : The side on which the model should have truncation applied. Should be selected between ['right', 'left']. Default value is picked from the class attribute of the same name.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 16835, "char_end": 17851, "token_estimate": 254, "prev_chunk_id": 600, "next_chunk_id": 602, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 602, "text": "chat_template (`str`, *optional*) : A Jinja template string that will be used to format lists of chat messages. See https://huggingface.co/docs/transformers/chat_templating for a full description.\n\nmodel_input_names (`list[string]`, *optional*) : The list of inputs accepted by the forward pass of the model (like `\"token_type_ids\"` or `\"attention_mask\"`). Default value is picked from the class attribute of the same name.\n\nbos_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing the beginning of a sentence.\n\neos_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing the end of a sentence.\n\nunk_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing an out-of-vocabulary token.\n\nsep_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token separating two different sentences in the same input (used by BERT for instance).", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 17853, "char_end": 18781, "token_estimate": 232, "prev_chunk_id": 601, "next_chunk_id": 603, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 603, "text": "pad_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by attention mechanisms or loss computation.\n\ncls_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing the class of the input (used by BERT for instance).\n\nmask_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing a masked token (used by masked-language modeling pretraining objectives, like BERT). Will be associated to `self.mask_token` and `self.mask_token_id`.\n\nextra_special_tokens (list of `str` or `tokenizers.AddedToken`, *optional*) : A list of extra model-specific special tokens. Add them here to ensure they are skipped when decoding with `skip_special_tokens` is set to True. If they are not part of the vocabulary, they will be added at the end of the vocabulary.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 18783, "char_end": 19684, "token_estimate": 225, "prev_chunk_id": 602, "next_chunk_id": 604, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 604, "text": "split_special_tokens (`bool`, *optional*, defaults to `False`) : Whether or not the special tokens should be split during the tokenization process. Passing will affect the internal state of the tokenizer. The default behavior is to not split special tokens. This means that if `` is the `bos_token`, then `tokenizer.tokenize(\"\") = ['`]. Otherwise, if `split_special_tokens=True`, then `tokenizer.tokenize(\"\")` will be give `['']`. \n\ntokenizer_object (`tokenizers.Tokenizer`) : A `tokenizers.Tokenizer` object from \ud83e\udd17 tokenizers to instantiate from. See [Using tokenizers from \ud83e\udd17 tokenizers](../fast_tokenizers) for more information.\n\ntokenizer_file (`str`) : A path to a local JSON file representing a previously serialized `tokenizers.Tokenizer` object from \ud83e\udd17 tokenizers.\n\n**Returns:**\n\n`[BatchEncoding](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.BatchEncoding)`\n\nA [BatchEncoding](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.BatchEncoding) with the following fields:", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 64332, "char_end": 65341, "token_estimate": 252, "prev_chunk_id": 603, "next_chunk_id": 605, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 605, "text": "- **input_ids** -- List of token ids to be fed to a model.\n\n [What are input IDs?](../glossary#input-ids)\n\n- **token_type_ids** -- List of token type ids to be fed to a model (when `return_token_type_ids=True` or\n if *\"token_type_ids\"* is in `self.model_input_names`).\n\n [What are token type IDs?](../glossary#token-type-ids)\n\n- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when\n `return_attention_mask=True` or if *\"attention_mask\"* is in `self.model_input_names`).\n\n [What are attention masks?](../glossary#attention-mask)", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 15707, "char_end": 16289, "token_estimate": 145, "prev_chunk_id": 604, "next_chunk_id": 606, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 606, "text": "- **overflowing_tokens** -- List of overflowing tokens sequences (when a `max_length` is specified and\n `return_overflowing_tokens=True`).\n- **num_truncated_tokens** -- Number of tokens truncated (when a `max_length` is specified and\n `return_overflowing_tokens=True`).\n- **special_tokens_mask** -- List of 0s and 1s, with 1 specifying added special tokens and 0 specifying\n regular sequence tokens (when `add_special_tokens=True` and `return_special_tokens_mask=True`).\n- **length** -- The length of the inputs (when `return_length=True`)", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 16291, "char_end": 16833, "token_estimate": 135, "prev_chunk_id": 605, "next_chunk_id": 607, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 607, "text": "#### add_tokens[[transformers.TokenizersBackend.add_tokens]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L1213)\n\n#TODO remove this from here! PreTrainedTOkeniuzerBase should be agnostic of AddedToken.\n\nAdd a list of new tokens. If the new tokens are not in the vocabulary, they are added to the end. Added tokens and\ntokens from the vocabulary of the tokenization algorithm are therefore not treated in the same way.\n\nExamples:\n\n```python", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "add_tokens[[transformers.TokenizersBackend.add_tokens]]", "char_start": 66470, "char_end": 66974, "token_estimate": 126, "prev_chunk_id": 606, "next_chunk_id": 608, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 608, "text": "# Let's see how to increase the vocabulary of Bert model and tokenizer\ntokenizer = BertTokenizerFast.from_pretrained(\"google-bert/bert-base-uncased\")\nmodel = BertModel.from_pretrained(\"google-bert/bert-base-uncased\")\n\nnum_added_toks = tokenizer.add_tokens([\"new_tok1\", \"my_new-tok2\"])\nprint(\"We have added\", num_added_toks, \"tokens\")", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Let's see how to increase the vocabulary of Bert model and tokenizer", "char_start": 21985, "char_end": 22318, "token_estimate": 83, "prev_chunk_id": 607, "next_chunk_id": 609, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 609, "text": "# Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e., the length of the tokenizer.\nmodel.resize_token_embeddings(len(tokenizer))\n```\n\n**Parameters:**\n\nnew_tokens (`str`, `tokenizers.AddedToken` or a sequence of *str* or `tokenizers.AddedToken`) : Tokens are only added if they are not already in the vocabulary. `tokenizers.AddedToken` wraps a string token to let you personalize its behavior: whether this token should only match against a single word, whether this token should strip all potential whitespaces on the left side, whether this token should strip all potential whitespaces on the right side, etc.\n\nspecial_tokens (`bool`, *optional*, defaults to `False`) : Specifies if the token is special. This mostly changes the normalization behavior See details for `tokenizers.AddedToken` in HuggingFace tokenizers library.\n\n**Returns:**\n\n``int``\n\nNumber of tokens added to the vocabulary.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e., the length of the tokenizer.", "char_start": 22319, "char_end": 23254, "token_estimate": 233, "prev_chunk_id": 608, "next_chunk_id": 610, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 610, "text": "#### add_special_tokens[[transformers.TokenizersBackend.add_special_tokens]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L1106)\n\nAdd a dictionary of special tokens (eos, pad, cls, etc.) to the encoder and link them to class attributes. If\nspecial tokens are NOT in the vocabulary, they are added to it (indexed starting from the last index of the\ncurrent vocabulary).\n\nWhen adding new tokens to the vocabulary, you should make sure to also resize the token embedding matrix of the\nmodel so that its embedding matrix matches the tokenizer.\n\nIn order to do that, please use the [resize_token_embeddings()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel.resize_token_embeddings) method.\n\nUsing `add_special_tokens` will ensure your special tokens can be used in several ways:", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "add_special_tokens[[transformers.TokenizersBackend.add_special_tokens]]", "char_start": 68245, "char_end": 69113, "token_estimate": 217, "prev_chunk_id": 609, "next_chunk_id": 611, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 611, "text": "- Special tokens can be skipped when decoding using `skip_special_tokens = True`.\n- Special tokens are carefully handled by the tokenizer (they are never split), similar to `AddedTokens`.\n- You can easily refer to special tokens using tokenizer class attributes like `tokenizer.cls_token`. This\n makes it easy to develop model-agnostic training and fine-tuning scripts.\n\nWhen possible, special tokens are already registered for provided pretrained models (for instance\n[BertTokenizer](/docs/transformers/v5.6.2/en/model_doc/squeezebert#transformers.BertTokenizer) `cls_token` is already registered to be `'[CLS]'` and XLM's one is also registered to be\n`''`).\n\nExamples:\n\n```python", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "add_special_tokens[[transformers.TokenizersBackend.add_special_tokens]]", "char_start": 24121, "char_end": 24803, "token_estimate": 170, "prev_chunk_id": 610, "next_chunk_id": 612, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 612, "text": "# Let's see how to add a new classification token to GPT-2\ntokenizer = GPT2Tokenizer.from_pretrained(\"openai-community/gpt2\")\nmodel = GPT2Model.from_pretrained(\"openai-community/gpt2\")\n\nspecial_tokens_dict = {\"cls_token\": \"\"}\n\nnum_added_toks = tokenizer.add_special_tokens(special_tokens_dict)\nprint(\"We have added\", num_added_toks, \"tokens\")", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Let's see how to add a new classification token to GPT-2", "char_start": 24804, "char_end": 25146, "token_estimate": 85, "prev_chunk_id": 611, "next_chunk_id": 613, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 613, "text": "# Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e., the length of the tokenizer.\nmodel.resize_token_embeddings(len(tokenizer))\n\nassert tokenizer.cls_token == \"\"\n```\n\n**Parameters:**\n\nspecial_tokens_dict (dictionary *str* to *str*, `tokenizers.AddedToken`, or `Sequence[Union[str, AddedToken]]`) : Keys should be in the list of predefined special attributes: [`bos_token`, `eos_token`, `unk_token`, `sep_token`, `pad_token`, `cls_token`, `mask_token`, `extra_special_tokens`]. Tokens are only added if they are not already in the vocabulary (tested by checking if the tokenizer assign the index of the `unk_token` to them).", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e., the length of the tokenizer.", "char_start": 25147, "char_end": 25813, "token_estimate": 166, "prev_chunk_id": 612, "next_chunk_id": 614, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 614, "text": "replace_extra_special_tokens (`bool`, *optional*, defaults to `True`) : If `True`, the existing list of extra special tokens will be replaced by the list provided in `special_tokens_dict`. Otherwise, `extra_special_tokens` will be extended. In the former case, the tokens will NOT be removed from the tokenizer's full vocabulary - they are only being flagged as non-special tokens. Remember, this only affects which tokens are skipped during decoding, not the `added_tokens_encoder` and `added_tokens_decoder`. This means that the previous `extra_special_tokens` are still added tokens, and will not be split by the model.\n\n**Returns:**\n\n``int``\n\nNumber of tokens added to the vocabulary.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e., the length of the tokenizer.", "char_start": 25815, "char_end": 26503, "token_estimate": 172, "prev_chunk_id": 613, "next_chunk_id": 615, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 615, "text": "#### apply_chat_template[[transformers.TokenizersBackend.apply_chat_template]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L2968)\n\nConverts a list of dictionaries with `\"role\"` and `\"content\"` keys to a list of token\nids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to\ndetermine the format and control tokens to use when converting.\n\n**Parameters:**\n\nconversation (Union[list[dict[str, str]], list[list[dict[str, str]]]]) : A list of dicts with \"role\" and \"content\" keys, representing the chat history so far.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "apply_chat_template[[transformers.TokenizersBackend.apply_chat_template]]", "char_start": 71498, "char_end": 72133, "token_estimate": 158, "prev_chunk_id": 614, "next_chunk_id": 616, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 616, "text": "tools (`list[Union[Dict, Callable]]`, *optional*) : A list of tools (callable functions) that will be accessible to the model. If the template does not support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema, giving the name, description and argument types for the tool. See our [tool use guide](https://huggingface.co/docs/transformers/en/chat_extras#passing-tools) for more information.\n\ndocuments (`list[dict[str, str]]`, *optional*) : A list of dicts representing documents that will be accessible to the model if it is performing RAG (retrieval-augmented generation). If the template does not support RAG, this argument will have no effect. We recommend that each document should be a dict containing \"title\" and \"text\" keys.\n\nchat_template (`str`, *optional*) : A Jinja template to use for this conversion. It is usually not necessary to pass anything to this argument, as the model's template will be used by default.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "apply_chat_template[[transformers.TokenizersBackend.apply_chat_template]]", "char_start": 27137, "char_end": 28110, "token_estimate": 243, "prev_chunk_id": 615, "next_chunk_id": 617, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 617, "text": "add_generation_prompt (bool, *optional*) : If this is set, a prompt with the token(s) that indicate the start of an assistant message will be appended to the formatted output. This is useful when you want to generate a response from the model. Note that this argument will be passed to the chat template, and so it must be supported in the template for this argument to have any effect.\n\ncontinue_final_message (bool, *optional*) : If this is set, the chat will be formatted so that the final message in the chat is open-ended, without any EOS tokens. The model will continue this message rather than starting a new one. This allows you to \"prefill\" part of the model's response for it. Cannot be used at the same time as `add_generation_prompt`.\n\ntokenize (`bool`, defaults to `True`) : Whether to tokenize the output. If `False`, the output will be a string.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "apply_chat_template[[transformers.TokenizersBackend.apply_chat_template]]", "char_start": 28112, "char_end": 28972, "token_estimate": 215, "prev_chunk_id": 616, "next_chunk_id": 618, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 618, "text": "padding (`bool`, `str` or [PaddingStrategy](/docs/transformers/v5.6.2/en/internal/file_utils#transformers.utils.PaddingStrategy), *optional*, defaults to `False`) : Select a strategy to pad the returned sequences (according to the model's padding side and padding index) among: - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths).\n\ntruncation (`bool`, defaults to `False`) : Whether to truncate sequences at the maximum length. Has no effect if tokenize is `False`.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "apply_chat_template[[transformers.TokenizersBackend.apply_chat_template]]", "char_start": 28974, "char_end": 29795, "token_estimate": 205, "prev_chunk_id": 617, "next_chunk_id": 619, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 619, "text": "max_length (`int`, *optional*) : Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is `False`. If not specified, the tokenizer's `max_length` attribute will be used as a default.\n\nreturn_tensors (`str` or [TensorType](/docs/transformers/v5.6.2/en/internal/file_utils#transformers.TensorType), *optional*) : If set, will return tensors of a particular framework. Has no effect if tokenize is `False`. Acceptable values are: - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return NumPy `np.ndarray` objects.\n\nreturn_dict (`bool`, defaults to `True`) : Whether to return a dictionary with named outputs. Has no effect if tokenize is `False`.\n\ntokenizer_kwargs (`dict[str : Any]`, *optional*): Additional kwargs to pass to the tokenizer.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "apply_chat_template[[transformers.TokenizersBackend.apply_chat_template]]", "char_start": 29797, "char_end": 30578, "token_estimate": 195, "prev_chunk_id": 618, "next_chunk_id": 620, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 620, "text": "return_assistant_tokens_mask (`bool`, defaults to `False`) : Whether to return a mask of the assistant generated tokens. For tokens generated by the assistant, the mask will contain 1. For user and system tokens, the mask will contain 0. This functionality is only available for chat templates that support it via the `{% generation %}` keyword.\n\n- ****kwargs** : Additional kwargs to pass to the template renderer. Will be accessible by the chat template.\n\n**Returns:**\n\n``Union[list[int], Dict]``\n\nA list of token ids representing the tokenized chat so far, including control tokens. This\noutput is ready to pass to the model, either directly or via methods like `generate()`. If `return_dict` is\nset, will return a dict of tokenizer outputs instead.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "apply_chat_template[[transformers.TokenizersBackend.apply_chat_template]]", "char_start": 30580, "char_end": 31332, "token_estimate": 188, "prev_chunk_id": 619, "next_chunk_id": 621, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 621, "text": "#### batch_decode[[transformers.TokenizersBackend.batch_decode]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L2880)\n\nConvert a list of lists of token ids into a list of strings by calling decode.\n\nThis method is provided for backwards compatibility. The `decode` method now handles batched input natively,\nso you can use `decode` directly instead of `batch_decode`.\n\n**Parameters:**\n\nsequences (`Union[list[int], list[list[int]], np.ndarray, torch.Tensor]`) : List of tokenized input ids. Can be obtained using the `__call__` method.\n\nskip_special_tokens (`bool`, *optional*, defaults to `False`) : Whether or not to remove special tokens in the decoding.\n\nclean_up_tokenization_spaces (`bool`, *optional*) : Whether or not to clean up the tokenization spaces. If `None`, will default to `self.clean_up_tokenization_spaces`.\n\nkwargs (additional keyword arguments, *optional*) : Will be passed to the underlying model specific decode method.\n\n**Returns:**", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "batch_decode[[transformers.TokenizersBackend.batch_decode]]", "char_start": 76331, "char_end": 77351, "token_estimate": 255, "prev_chunk_id": 620, "next_chunk_id": 622, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 622, "text": "``list[str]``\n\nThe list of decoded sentences.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "batch_decode[[transformers.TokenizersBackend.batch_decode]]", "char_start": 32351, "char_end": 32396, "token_estimate": 11, "prev_chunk_id": 621, "next_chunk_id": 623, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 623, "text": "#### decode[[transformers.TokenizersBackend.decode]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L2832)\n\nConverts a sequence of ids into a string, or a list of sequences into a list of strings,\nusing the tokenizer and vocabulary with options to remove special tokens and clean up\ntokenization spaces.\n\nSimilar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.\n\n**Parameters:**\n\ntoken_ids (`Union[int, list[int], list[list[int]], np.ndarray, torch.Tensor]`) : A single sequence or a batch (list of sequences) of tokenized input ids. Can be obtained using the `__call__` method.\n\nskip_special_tokens (`bool`, *optional*, defaults to `False`) : Whether or not to remove special tokens in the decoding.\n\nkwargs (additional keyword arguments, *optional*) : Will be passed to the underlying model specific decode method.\n\n**Returns:**\n\n``Union[str, list[str]]``", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "decode[[transformers.TokenizersBackend.decode]]", "char_start": 77399, "char_end": 78351, "token_estimate": 238, "prev_chunk_id": 622, "next_chunk_id": 624, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 624, "text": "The decoded string for a single sequence, or a list of decoded strings for a\nbatch of sequences.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "decode[[transformers.TokenizersBackend.decode]]", "char_start": 33347, "char_end": 33443, "token_estimate": 24, "prev_chunk_id": 623, "next_chunk_id": 625, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 625, "text": "#### encode[[transformers.TokenizersBackend.encode]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L2229)\n\nConverts a string to a sequence of ids (integer), using the tokenizer and vocabulary.\n\nSame as doing `self.convert_tokens_to_ids(self.tokenize(text))`.\n\n**Parameters:**\n\ntext (`str`, `list[str]` or `list[int]`) : The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids` method).\n\ntext_pair (`str`, `list[str]` or `list[int]`, *optional*) : Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids` method).", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "encode[[transformers.TokenizersBackend.encode]]", "char_start": 78450, "char_end": 79316, "token_estimate": 216, "prev_chunk_id": 624, "next_chunk_id": 626, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 626, "text": "add_special_tokens (`bool`, *optional*, defaults to `True`) : Whether or not to add special tokens when encoding the sequences. This will use the underlying `PretrainedTokenizerBase.build_inputs_with_special_tokens` function, which defines which tokens are automatically added to the input ids. This is useful if you want to add `bos` or `eos` tokens automatically.\n\npadding (`bool`, `str` or [PaddingStrategy](/docs/transformers/v5.6.2/en/internal/file_utils#transformers.utils.PaddingStrategy), *optional*, defaults to `False`) : Activates and controls padding. Accepts the following values: - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence is provided). - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths).", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "encode[[transformers.TokenizersBackend.encode]]", "char_start": 34309, "char_end": 35311, "token_estimate": 250, "prev_chunk_id": 625, "next_chunk_id": 627, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 627, "text": "truncation (`bool`, `str` or [TruncationStrategy](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.tokenization_utils_base.TruncationStrategy), *optional*, defaults to `False`) : Activates and controls truncation. Accepts the following values: - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size).", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "encode[[transformers.TokenizersBackend.encode]]", "char_start": 35313, "char_end": 36656, "token_estimate": 335, "prev_chunk_id": 626, "next_chunk_id": 628, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 628, "text": "max_length (`int`, *optional*) : Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated.\n\nstride (`int`, *optional*, defaults to 0) : If set to a number along with `max_length`, the overflowing tokens returned when `return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence returned to provide some overlap between truncated and overflowing sequences. The value of this argument defines the number of overlapping tokens.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "encode[[transformers.TokenizersBackend.encode]]", "char_start": 36658, "char_end": 37423, "token_estimate": 191, "prev_chunk_id": 627, "next_chunk_id": 629, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 629, "text": "is_split_into_words (`bool`, *optional*, defaults to `False`) : Whether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace) which it will tokenize. This is useful for NER or token classification.\n\npad_to_multiple_of (`int`, *optional*) : If set will pad the sequence to a multiple of the provided value. Requires `padding` to be activated. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).\n\npadding_side (`str`, *optional*) : The side on which the model should have padding applied. Should be selected between ['right', 'left']. Default value is picked from the class attribute of the same name.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "encode[[transformers.TokenizersBackend.encode]]", "char_start": 37425, "char_end": 38231, "token_estimate": 201, "prev_chunk_id": 628, "next_chunk_id": 630, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 630, "text": "return_tensors (`str` or [TensorType](/docs/transformers/v5.6.2/en/internal/file_utils#transformers.TensorType), *optional*) : If set, will return tensors instead of list of python integers. Acceptable values are: - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return Numpy `np.ndarray` objects. \n\n- ****kwargs** : Passed along to the `.tokenize()` method.\n\n**Returns:**\n\n``list[int]`, `torch.Tensor`, or `np.ndarray``\n\nThe tokenized ids of the text.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "encode[[transformers.TokenizersBackend.encode]]", "char_start": 38233, "char_end": 38696, "token_estimate": 115, "prev_chunk_id": 629, "next_chunk_id": 631, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 631, "text": "#### push_to_hub[[transformers.TokenizersBackend.push_to_hub]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/utils/hub.py#L720)\n\nUpload the tokenizer files to the \ud83e\udd17 Model Hub.\n\nExamples:\n\n```python\nfrom transformers import AutoTokenizer\n\ntokenizer = AutoTokenizer.from_pretrained(\"google-bert/bert-base-cased\")", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "push_to_hub[[transformers.TokenizersBackend.push_to_hub]]", "char_start": 83707, "char_end": 84054, "token_estimate": 86, "prev_chunk_id": 630, "next_chunk_id": 632, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 632, "text": "# Push the tokenizer to your namespace with the name \"my-finetuned-bert\".\ntokenizer.push_to_hub(\"my-finetuned-bert\")", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Push the tokenizer to your namespace with the name \"my-finetuned-bert\".", "char_start": 39042, "char_end": 39158, "token_estimate": 29, "prev_chunk_id": 631, "next_chunk_id": 633, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 633, "text": "# Push the tokenizer to an organization with the name \"my-finetuned-bert\".\ntokenizer.push_to_hub(\"huggingface/my-finetuned-bert\")\n```\n\n**Parameters:**\n\nrepo_id (`str`) : The name of the repository you want to push your tokenizer to. It should contain your organization name when pushing to a given organization.\n\ncommit_message (`str`, *optional*) : Message to commit while pushing. Will default to `\"Upload tokenizer\"`.\n\ncommit_description (`str`, *optional*) : The description of the commit that will be created\n\nprivate (`bool`, *optional*) : Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.\n\ntoken (`bool` or `str`, *optional*) : The token to use as HTTP bearer authorization for remote files. If `True` (default), will use the token generated when running `hf auth login` (stored in `~/.huggingface`).\n\nrevision (`str`, *optional*) : Branch to push the uploaded files to.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Push the tokenizer to an organization with the name \"my-finetuned-bert\".", "char_start": 39160, "char_end": 40162, "token_estimate": 250, "prev_chunk_id": 632, "next_chunk_id": 634, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 634, "text": "create_pr (`bool`, *optional*, defaults to `False`) : Whether or not to create a PR with the uploaded files or directly commit.\n\nmax_shard_size (`int` or `str`, *optional*, defaults to `\"50GB\"`) : Only applicable for models. The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size lower than this size. If expressed as a string, needs to be digits followed by a unit (like `\"5MB\"`).\n\ntags (`list[str]`, *optional*) : List of tags to push on the Hub.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Push the tokenizer to an organization with the name \"my-finetuned-bert\".", "char_start": 40164, "char_end": 40657, "token_estimate": 123, "prev_chunk_id": 633, "next_chunk_id": 635, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 635, "text": "#### convert_to_native_format[[transformers.TokenizersBackend.convert_to_native_format]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_tokenizers.py#L101)\n\nBuild a `tokenizers.Tokenizer` backend from the available serialization files (tokenizer.json, sentencepiece\nmodels, tekken.json, vocab/merges).", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "convert_to_native_format[[transformers.TokenizersBackend.convert_to_native_format]]", "char_start": 85672, "char_end": 86028, "token_estimate": 89, "prev_chunk_id": 634, "next_chunk_id": 636, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 636, "text": "#### get_added_vocab[[transformers.TokenizersBackend.get_added_vocab]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_tokenizers.py#L635)\n\nReturns the added tokens in the vocabulary as a dictionary of token to index.\n\n**Returns:**\n\n``dict[str, int]``\n\nThe added tokens.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "get_added_vocab[[transformers.TokenizersBackend.get_added_vocab]]", "char_start": 86029, "char_end": 86353, "token_estimate": 81, "prev_chunk_id": 635, "next_chunk_id": 637, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 637, "text": "#### num_special_tokens_to_add[[transformers.TokenizersBackend.num_special_tokens_to_add]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_tokenizers.py#L732)\n\nReturns the number of added tokens when encoding a sequence with special tokens.\n\nThis encodes a dummy input and checks the number of added tokens, and is therefore not efficient. Do not put\nthis inside your training loop.\n\n**Parameters:**\n\npair (`bool`, *optional*, defaults to `False`) : Whether the number of added tokens should be computed in the case of a sequence pair or a single sequence.\n\n**Returns:**\n\n``int``\n\nNumber of special tokens added to sequences.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "num_special_tokens_to_add[[transformers.TokenizersBackend.num_special_tokens_to_add]]", "char_start": 86354, "char_end": 87033, "token_estimate": 169, "prev_chunk_id": 636, "next_chunk_id": 638, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 638, "text": "#### set_truncation_and_padding[[transformers.TokenizersBackend.set_truncation_and_padding]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_tokenizers.py#L782)\n\nDefine the truncation and the padding strategies for fast tokenizers (provided by HuggingFace tokenizers\nlibrary) and restore the tokenizer settings afterwards.\n\nThe provided tokenizer has no padding / truncation strategy before the managed section. If your tokenizer set a\npadding / truncation strategy before, then it will be reset to no padding / truncation when exiting the managed\nsection.\n\n**Parameters:**\n\npadding_strategy ([PaddingStrategy](/docs/transformers/v5.6.2/en/internal/file_utils#transformers.utils.PaddingStrategy)) : The kind of padding that will be applied to the input\n\ntruncation_strategy ([TruncationStrategy](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.tokenization_utils_base.TruncationStrategy)) : The kind of truncation that will be applied to the input", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "set_truncation_and_padding[[transformers.TokenizersBackend.set_truncation_and_padding]]", "char_start": 87034, "char_end": 88057, "token_estimate": 255, "prev_chunk_id": 637, "next_chunk_id": 639, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 639, "text": "max_length (`int`) : The maximum size of a sequence.\n\nstride (`int`) : The stride to use when handling overflow.\n\npad_to_multiple_of (`int`, *optional*) : If set will pad the sequence to a multiple of the provided value. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).\n\npadding_side (`str`, *optional*) : The side on which the model should have padding applied. Should be selected between ['right', 'left']. Default value is picked from the class attribute of the same name.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "set_truncation_and_padding[[transformers.TokenizersBackend.set_truncation_and_padding]]", "char_start": 88059, "char_end": 88606, "token_estimate": 136, "prev_chunk_id": 638, "next_chunk_id": 640, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 640, "text": "#### train_new_from_iterator[[transformers.TokenizersBackend.train_new_from_iterator]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_tokenizers.py#L1061)\n\nTrains a tokenizer on a new corpus with the same defaults (in terms of special tokens or tokenization pipeline)\nas the current one.\n\n**Parameters:**\n\ntext_iterator (generator of `list[str]`) : The training corpus. Should be a generator of batches of texts, for instance a list of lists of texts if you have everything in memory.\n\nvocab_size (`int`) : The size of the vocabulary you want for your tokenizer.\n\nlength (`int`, *optional*) : The total number of sequences in the iterator. This is used to provide meaningful progress tracking\n\nnew_special_tokens (list of `str` or `AddedToken`, *optional*) : A list of new special tokens to add to the tokenizer you are training.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "train_new_from_iterator[[transformers.TokenizersBackend.train_new_from_iterator]]", "char_start": 88607, "char_end": 89491, "token_estimate": 221, "prev_chunk_id": 639, "next_chunk_id": 641, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 641, "text": "special_tokens_map (`dict[str, str]`, *optional*) : If you want to rename some of the special tokens this tokenizer uses, pass along a mapping old special token name to new special token name in this argument.\n\nkwargs (`dict[str, Any]`, *optional*) : Additional keyword arguments passed along to the trainer from the \ud83e\udd17 Tokenizers library.\n\n**Returns:**\n\n`[PreTrainedTokenizerFast](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.TokenizersBackend)`\n\nA new tokenizer of the same type as the original one, trained on\n`text_iterator`.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "train_new_from_iterator[[transformers.TokenizersBackend.train_new_from_iterator]]", "char_start": 89493, "char_end": 90041, "token_estimate": 137, "prev_chunk_id": 640, "next_chunk_id": 642, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 642, "text": "#### update_post_processor[[transformers.TokenizersBackend.update_post_processor]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_tokenizers.py#L522)\n\nUpdates the underlying post processor with the current `bos_token` and `eos_token`.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "update_post_processor[[transformers.TokenizersBackend.update_post_processor]]", "char_start": 90042, "char_end": 90331, "token_estimate": 72, "prev_chunk_id": 641, "next_chunk_id": 643, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 643, "text": "## PythonBackend[[transformers.PythonBackend]]", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "PythonBackend[[transformers.PythonBackend]]", "char_start": 90333, "char_end": 90379, "token_estimate": 11, "prev_chunk_id": 642, "next_chunk_id": 644, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 644, "text": "#### transformers.PythonBackend[[transformers.PythonBackend]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_python.py#L400)\n\nBase class for all slow tokenizers.\n\nInherits from [PreTrainedTokenizerBase](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase).\n\nHandle all the shared methods for tokenization and special tokens as well as methods downloading/caching/loading\npretrained tokenizers as well as adding tokens to the vocabulary.\n\nThis class also contain the added tokens in a unified way on top of all tokenizers so we don't have to handle the\nspecific vocabulary augmentation methods of the various underlying dictionary structures (BPE, sentencepiece...).\n\nClass attributes (overridden by derived classes)", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 4154, "char_end": 4960, "token_estimate": 201, "prev_chunk_id": 643, "next_chunk_id": 645, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 645, "text": "- **vocab_files_names** (`dict[str, str]`) -- A dictionary with, as keys, the `__init__` keyword name of each\n vocabulary file required by the model, and as associated values, the filename for saving the associated file\n (string).\n- **pretrained_vocab_files_map** (`dict[str, dict[str, str]]`) -- A dictionary of dictionaries, with the\n high-level keys being the `__init__` keyword name of each vocabulary file required by the model, the\n low-level being the `short-cut-names` of the pretrained models with, as associated values, the `url` to the\n associated pretrained vocabulary file.\n- **model_input_names** (`list[str]`) -- A list of inputs expected in the forward pass of the model.\n- **padding_side** (`str`) -- The default value for the side on which the model should have padding applied.\n Should be `'right'` or `'left'`.\n- **truncation_side** (`str`) -- The default value for the side on which the model should have truncation\n applied. Should be `'right'` or `'left'`.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 4962, "char_end": 5948, "token_estimate": 246, "prev_chunk_id": 644, "next_chunk_id": 646, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 646, "text": "build_inputs_with_special_tokenstransformers.PythonBackend.build_inputs_with_special_tokenshttps://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_python.py#L860[{\"name\": \"token_ids_0\", \"val\": \": list\"}, {\"name\": \"token_ids_1\", \"val\": \": list[int] | None = None\"}]- **token_ids_0** (`list[int]`) --\n List of IDs to which the special tokens will be added.\n- **token_ids_1** (`list[int]`, *optional*) --\n Optional second list of IDs for sequence pairs.0`list[int]`List of input IDs with the appropriate special tokens.\n\nBuild model inputs from a sequence or a pair of sequences by adding special tokens.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 92177, "char_end": 92810, "token_estimate": 158, "prev_chunk_id": 645, "next_chunk_id": 647, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 647, "text": "This method dynamically builds inputs based on the tokenizer's `special_tokens_pattern`:\n- `\"none\"`: No special tokens\n- `\"cls_sep\"`: [CLS] seq0 [SEP] or [CLS] seq0 [SEP] seq1 [SEP]\n- `\"eos\"`: seq0 [EOS] or seq0 [EOS] seq1 [EOS]\n- `\"bos\"`: [BOS] seq0 or [BOS] seq0 [BOS] seq1\n- `\"bos_eos\"`: [BOS] seq0 [EOS] or [BOS] seq0 [EOS] seq1 [EOS]\n- `\"cls_double_sep\"`: [CLS] seq0 [SEP] or [CLS] seq0 [SEP] [SEP] seq1 [SEP]\n- `\"prefix_suffix\"`: ` seq0 [seq1] ` (custom prefix/suffix stored on the tokenizer)\n\n**Parameters:**\n\nmodel_max_length (`int`, *optional*) : The maximum length (in number of tokens) for the inputs to the transformer model. When the tokenizer is loaded with [from_pretrained()](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.from_pretrained), this will be set to the value stored for the associated model in `max_model_input_sizes` (see above). If no value is provided, will default to VERY_LARGE_INTEGER (`int(1e30)`).", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 92812, "char_end": 93792, "token_estimate": 245, "prev_chunk_id": 646, "next_chunk_id": 648, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 648, "text": "padding_side (`str`, *optional*) : The side on which the model should have padding applied. Should be selected between ['right', 'left']. Default value is picked from the class attribute of the same name.\n\ntruncation_side (`str`, *optional*) : The side on which the model should have truncation applied. Should be selected between ['right', 'left']. Default value is picked from the class attribute of the same name.\n\nchat_template (`str`, *optional*) : A Jinja template string that will be used to format lists of chat messages. See https://huggingface.co/docs/transformers/chat_templating for a full description.\n\nmodel_input_names (`list[string]`, *optional*) : The list of inputs accepted by the forward pass of the model (like `\"token_type_ids\"` or `\"attention_mask\"`). Default value is picked from the class attribute of the same name.\n\nbos_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing the beginning of a sentence.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 17435, "char_end": 18394, "token_estimate": 239, "prev_chunk_id": 647, "next_chunk_id": 649, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 649, "text": "eos_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing the end of a sentence.\n\nunk_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing an out-of-vocabulary token.\n\nsep_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token separating two different sentences in the same input (used by BERT for instance).\n\npad_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by attention mechanisms or loss computation.\n\ncls_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing the class of the input (used by BERT for instance).\n\nmask_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing a masked token (used by masked-language modeling pretraining objectives, like BERT). Will be associated to `self.mask_token` and `self.mask_token_id`.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 18396, "char_end": 19371, "token_estimate": 243, "prev_chunk_id": 648, "next_chunk_id": 650, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 650, "text": "extra_special_tokens (list of `str` or `tokenizers.AddedToken`, *optional*) : A list of extra model-specific special tokens. Add them here to ensure they are skipped when decoding with `skip_special_tokens` is set to True. If they are not part of the vocabulary, they will be added at the end of the vocabulary.\n\nsplit_special_tokens (`bool`, *optional*, defaults to `False`) : Whether or not the special tokens should be split during the tokenization process. Passing will affect the internal state of the tokenizer. The default behavior is to not split special tokens. This means that if `` is the `bos_token`, then `tokenizer.tokenize(\"\") = ['`]. Otherwise, if `split_special_tokens=True`, then `tokenizer.tokenize(\"\")` will be give `['']`.\n\n**Returns:**\n\n``list[int]``\n\nList of input IDs with the appropriate special tokens.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.PythonBackend[[transformers.PythonBackend]]", "char_start": 95732, "char_end": 96560, "token_estimate": 207, "prev_chunk_id": 649, "next_chunk_id": 651, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 651, "text": "#### create_token_type_ids_from_sequences[[transformers.PythonBackend.create_token_type_ids_from_sequences]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_python.py#L1292)\n\nCreate a mask from the two sequences passed to be used in a sequence-pair classification task.\n\nThis method dynamically builds the token type IDs based on the tokenizer's configuration attributes:\n- `token_type_ids_pattern`: Pattern to use (\"all_zeros\" or \"bert_style\")\n- `token_type_ids_include_special_tokens`: Whether to account for special tokens in length calculation\n\nExamples:\n```python", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "create_token_type_ids_from_sequences[[transformers.PythonBackend.create_token_type_ids_from_sequences]]", "char_start": 41731, "char_end": 42347, "token_estimate": 154, "prev_chunk_id": 650, "next_chunk_id": 652, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 652, "text": "# All zeros pattern (default, used by RoBERTa, BART, etc.)\ntokenizer.token_type_ids_pattern = \"all_zeros\"", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "All zeros pattern (default, used by RoBERTa, BART, etc.)", "char_start": 42348, "char_end": 42453, "token_estimate": 26, "prev_chunk_id": 651, "next_chunk_id": 653, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 653, "text": "# Returns: [0, 0, 0, ...] for both sequences", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Returns: [0, 0, 0, ...] for both sequences", "char_start": 42454, "char_end": 42498, "token_estimate": 11, "prev_chunk_id": 652, "next_chunk_id": 654, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 654, "text": "# BERT-style pattern (first sequence gets 0s, second gets 1s)\ntokenizer.token_type_ids_pattern = \"bert_style\"", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "BERT-style pattern (first sequence gets 0s, second gets 1s)", "char_start": 42500, "char_end": 42609, "token_estimate": 27, "prev_chunk_id": 653, "next_chunk_id": 655, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 655, "text": "# Returns: [0, 0, 0, ..., 1, 1, 1, ...] for sequence pairs\n```\n\n**Parameters:**\n\ntoken_ids_0 (`list[int]`) : List of IDs.\n\ntoken_ids_1 (`list[int]`, *optional*) : Optional second list of IDs for sequence pairs.\n\n**Returns:**\n\n``list[int]``\n\nToken type IDs according to the configured pattern.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "Returns: [0, 0, 0, ..., 1, 1, 1, ...] for sequence pairs", "char_start": 42610, "char_end": 42902, "token_estimate": 73, "prev_chunk_id": 654, "next_chunk_id": 656, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 656, "text": "#### get_added_vocab[[transformers.PythonBackend.get_added_vocab]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_python.py#L488)\n\nReturns the added tokens in the vocabulary as a dictionary of token to index. Results might be different from\nthe fast call because for now we always add the tokens even if they are already in the vocabulary. This is\nsomething we should change.\n\n**Returns:**\n\n``dict[str, int]``\n\nThe added tokens.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "get_added_vocab[[transformers.PythonBackend.get_added_vocab]]", "char_start": 42903, "char_end": 43380, "token_estimate": 119, "prev_chunk_id": 655, "next_chunk_id": 657, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 657, "text": "#### get_special_tokens_mask[[transformers.PythonBackend.get_special_tokens_mask]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_python.py#L965)\n\nRetrieves sequence ids from a token list that has no special tokens added. This method is called when adding\nspecial tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.\n\nThis method dynamically builds the special tokens mask based on the tokenizer's `special_tokens_pattern`:\n- `\"none\"`: No special tokens (default, returns all 0s)\n- `\"cls_sep\"`: [CLS] seq0 [SEP] or [CLS] seq0 [SEP] seq1 [SEP]\n- `\"eos\"`: seq0 [EOS] or seq0 [EOS] seq1 [EOS]\n- `\"bos\"`: [BOS] seq0 or [BOS] seq0 [BOS] seq1\n- `\"bos_eos\"`: [BOS] seq0 [EOS] or [BOS] seq0 [EOS] seq1 [EOS]\n- `\"cls_double_sep\"`: [CLS] seq0 [SEP] or [CLS] seq0 [SEP] [SEP] seq1 [SEP]\n- `\"prefix_suffix\"`: ` seq0 [seq1] `\n\n**Parameters:**\n\ntoken_ids_0 (`list[int]`) : List of ids of the first sequence.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "get_special_tokens_mask[[transformers.PythonBackend.get_special_tokens_mask]]", "char_start": 43381, "char_end": 44343, "token_estimate": 240, "prev_chunk_id": 656, "next_chunk_id": 658, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 658, "text": "token_ids_1 (`list[int]`, *optional*) : List of ids of the second sequence.\n\nalready_has_special_tokens (`bool`, *optional*, defaults to `False`) : Whether or not the token list is already formatted with special tokens for the model.\n\n**Returns:**\n\n`A list of integers in the range [0, 1]`\n\n1 for a special token, 0 for a sequence token.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "get_special_tokens_mask[[transformers.PythonBackend.get_special_tokens_mask]]", "char_start": 44345, "char_end": 44682, "token_estimate": 84, "prev_chunk_id": 657, "next_chunk_id": 659, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 659, "text": "#### num_special_tokens_to_add[[transformers.PythonBackend.num_special_tokens_to_add]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_python.py#L602)\n\nReturns the number of added tokens when encoding a sequence with special tokens.\n\nThis encodes a dummy input and checks the number of added tokens, and is therefore not efficient. Do not put\nthis inside your training loop.\n\n**Parameters:**\n\npair (`bool`, *optional*, defaults to `False`) : Whether the number of added tokens should be computed in the case of a sequence pair or a single sequence.\n\n**Returns:**\n\n``int``\n\nNumber of special tokens added to sequences.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "num_special_tokens_to_add[[transformers.PythonBackend.num_special_tokens_to_add]]", "char_start": 44683, "char_end": 45348, "token_estimate": 166, "prev_chunk_id": 658, "next_chunk_id": 660, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 660, "text": "#### prepare_for_model[[transformers.PythonBackend.prepare_for_model]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_python.py#L1115)\n\nPrepares a sequence of input ids so it can be used by the model. Adds special tokens, truncates, and pads.\n\n**Parameters:**\n\nids : Tokenized input ids of the first sequence.\n\npair_ids : Tokenized input ids of the second sequence (optional).", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "prepare_for_model[[transformers.PythonBackend.prepare_for_model]]", "char_start": 45349, "char_end": 45774, "token_estimate": 106, "prev_chunk_id": 659, "next_chunk_id": 661, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 661, "text": "#### prepare_for_tokenization[[transformers.PythonBackend.prepare_for_tokenization]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_python.py#L836)\n\nPerforms any necessary transformations before tokenization.\n\nThis method should pop the arguments from kwargs and return the remaining `kwargs` as well. We test the\n`kwargs` at the end of the encoding process to be sure all the arguments have been used.\n\n**Parameters:**\n\ntext (`str`) : The text to prepare.\n\nis_split_into_words (`bool`, *optional*, defaults to `False`) : Whether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace) which it will tokenize. This is useful for NER or token classification.\n\nkwargs (`dict[str, Any]`, *optional*) : Keyword arguments to use for the tokenization.\n\n**Returns:**\n\n``tuple[str, dict[str, Any]]``\n\nThe prepared text and the unused kwargs.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "prepare_for_tokenization[[transformers.PythonBackend.prepare_for_tokenization]]", "char_start": 45775, "char_end": 46793, "token_estimate": 254, "prev_chunk_id": 660, "next_chunk_id": 662, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 662, "text": "#### save_vocabulary[[transformers.PythonBackend.save_vocabulary]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_python.py#L1356)\n\nDefault implementation for common vocabulary saving patterns.\nSaves self.encoder/self.vocab as JSON, optionally with self.bpe_ranks as merges.\nReturns empty tuple if no vocabulary exists.\n\nOverride this method if your tokenizer needs custom saving logic (e.g., SentencePiece models,\nmultiple vocabulary files, or special file formats).\n\n**Parameters:**\n\nsave_directory (`str`) : The directory in which to save the vocabulary.\n\nfilename_prefix (`str`, *optional*) : An optional prefix to add to the named of the saved files.\n\n**Returns:**\n\n``tuple[str, ...]``\n\nPaths to the files saved, or empty tuple if no files saved.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "save_vocabulary[[transformers.PythonBackend.save_vocabulary]]", "char_start": 46794, "char_end": 47594, "token_estimate": 200, "prev_chunk_id": 661, "next_chunk_id": 663, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 663, "text": "#### tokenize[[transformers.PythonBackend.tokenize]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_python.py#L625)\n\nConverts a string into a sequence of tokens, using the tokenizer.\n\n**Parameters:**\n\ntext : The sequence to be encoded.\n\n- ****kwargs** : Passed along to the model-specific `prepare_for_tokenization` preprocessing method.\n\n**Returns:**\n\nThe list of tokens.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "tokenize[[transformers.PythonBackend.tokenize]]", "char_start": 47595, "char_end": 48016, "token_estimate": 105, "prev_chunk_id": 662, "next_chunk_id": 664, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 664, "text": "#### truncate_sequences[[transformers.PythonBackend.truncate_sequences]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_python.py#L1225)\n\nTruncates sequences according to the specified strategy.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "truncate_sequences[[transformers.PythonBackend.truncate_sequences]]", "char_start": 48017, "char_end": 48260, "token_estimate": 60, "prev_chunk_id": 663, "next_chunk_id": 665, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 665, "text": "## TokenizersBackend[[transformers.TokenizersBackend]]", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 103092, "char_end": 103146, "token_estimate": 13, "prev_chunk_id": 664, "next_chunk_id": 666, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 666, "text": "#### transformers.TokenizersBackend[[transformers.TokenizersBackend]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_tokenizers.py#L84)\n\nBase class for all fast tokenizers (wrapping HuggingFace tokenizers library).\n\nInherits from [PreTrainedTokenizerBase](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase).\n\nHandles all the shared methods for tokenization and special tokens, as well as methods for\ndownloading/caching/loading pretrained tokenizers, as well as adding tokens to the vocabulary.\n\nThis class also contains the added tokens in a unified way on top of all tokenizers so we don't have to handle the\nspecific vocabulary augmentation methods of the various underlying dictionary structures (BPE, sentencepiece...).\n\nClass attributes (overridden by derived classes)", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 48729, "char_end": 49602, "token_estimate": 218, "prev_chunk_id": 665, "next_chunk_id": 667, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 667, "text": "- **vocab_files_names** (`dict[str, str]`) -- A dictionary with, as keys, the `__init__` keyword name of each\n vocabulary file required by the model, and as associated values, the filename for saving the associated file\n (string).\n- **pretrained_vocab_files_map** (`dict[str, dict[str, str]]`) -- A dictionary of dictionaries, with the\n high-level keys being the `__init__` keyword name of each vocabulary file required by the model, the\n low-level being the `short-cut-names` of the pretrained models with, as associated values, the `url` to the\n associated pretrained vocabulary file.\n- **model_input_names** (`list[str]`) -- A list of inputs expected in the forward pass of the model.\n- **padding_side** (`str`) -- The default value for the side on which the model should have padding applied.\n Should be `'right'` or `'left'`.\n- **truncation_side** (`str`) -- The default value for the side on which the model should have truncation\n applied. Should be `'right'` or `'left'`.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 4962, "char_end": 5948, "token_estimate": 246, "prev_chunk_id": 666, "next_chunk_id": 668, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 668, "text": "convert_to_native_formattransformers.TokenizersBackend.convert_to_native_formathttps://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_tokenizers.py#L101[{\"name\": \"trust_remote_code\", \"val\": \" = False\"}, {\"name\": \"**kwargs\", \"val\": \"\"}]\n\nBuild a `tokenizers.Tokenizer` backend from the available serialization files (tokenizer.json, sentencepiece\nmodels, tekken.json, vocab/merges).\n\n**Parameters:**\n\nmodel_max_length (`int`, *optional*) : The maximum length (in number of tokens) for the inputs to the transformer model. When the tokenizer is loaded with [from_pretrained()](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.from_pretrained), this will be set to the value stored for the associated model in `max_model_input_sizes` (see above). If no value is provided, will default to VERY_LARGE_INTEGER (`int(1e30)`).", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 105011, "char_end": 105911, "token_estimate": 225, "prev_chunk_id": 667, "next_chunk_id": 669, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 669, "text": "padding_side (`str`, *optional*) : The side on which the model should have padding applied. Should be selected between ['right', 'left']. Default value is picked from the class attribute of the same name.\n\ntruncation_side (`str`, *optional*) : The side on which the model should have truncation applied. Should be selected between ['right', 'left']. Default value is picked from the class attribute of the same name.\n\nchat_template (`str`, *optional*) : A Jinja template string that will be used to format lists of chat messages. See https://huggingface.co/docs/transformers/chat_templating for a full description.\n\nmodel_input_names (`list[string]`, *optional*) : The list of inputs accepted by the forward pass of the model (like `\"token_type_ids\"` or `\"attention_mask\"`). Default value is picked from the class attribute of the same name.\n\nbos_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing the beginning of a sentence.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 17435, "char_end": 18394, "token_estimate": 239, "prev_chunk_id": 668, "next_chunk_id": 670, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 670, "text": "eos_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing the end of a sentence.\n\nunk_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing an out-of-vocabulary token.\n\nsep_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token separating two different sentences in the same input (used by BERT for instance).\n\npad_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by attention mechanisms or loss computation.\n\ncls_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing the class of the input (used by BERT for instance).\n\nmask_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing a masked token (used by masked-language modeling pretraining objectives, like BERT). Will be associated to `self.mask_token` and `self.mask_token_id`.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 18396, "char_end": 19371, "token_estimate": 243, "prev_chunk_id": 669, "next_chunk_id": 671, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 671, "text": "extra_special_tokens (list of `str` or `tokenizers.AddedToken`, *optional*) : A list of extra model-specific special tokens. Add them here to ensure they are skipped when decoding with `skip_special_tokens` is set to True. If they are not part of the vocabulary, they will be added at the end of the vocabulary.\n\nsplit_special_tokens (`bool`, *optional*, defaults to `False`) : Whether or not the special tokens should be split during the tokenization process. Passing will affect the internal state of the tokenizer. The default behavior is to not split special tokens. This means that if `` is the `bos_token`, then `tokenizer.tokenize(\"\") = ['`]. Otherwise, if `split_special_tokens=True`, then `tokenizer.tokenize(\"\")` will be give `['']`.\n\ntokenizer_object (`tokenizers.Tokenizer`) : A `tokenizers.Tokenizer` object from \ud83e\udd17 tokenizers to instantiate from. See [Using tokenizers from \ud83e\udd17 tokenizers](../fast_tokenizers) for more information.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 0, "char_end": 942, "token_estimate": 235, "prev_chunk_id": 670, "next_chunk_id": 672, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 672, "text": "tokenizer_file (`str`) : A path to a local JSON file representing a previously serialized `tokenizers.Tokenizer` object from \ud83e\udd17 tokenizers.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.TokenizersBackend[[transformers.TokenizersBackend]]", "char_start": 64964, "char_end": 65102, "token_estimate": 34, "prev_chunk_id": 671, "next_chunk_id": 673, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 673, "text": "#### get_added_vocab[[transformers.TokenizersBackend.get_added_vocab]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_tokenizers.py#L635)\n\nReturns the added tokens in the vocabulary as a dictionary of token to index.\n\n**Returns:**\n\n``dict[str, int]``\n\nThe added tokens.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "get_added_vocab[[transformers.TokenizersBackend.get_added_vocab]]", "char_start": 86029, "char_end": 86353, "token_estimate": 81, "prev_chunk_id": 672, "next_chunk_id": 674, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 674, "text": "#### num_special_tokens_to_add[[transformers.TokenizersBackend.num_special_tokens_to_add]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_tokenizers.py#L732)\n\nReturns the number of added tokens when encoding a sequence with special tokens.\n\nThis encodes a dummy input and checks the number of added tokens, and is therefore not efficient. Do not put\nthis inside your training loop.\n\n**Parameters:**\n\npair (`bool`, *optional*, defaults to `False`) : Whether the number of added tokens should be computed in the case of a sequence pair or a single sequence.\n\n**Returns:**\n\n``int``\n\nNumber of special tokens added to sequences.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "num_special_tokens_to_add[[transformers.TokenizersBackend.num_special_tokens_to_add]]", "char_start": 86354, "char_end": 87033, "token_estimate": 169, "prev_chunk_id": 673, "next_chunk_id": 675, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 675, "text": "#### set_truncation_and_padding[[transformers.TokenizersBackend.set_truncation_and_padding]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_tokenizers.py#L782)\n\nDefine the truncation and the padding strategies for fast tokenizers (provided by HuggingFace tokenizers\nlibrary) and restore the tokenizer settings afterwards.\n\nThe provided tokenizer has no padding / truncation strategy before the managed section. If your tokenizer set a\npadding / truncation strategy before, then it will be reset to no padding / truncation when exiting the managed\nsection.\n\n**Parameters:**\n\npadding_strategy ([PaddingStrategy](/docs/transformers/v5.6.2/en/internal/file_utils#transformers.utils.PaddingStrategy)) : The kind of padding that will be applied to the input\n\ntruncation_strategy ([TruncationStrategy](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.tokenization_utils_base.TruncationStrategy)) : The kind of truncation that will be applied to the input", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "set_truncation_and_padding[[transformers.TokenizersBackend.set_truncation_and_padding]]", "char_start": 87034, "char_end": 88057, "token_estimate": 255, "prev_chunk_id": 674, "next_chunk_id": 676, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 676, "text": "max_length (`int`) : The maximum size of a sequence.\n\nstride (`int`) : The stride to use when handling overflow.\n\npad_to_multiple_of (`int`, *optional*) : If set will pad the sequence to a multiple of the provided value. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).\n\npadding_side (`str`, *optional*) : The side on which the model should have padding applied. Should be selected between ['right', 'left']. Default value is picked from the class attribute of the same name.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "set_truncation_and_padding[[transformers.TokenizersBackend.set_truncation_and_padding]]", "char_start": 88059, "char_end": 88606, "token_estimate": 136, "prev_chunk_id": 675, "next_chunk_id": 677, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 677, "text": "#### train_new_from_iterator[[transformers.TokenizersBackend.train_new_from_iterator]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_tokenizers.py#L1061)\n\nTrains a tokenizer on a new corpus with the same defaults (in terms of special tokens or tokenization pipeline)\nas the current one.\n\n**Parameters:**\n\ntext_iterator (generator of `list[str]`) : The training corpus. Should be a generator of batches of texts, for instance a list of lists of texts if you have everything in memory.\n\nvocab_size (`int`) : The size of the vocabulary you want for your tokenizer.\n\nlength (`int`, *optional*) : The total number of sequences in the iterator. This is used to provide meaningful progress tracking\n\nnew_special_tokens (list of `str` or `AddedToken`, *optional*) : A list of new special tokens to add to the tokenizer you are training.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "train_new_from_iterator[[transformers.TokenizersBackend.train_new_from_iterator]]", "char_start": 88607, "char_end": 89491, "token_estimate": 221, "prev_chunk_id": 676, "next_chunk_id": 678, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 678, "text": "special_tokens_map (`dict[str, str]`, *optional*) : If you want to rename some of the special tokens this tokenizer uses, pass along a mapping old special token name to new special token name in this argument.\n\nkwargs (`dict[str, Any]`, *optional*) : Additional keyword arguments passed along to the trainer from the \ud83e\udd17 Tokenizers library.\n\n**Returns:**\n\n`[PreTrainedTokenizerFast](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.TokenizersBackend)`\n\nA new tokenizer of the same type as the original one, trained on\n`text_iterator`.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "train_new_from_iterator[[transformers.TokenizersBackend.train_new_from_iterator]]", "char_start": 89493, "char_end": 90041, "token_estimate": 137, "prev_chunk_id": 677, "next_chunk_id": 679, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 679, "text": "#### update_post_processor[[transformers.TokenizersBackend.update_post_processor]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_tokenizers.py#L522)\n\nUpdates the underlying post processor with the current `bos_token` and `eos_token`.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "update_post_processor[[transformers.TokenizersBackend.update_post_processor]]", "char_start": 90042, "char_end": 90331, "token_estimate": 72, "prev_chunk_id": 678, "next_chunk_id": 680, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 680, "text": "## SentencePieceBackend[[transformers.SentencePieceBackend]]", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "SentencePieceBackend[[transformers.SentencePieceBackend]]", "char_start": 113239, "char_end": 113299, "token_estimate": 15, "prev_chunk_id": 679, "next_chunk_id": 681, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 681, "text": "#### transformers.SentencePieceBackend[[transformers.SentencePieceBackend]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_sentencepiece.py#L45)\n\nBase class for SentencePiece-based tokenizers that load from sentencepiece.model files.\n\nInherits from [PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend).\n\nHandle all the shared methods for tokenization and special tokens as well as methods downloading/caching/loading\npretrained tokenizers as well as adding tokens to the vocabulary.\n\nThis class also contain the added tokens in a unified way on top of all tokenizers so we don't have to handle the\nspecific vocabulary augmentation methods of the various underlying dictionary structures (BPE, sentencepiece...).\n\nClass attributes (overridden by derived classes)", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.SentencePieceBackend[[transformers.SentencePieceBackend]]", "char_start": 113301, "char_end": 114166, "token_estimate": 216, "prev_chunk_id": 680, "next_chunk_id": 682, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 682, "text": "- **vocab_files_names** (`dict[str, str]`) -- A dictionary with, as keys, the `__init__` keyword name of each\n vocabulary file required by the model, and as associated values, the filename for saving the associated file\n (string).\n- **pretrained_vocab_files_map** (`dict[str, dict[str, str]]`) -- A dictionary of dictionaries, with the\n high-level keys being the `__init__` keyword name of each vocabulary file required by the model, the\n low-level being the `short-cut-names` of the pretrained models with, as associated values, the `url` to the\n associated pretrained vocabulary file.\n- **model_input_names** (`list[str]`) -- A list of inputs expected in the forward pass of the model.\n- **padding_side** (`str`) -- The default value for the side on which the model should have padding applied.\n Should be `'right'` or `'left'`.\n- **truncation_side** (`str`) -- The default value for the side on which the model should have truncation\n applied. Should be `'right'` or `'left'`.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.SentencePieceBackend[[transformers.SentencePieceBackend]]", "char_start": 4962, "char_end": 5948, "token_estimate": 246, "prev_chunk_id": 681, "next_chunk_id": 683, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 683, "text": "convert_tokens_to_stringtransformers.SentencePieceBackend.convert_tokens_to_stringhttps://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_sentencepiece.py#L232[{\"name\": \"tokens\", \"val\": \": list\"}]\nConverts a sequence of tokens (string) in a single string.\n\n**Parameters:**\n\nmodel_max_length (`int`, *optional*) : The maximum length (in number of tokens) for the inputs to the transformer model. When the tokenizer is loaded with [from_pretrained()](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.from_pretrained), this will be set to the value stored for the associated model in `max_model_input_sizes` (see above). If no value is provided, will default to VERY_LARGE_INTEGER (`int(1e30)`).\n\npadding_side (`str`, *optional*) : The side on which the model should have padding applied. Should be selected between ['right', 'left']. Default value is picked from the class attribute of the same name.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.SentencePieceBackend[[transformers.SentencePieceBackend]]", "char_start": 115156, "char_end": 116135, "token_estimate": 244, "prev_chunk_id": 682, "next_chunk_id": 684, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 684, "text": "truncation_side (`str`, *optional*) : The side on which the model should have truncation applied. Should be selected between ['right', 'left']. Default value is picked from the class attribute of the same name.\n\nchat_template (`str`, *optional*) : A Jinja template string that will be used to format lists of chat messages. See https://huggingface.co/docs/transformers/chat_templating for a full description.\n\nmodel_input_names (`list[string]`, *optional*) : The list of inputs accepted by the forward pass of the model (like `\"token_type_ids\"` or `\"attention_mask\"`). Default value is picked from the class attribute of the same name.\n\nbos_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing the beginning of a sentence.\n\neos_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing the end of a sentence.\n\nunk_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing an out-of-vocabulary token.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.SentencePieceBackend[[transformers.SentencePieceBackend]]", "char_start": 17641, "char_end": 18623, "token_estimate": 245, "prev_chunk_id": 683, "next_chunk_id": 685, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 685, "text": "sep_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token separating two different sentences in the same input (used by BERT for instance).\n\npad_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by attention mechanisms or loss computation.\n\ncls_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing the class of the input (used by BERT for instance).\n\nmask_token (`str` or `tokenizers.AddedToken`, *optional*) : A special token representing a masked token (used by masked-language modeling pretraining objectives, like BERT). Will be associated to `self.mask_token` and `self.mask_token_id`.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.SentencePieceBackend[[transformers.SentencePieceBackend]]", "char_start": 18625, "char_end": 19371, "token_estimate": 186, "prev_chunk_id": 684, "next_chunk_id": 686, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 686, "text": "extra_special_tokens (list of `str` or `tokenizers.AddedToken`, *optional*) : A list of extra model-specific special tokens. Add them here to ensure they are skipped when decoding with `skip_special_tokens` is set to True. If they are not part of the vocabulary, they will be added at the end of the vocabulary.\n\nsplit_special_tokens (`bool`, *optional*, defaults to `False`) : Whether or not the special tokens should be split during the tokenization process. Passing will affect the internal state of the tokenizer. The default behavior is to not split special tokens. This means that if `` is the `bos_token`, then `tokenizer.tokenize(\"\") = ['`]. Otherwise, if `split_special_tokens=True`, then `tokenizer.tokenize(\"\")` will be give `['']`.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.SentencePieceBackend[[transformers.SentencePieceBackend]]", "char_start": 19373, "char_end": 20116, "token_estimate": 185, "prev_chunk_id": 685, "next_chunk_id": 687, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 687, "text": "#### get_vocab[[transformers.SentencePieceBackend.get_vocab]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_sentencepiece.py#L104)\n\nReturns vocab as a dict", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "get_vocab[[transformers.SentencePieceBackend.get_vocab]]", "char_start": 118613, "char_end": 118824, "token_estimate": 52, "prev_chunk_id": 686, "next_chunk_id": 688, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 688, "text": "#### save_vocabulary[[transformers.SentencePieceBackend.save_vocabulary]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_sentencepiece.py#L237)\n\nSave the sentencepiece vocabulary (copy original file) to a directory.\n\n**Parameters:**\n\nsave_directory (`str`) : The directory in which to save the vocabulary.\n\nfilename_prefix (`str`, *optional*) : An optional prefix to add to the named of the saved files.\n\n**Returns:**\n\n``tuple(str)``\n\nPaths to the files saved.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "save_vocabulary[[transformers.SentencePieceBackend.save_vocabulary]]", "char_start": 118825, "char_end": 119340, "token_estimate": 128, "prev_chunk_id": 687, "next_chunk_id": 689, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 689, "text": "## BatchEncoding[[transformers.BatchEncoding]]", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "BatchEncoding[[transformers.BatchEncoding]]", "char_start": 119342, "char_end": 119388, "token_estimate": 11, "prev_chunk_id": 688, "next_chunk_id": 690, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 690, "text": "#### transformers.BatchEncoding[[transformers.BatchEncoding]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L193)\n\nHolds the output of the [__call__()](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__),\n`~tokenization_utils_base.PreTrainedTokenizerBase.encode_plus` and\n`~tokenization_utils_base.PreTrainedTokenizerBase.batch_encode_plus` methods (tokens, attention_masks, etc).\n\nThis class is derived from a python dictionary and can be used as a dictionary. In addition, this class exposes\nutility methods to map from word/character space to token space.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.BatchEncoding[[transformers.BatchEncoding]]", "char_start": 119390, "char_end": 120064, "token_estimate": 168, "prev_chunk_id": 689, "next_chunk_id": 691, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 691, "text": "char_to_tokentransformers.BatchEncoding.char_to_tokenhttps://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L549[{\"name\": \"batch_or_char_index\", \"val\": \": int\"}, {\"name\": \"char_index\", \"val\": \": int | None = None\"}, {\"name\": \"sequence_index\", \"val\": \": int = 0\"}]- **batch_or_char_index** (`int`) --\n Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of\n the word in the sequence\n- **char_index** (`int`, *optional*) --\n If a batch index is provided in *batch_or_token_index*, this can be the index of the word in the\n sequence.\n- **sequence_index** (`int`, *optional*, defaults to 0) --\n If pair of sequences are encoded in the batch this can be used to specify which sequence in the pair (0\n or 1) the provided character index belongs to.0`int`Index of the token, or None if the char index refers to a whitespace only token and whitespace is\ntrimmed with `trim_offsets=True`.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.BatchEncoding[[transformers.BatchEncoding]]", "char_start": 120066, "char_end": 121043, "token_estimate": 244, "prev_chunk_id": 690, "next_chunk_id": 692, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 692, "text": "Get the index of the token in the encoded output comprising a character in the original string for a sequence\nof the batch.\n\nCan be called as:\n\n- `self.char_to_token(char_index)` if batch size is 1\n- `self.char_to_token(batch_index, char_index)` if batch size is greater or equal to 1\n\nThis method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e. words\nare defined by the user). In this case it allows to easily associate encoded tokens with provided tokenized\nwords.\n\n**Parameters:**\n\ndata (`dict`, *optional*) : Dictionary of lists/arrays/tensors returned by the `__call__`/`encode_plus`/`batch_encode_plus` methods ('input_ids', 'attention_mask', etc.).\n\nencoding (`tokenizers.Encoding` or `Sequence[tokenizers.Encoding]`, *optional*) : If the tokenizer is a fast tokenizer which outputs additional information like mapping from word/character space to token space the `tokenizers.Encoding` instance or list of instance (for batches) hold this information.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.BatchEncoding[[transformers.BatchEncoding]]", "char_start": 121045, "char_end": 122049, "token_estimate": 251, "prev_chunk_id": 691, "next_chunk_id": 693, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 693, "text": "tensor_type (`Union[None, str, TensorType]`, *optional*) : You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at initialization.\n\nprepend_batch_axis (`bool`, *optional*, defaults to `False`) : Whether or not to add a batch axis when converting to tensors (see `tensor_type` above). Note that this parameter has an effect if the parameter `tensor_type` is set, *otherwise has no effect*.\n\nn_sequences (`Optional[int]`, *optional*) : You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at initialization.\n\n**Returns:**\n\n``int``\n\nIndex of the token, or None if the char index refers to a whitespace only token and whitespace is\ntrimmed with `trim_offsets=True`.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "transformers.BatchEncoding[[transformers.BatchEncoding]]", "char_start": 122051, "char_end": 122786, "token_estimate": 183, "prev_chunk_id": 692, "next_chunk_id": 694, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 694, "text": "#### char_to_word[[transformers.BatchEncoding.char_to_word]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L634)\n\nGet the word in the original string corresponding to a character in the original string of a sequence of the\nbatch.\n\nCan be called as:\n\n- `self.char_to_word(char_index)` if batch size is 1\n- `self.char_to_word(batch_index, char_index)` if batch size is greater than 1\n\nThis method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e. words\nare defined by the user). In this case it allows to easily associate encoded tokens with provided tokenized\nwords.\n\n**Parameters:**\n\nbatch_or_char_index (`int`) : Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of the character in the original string.\n\nchar_index (`int`, *optional*) : If a batch index is provided in *batch_or_token_index*, this can be the index of the character in the original string.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "char_to_word[[transformers.BatchEncoding.char_to_word]]", "char_start": 122787, "char_end": 123801, "token_estimate": 253, "prev_chunk_id": 693, "next_chunk_id": 695, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 695, "text": "sequence_index (`int`, *optional*, defaults to 0) : If pair of sequences are encoded in the batch this can be used to specify which sequence in the pair (0 or 1) the provided character index belongs to.\n\n**Returns:**\n\n``int` or `list[int]``\n\nIndex or indices of the associated encoded token(s).", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "char_to_word[[transformers.BatchEncoding.char_to_word]]", "char_start": 123803, "char_end": 124097, "token_estimate": 73, "prev_chunk_id": 694, "next_chunk_id": 696, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 696, "text": "#### convert_to_tensors[[transformers.BatchEncoding.convert_to_tensors]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L673)\n\nConvert the inner content to tensors.\n\n**Parameters:**\n\ntensor_type (`str` or [TensorType](/docs/transformers/v5.6.2/en/internal/file_utils#transformers.TensorType), *optional*) : The type of tensors to use. If `str`, should be one of the values of the enum [TensorType](/docs/transformers/v5.6.2/en/internal/file_utils#transformers.TensorType). If `None`, no modification is done.\n\nprepend_batch_axis (`int`, *optional*, defaults to `False`) : Whether or not to add the batch dimension during the conversion.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "convert_to_tensors[[transformers.BatchEncoding.convert_to_tensors]]", "char_start": 124098, "char_end": 124797, "token_estimate": 174, "prev_chunk_id": 695, "next_chunk_id": 697, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 697, "text": "#### sequence_ids[[transformers.BatchEncoding.sequence_ids]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L337)\n\nReturn a list mapping the tokens to the id of their original sentences:\n\n- `None` for special tokens added around or between sequences,\n- `0` for tokens corresponding to words in the first sequence,\n- `1` for tokens corresponding to words in the second sequence when a pair of sequences was jointly\n encoded.\n\n**Parameters:**\n\nbatch_index (`int`, *optional*, defaults to 0) : The index to access in the batch.\n\n**Returns:**\n\n``list[Optional[int]]``\n\nA list indicating the sequence id corresponding to each token. Special tokens added\nby the tokenizer are mapped to `None` and other tokens are mapped to the index of their corresponding\nsequence.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "sequence_ids[[transformers.BatchEncoding.sequence_ids]]", "char_start": 124798, "char_end": 125622, "token_estimate": 206, "prev_chunk_id": 696, "next_chunk_id": 698, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 698, "text": "#### to[[transformers.BatchEncoding.to]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L767)\n\nSend all values to device by calling `v.to(device, non_blocking=non_blocking)` (PyTorch only).\n\n**Parameters:**\n\ndevice (`str` or `torch.device`) : The device to put the tensors on.\n\nnon_blocking (`bool`) : Whether to perform the copy asynchronously.\n\n**Returns:**\n\n`[BatchEncoding](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.BatchEncoding)`\n\nThe same instance after modification.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "to[[transformers.BatchEncoding.to]]", "char_start": 125623, "char_end": 126183, "token_estimate": 140, "prev_chunk_id": 697, "next_chunk_id": 699, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 699, "text": "#### token_to_chars[[transformers.BatchEncoding.token_to_chars]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L510)\n\nGet the character span corresponding to an encoded token in a sequence of the batch.\n\nCharacter spans are returned as a [CharSpan](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.CharSpan) with:\n\n- **start** -- Index of the first character in the original string associated to the token.\n- **end** -- Index of the character following the last character in the original string associated to the\n token.\n\nCan be called as:\n\n- `self.token_to_chars(token_index)` if batch size is 1\n- `self.token_to_chars(batch_index, token_index)` if batch size is greater or equal to 1\n\n**Parameters:**\n\nbatch_or_token_index (`int`) : Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of the token in the sequence.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "token_to_chars[[transformers.BatchEncoding.token_to_chars]]", "char_start": 126184, "char_end": 127133, "token_estimate": 237, "prev_chunk_id": 698, "next_chunk_id": 700, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 700, "text": "token_index (`int`, *optional*) : If a batch index is provided in *batch_or_token_index*, this can be the index of the token or tokens in the sequence.\n\n**Returns:**\n\n`[CharSpan](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.CharSpan)`\n\nSpan of characters in the original string, or None, if the token\n(e.g. , ) doesn't correspond to any chars in the origin string.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "token_to_chars[[transformers.BatchEncoding.token_to_chars]]", "char_start": 127135, "char_end": 127524, "token_estimate": 97, "prev_chunk_id": 699, "next_chunk_id": 701, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 701, "text": "#### token_to_sequence[[transformers.BatchEncoding.token_to_sequence]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L380)\n\nGet the index of the sequence represented by the given token. In the general use case, this method returns `0`\nfor a single sequence or the first sequence of a pair, and `1` for the second sequence of a pair\n\nCan be called as:\n\n- `self.token_to_sequence(token_index)` if batch size is 1\n- `self.token_to_sequence(batch_index, token_index)` if batch size is greater than 1\n\nThis method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e.,\nwords are defined by the user). In this case it allows to easily associate encoded tokens with provided\ntokenized words.\n\n**Parameters:**\n\nbatch_or_token_index (`int`) : Index of the sequence in the batch. If the batch only comprises one sequence, this can be the index of the token in the sequence.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "token_to_sequence[[transformers.BatchEncoding.token_to_sequence]]", "char_start": 127525, "char_end": 128492, "token_estimate": 241, "prev_chunk_id": 700, "next_chunk_id": 702, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 702, "text": "token_index (`int`, *optional*) : If a batch index is provided in *batch_or_token_index*, this can be the index of the token in the sequence.\n\n**Returns:**\n\n``int``\n\nIndex of the word in the input sequence.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "token_to_sequence[[transformers.BatchEncoding.token_to_sequence]]", "char_start": 128494, "char_end": 128700, "token_estimate": 51, "prev_chunk_id": 701, "next_chunk_id": 703, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 703, "text": "#### token_to_word[[transformers.BatchEncoding.token_to_word]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L419)\n\nGet the index of the word corresponding (i.e. comprising) to an encoded token in a sequence of the batch.\n\nCan be called as:\n\n- `self.token_to_word(token_index)` if batch size is 1\n- `self.token_to_word(batch_index, token_index)` if batch size is greater than 1\n\nThis method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e.,\nwords are defined by the user). In this case it allows to easily associate encoded tokens with provided\ntokenized words.\n\n**Parameters:**\n\nbatch_or_token_index (`int`) : Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of the token in the sequence.\n\ntoken_index (`int`, *optional*) : If a batch index is provided in *batch_or_token_index*, this can be the index of the token in the sequence.\n\n**Returns:**\n\n``int``", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "token_to_word[[transformers.BatchEncoding.token_to_word]]", "char_start": 128701, "char_end": 129715, "token_estimate": 253, "prev_chunk_id": 702, "next_chunk_id": 704, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 704, "text": "Index of the word in the input sequence.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "token_to_word[[transformers.BatchEncoding.token_to_word]]", "char_start": 128660, "char_end": 128700, "token_estimate": 10, "prev_chunk_id": 703, "next_chunk_id": 705, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 705, "text": "#### tokens[[transformers.BatchEncoding.tokens]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L319)\n\nReturn the list of tokens (sub-parts of the input strings after word/subword splitting and before conversion to\ninteger indices) at a given batch index (only works for the output of a fast tokenizer).\n\n**Parameters:**\n\nbatch_index (`int`, *optional*, defaults to 0) : The index to access in the batch.\n\n**Returns:**\n\n``list[str]``\n\nThe list of tokens at that index.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "tokens[[transformers.BatchEncoding.tokens]]", "char_start": 129758, "char_end": 130289, "token_estimate": 132, "prev_chunk_id": 704, "next_chunk_id": 706, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 706, "text": "#### word_ids[[transformers.BatchEncoding.word_ids]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L361)\n\nReturn a list mapping the tokens to their actual word in the initial sentence for a fast tokenizer.\n\n**Parameters:**\n\nbatch_index (`int`, *optional*, defaults to 0) : The index to access in the batch.\n\n**Returns:**\n\n``list[Optional[int]]``\n\nA list indicating the word corresponding to each token. Special tokens added by the\ntokenizer are mapped to `None` and other tokens are mapped to the index of their corresponding word\n(several tokens will be mapped to the same word index if they are parts of that word).", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "word_ids[[transformers.BatchEncoding.word_ids]]", "char_start": 130290, "char_end": 130971, "token_estimate": 170, "prev_chunk_id": 705, "next_chunk_id": 707, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 707, "text": "#### word_to_chars[[transformers.BatchEncoding.word_to_chars]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L589)\n\nGet the character span in the original string corresponding to given word in a sequence of the batch.\n\nCharacter spans are returned as a CharSpan NamedTuple with:\n\n- start: index of the first character in the original string\n- end: index of the character following the last character in the original string\n\nCan be called as:\n\n- `self.word_to_chars(word_index)` if batch size is 1\n- `self.word_to_chars(batch_index, word_index)` if batch size is greater or equal to 1\n\n**Parameters:**\n\nbatch_or_word_index (`int`) : Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of the word in the sequence\n\nword_index (`int`, *optional*) : If a batch index is provided in *batch_or_token_index*, this can be the index of the word in the sequence.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "word_to_chars[[transformers.BatchEncoding.word_to_chars]]", "char_start": 130972, "char_end": 131935, "token_estimate": 240, "prev_chunk_id": 706, "next_chunk_id": 708, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 708, "text": "sequence_index (`int`, *optional*, defaults to 0) : If pair of sequences are encoded in the batch this can be used to specify which sequence in the pair (0 or 1) the provided word index belongs to.\n\n**Returns:**\n\n``CharSpan` or `list[CharSpan]``\n\nSpan(s) of the associated character or characters in the string. CharSpan\nare NamedTuple with:\n\n- start: index of the first character associated to the token in the original string\n- end: index of the character following the last character associated to the token in the original\n string", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "word_to_chars[[transformers.BatchEncoding.word_to_chars]]", "char_start": 131937, "char_end": 132472, "token_estimate": 133, "prev_chunk_id": 707, "next_chunk_id": 709, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 709, "text": "#### word_to_tokens[[transformers.BatchEncoding.word_to_tokens]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/tokenization_utils_base.py#L457)\n\nGet the encoded token span corresponding to a word in a sequence of the batch.\n\nToken spans are returned as a [TokenSpan](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.TokenSpan) with:\n\n- **start** -- Index of the first token.\n- **end** -- Index of the token following the last token.\n\nCan be called as:\n\n- `self.word_to_tokens(word_index, sequence_index: int = 0)` if batch size is 1\n- `self.word_to_tokens(batch_index, word_index, sequence_index: int = 0)` if batch size is greater or equal to\n 1\n\nThis method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e. words\nare defined by the user). In this case it allows to easily associate encoded tokens with provided tokenized\nwords.\n\n**Parameters:**", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "word_to_tokens[[transformers.BatchEncoding.word_to_tokens]]", "char_start": 132473, "char_end": 133423, "token_estimate": 237, "prev_chunk_id": 708, "next_chunk_id": 710, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 710, "text": "batch_or_word_index (`int`) : Index of the sequence in the batch. If the batch only comprises one sequence, this can be the index of the word in the sequence.\n\nword_index (`int`, *optional*) : If a batch index is provided in *batch_or_token_index*, this can be the index of the word in the sequence.\n\nsequence_index (`int`, *optional*, defaults to 0) : If pair of sequences are encoded in the batch this can be used to specify which sequence in the pair (0 or 1) the provided word index belongs to.\n\n**Returns:**\n\n`([TokenSpan](/docs/transformers/v5.6.2/en/internal/tokenization_utils#transformers.TokenSpan), *optional*)`\n\nSpan of tokens in the encoded sequence. Returns\n`None` if no tokens correspond to the word. This can happen especially when the token is a special token\nthat has been used to format the tokenization. For example when we add a class token at the very beginning\nof the tokenization.", "source_file": "transformers/main_classes/tokenizer.md", "section_heading": "word_to_tokens[[transformers.BatchEncoding.word_to_tokens]]", "char_start": 133425, "char_end": 134329, "token_estimate": 226, "prev_chunk_id": 709, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/main_classes/tokenizer", "doc_title": "Tokenizer" }, { "chunk_id": 711, "text": "# Pipelines\n\nThe pipelines are a great and easy way to use models for inference. These pipelines are objects that abstract most of\nthe complex code from the library, offering a simple API dedicated to several tasks, including Named Entity\nRecognition, Masked Language Modeling, Sentiment Analysis, Feature Extraction and Question Answering. See the\n[task summary](../task_summary) for examples of use.\n\nThere are two categories of pipeline abstractions to be aware about:\n\n- The [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline) which is the most powerful object encapsulating all other pipelines.\n- Task-specific pipelines are available for [audio](#audio), [computer vision](#computer-vision), [natural language processing](#natural-language-processing), and [multimodal](#multimodal) tasks.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "Pipelines", "char_start": 0, "char_end": 831, "token_estimate": 207, "prev_chunk_id": null, "next_chunk_id": 712, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 712, "text": "## The pipeline abstraction[[transformers.pipeline]]\n\nThe *pipeline* abstraction is a wrapper around all the other available pipelines. It is instantiated as any other\npipeline but can provide additional quality of life.\n\nSimple call on one item:\n\n```python\n>>> pipe = pipeline(\"text-classification\")\n>>> pipe(\"This restaurant is awesome\")\n[{'label': 'POSITIVE', 'score': 0.9998743534088135}]\n```\n\nIf you want to use a specific model from the [hub](https://huggingface.co) you can ignore the task if the model on\nthe hub already defines it:\n\n```python\n>>> pipe = pipeline(model=\"FacebookAI/roberta-large-mnli\")\n>>> pipe(\"This restaurant is awesome\")\n[{'label': 'NEUTRAL', 'score': 0.7313136458396912}]\n```\n\nTo call a pipeline on many items, you can call it with a *list*.\n\n```python\n>>> pipe = pipeline(\"text-classification\")\n>>> pipe([\"This restaurant is awesome\", \"This restaurant is awful\"])\n[{'label': 'POSITIVE', 'score': 0.9998743534088135},\n {'label': 'NEGATIVE', 'score': 0.9996669292449951}]\n```", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "The pipeline abstraction[[transformers.pipeline]]", "char_start": 833, "char_end": 1837, "token_estimate": 251, "prev_chunk_id": 711, "next_chunk_id": 713, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 713, "text": "To iterate over full datasets it is recommended to use a `dataset` directly. This means you don't need to allocate\nthe whole dataset at once, nor do you need to do batching yourself. This should work just as fast as custom loops on\nGPU. If it doesn't don't hesitate to create an issue.\n\n```python\nimport datasets\nfrom transformers import pipeline\nfrom transformers.pipelines.pt_utils import KeyDataset\nfrom tqdm.auto import tqdm\n\npipe = pipeline(\"automatic-speech-recognition\", model=\"facebook/wav2vec2-base-960h\", device=0)\ndataset = datasets.load_dataset(\"superb\", name=\"asr\", split=\"test\")", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "The pipeline abstraction[[transformers.pipeline]]", "char_start": 1839, "char_end": 2431, "token_estimate": 148, "prev_chunk_id": 712, "next_chunk_id": 714, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 714, "text": "# KeyDataset (only *pt*) will simply return the item in the dict returned by the dataset item", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "KeyDataset (only *pt*) will simply return the item in the dict returned by the dataset item", "char_start": 2433, "char_end": 2526, "token_estimate": 23, "prev_chunk_id": 713, "next_chunk_id": 715, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 715, "text": "# as we're not interested in the *target* part of the dataset. For sentence pair use KeyPairDataset\nfor out in tqdm(pipe(KeyDataset(dataset, \"file\"))):\n print(out)\n # {\"text\": \"NUMBER TEN FRESH NELLY IS WAITING ON YOU GOOD NIGHT HUSBAND\"}\n # {\"text\": ....}\n # ....\n```\n\nFor ease of use, a generator is also possible:\n\n```python\nfrom transformers import pipeline\n\npipe = pipeline(\"text-classification\")\n\ndef data():\n while True:\n # This could come from a dataset, a database, a queue or HTTP request\n # in a server\n # Caveat: because this is iterative, you cannot use `num_workers > 1` variable\n # to use multiple threads to preprocess data. You can still have 1 thread that\n # does the preprocessing while the main runs the big inference\n yield \"This is a test\"\n\nfor out in pipe(data()):\n print(out)\n # {\"text\": \"NUMBER TEN FRESH NELLY IS WAITING ON YOU GOOD NIGHT HUSBAND\"}\n # {\"text\": ....}\n # ....\n```", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "as we're not interested in the *target* part of the dataset. For sentence pair use KeyPairDataset", "char_start": 2527, "char_end": 3500, "token_estimate": 243, "prev_chunk_id": 714, "next_chunk_id": 716, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 716, "text": "#### transformers.pipeline[[transformers.pipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/__init__.py#L440)\n\nUtility factory method to build a [Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline).\n\nA pipeline consists of:\n\n- One or more components for pre-processing model inputs, such as a [tokenizer](tokenizer),\n[image_processor](image_processor), [feature_extractor](feature_extractor), or [processor](processors).\n- A [model](model) that generates predictions from the inputs.\n- Optional post-processing steps to refine the model's output, which can also be handled by processors.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.pipeline[[transformers.pipeline]]", "char_start": 3502, "char_end": 4175, "token_estimate": 168, "prev_chunk_id": 715, "next_chunk_id": 717, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 717, "text": "While there are such optional arguments as `tokenizer`, `feature_extractor`, `image_processor`, and `processor`,\nthey shouldn't be specified all at once. If these components are not provided, `pipeline` will try to load\nrequired ones automatically. In case you want to provide these components explicitly, please refer to a\nspecific pipeline in order to get more details regarding what components are required.\n\nExamples:\n\n```python\n>>> from transformers import pipeline, AutoModelForTokenClassification, AutoTokenizer\n\n>>> # Sentiment analysis pipeline\n>>> analyzer = pipeline(\"sentiment-analysis\")\n\n>>> # Named entity recognition pipeline, passing in a specific model and tokenizer\n>>> model = AutoModelForTokenClassification.from_pretrained(\"dbmdz/bert-large-cased-finetuned-conll03-english\")\n>>> tokenizer = AutoTokenizer.from_pretrained(\"google-bert/bert-base-cased\")\n>>> recognizer = pipeline(\"ner\", model=model, tokenizer=tokenizer)\n```\n\n**Parameters:**", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.pipeline[[transformers.pipeline]]", "char_start": 4177, "char_end": 5137, "token_estimate": 240, "prev_chunk_id": 716, "next_chunk_id": 718, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 718, "text": "task (`str`) : The task defining which pipeline will be returned. Currently accepted tasks are: - `\"audio-classification\"`: will return a [AudioClassificationPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.AudioClassificationPipeline). - `\"automatic-speech-recognition\"`: will return a [AutomaticSpeechRecognitionPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.AutomaticSpeechRecognitionPipeline). - `\"depth-estimation\"`: will return a [DepthEstimationPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.DepthEstimationPipeline). - `\"document-question-answering\"`: will return a [DocumentQuestionAnsweringPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.DocumentQuestionAnsweringPipeline). - `\"feature-extraction\"`: will return a [FeatureExtractionPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.FeatureExtractionPipeline). - `\"fill-mask\"`: will return a [FillMaskPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.FillMaskPipeline):. - `\"image-classification\"`: will return a [ImageClassificationPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.ImageClassificationPipeline). - `\"image-feature-extraction\"`: will return an [ImageFeatureExtractionPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.ImageFeatureExtractionPipeline). - `\"image-segmentation\"`: will return a [ImageSegmentationPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.ImageSegmentationPipeline). - `\"image-text-to-text\"`: will return a [ImageTextToTextPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.ImageTextToTextPipeline). - `\"keypoint-matching\"`: will return a [KeypointMatchingPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.KeypointMatchingPipeline). - `\"mask-generation\"`: will return a [MaskGenerationPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.MaskGenerationPipeline). - `\"object-detection\"`: will return a [ObjectDetectionPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.ObjectDetectionPipeline). - `\"table-question-answering\"`: will return a [TableQuestionAnsweringPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.TableQuestionAnsweringPipeline). - `\"text-classification\"` (alias `\"sentiment-analysis\"` available): will return a [TextClassificationPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.TextClassificationPipeline). - `\"text-generation\"`: will return a [TextGenerationPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.TextGenerationPipeline):. - `\"text-to-audio\"` (alias `\"text-to-speech\"` available): will return a [TextToAudioPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.TextToAudioPipeline):. - `\"token-classification\"` (alias `\"ner\"` available): will return a [TokenClassificationPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.TokenClassificationPipeline). - `\"video-classification\"`: will return a [VideoClassificationPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.VideoClassificationPipeline). - `\"zero-shot-classification\"`: will return a [ZeroShotClassificationPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.ZeroShotClassificationPipeline). - `\"zero-shot-image-classification\"`: will return a [ZeroShotImageClassificationPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.ZeroShotImageClassificationPipeline). - `\"zero-shot-audio-classification\"`: will return a [ZeroShotAudioClassificationPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.ZeroShotAudioClassificationPipeline). - `\"zero-shot-object-detection\"`: will return a [ZeroShotObjectDetectionPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.ZeroShotObjectDetectionPipeline).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.pipeline[[transformers.pipeline]]", "char_start": 5139, "char_end": 9177, "token_estimate": 1009, "prev_chunk_id": 717, "next_chunk_id": 719, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 719, "text": "model (`str` or [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel), *optional*) : The model that will be used by the pipeline to make predictions. This can be a model identifier or an actual instance of a pretrained model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel). If not provided, the default for the `task` will be loaded.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.pipeline[[transformers.pipeline]]", "char_start": 9180, "char_end": 9620, "token_estimate": 110, "prev_chunk_id": 718, "next_chunk_id": 720, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 720, "text": "config (`str` or [PreTrainedConfig](/docs/transformers/v5.6.2/en/main_classes/configuration#transformers.PreTrainedConfig), *optional*) : The configuration that will be used by the pipeline to instantiate the model. This can be a model identifier or an actual pretrained model configuration inheriting from [PreTrainedConfig](/docs/transformers/v5.6.2/en/main_classes/configuration#transformers.PreTrainedConfig). If not provided, the default configuration file for the requested model will be used. That means that if `model` is given, its default configuration will be used. However, if `model` is not supplied, this `task`'s default model's config is used instead.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.pipeline[[transformers.pipeline]]", "char_start": 9622, "char_end": 10290, "token_estimate": 167, "prev_chunk_id": 719, "next_chunk_id": 721, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 721, "text": "tokenizer (`str` or [PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend), *optional*) : The tokenizer that will be used by the pipeline to encode data for the model. This can be a model identifier or an actual pretrained tokenizer inheriting from [PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend). If not provided, the default tokenizer for the given `model` will be loaded (if it is a string). If `model` is not specified or not a string, then the default tokenizer for `config` is loaded (if it is a string). However, if `config` is also not given or not a string, then the default tokenizer for the given `task` will be loaded.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.pipeline[[transformers.pipeline]]", "char_start": 10292, "char_end": 11024, "token_estimate": 183, "prev_chunk_id": 720, "next_chunk_id": 722, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 722, "text": "feature_extractor (`str` or `PreTrainedFeatureExtractor`, *optional*) : The feature extractor that will be used by the pipeline to encode data for the model. This can be a model identifier or an actual pretrained feature extractor inheriting from `PreTrainedFeatureExtractor`. Feature extractors are used for non-NLP models, such as Speech or Vision models as well as multi-modal models. Multi-modal models will also require a tokenizer to be passed. If not provided, the default feature extractor for the given `model` will be loaded (if it is a string). If `model` is not specified or not a string, then the default feature extractor for `config` is loaded (if it is a string). However, if `config` is also not given or not a string, then the default feature extractor for the given `task` will be loaded.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.pipeline[[transformers.pipeline]]", "char_start": 11026, "char_end": 11835, "token_estimate": 202, "prev_chunk_id": 721, "next_chunk_id": 723, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 723, "text": "image_processor (`str` or [BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor), *optional*) : The image processor that will be used by the pipeline to preprocess images for the model. This can be a model identifier or an actual image processor inheriting from [BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor). Image processors are used for Vision models and multi-modal models that require image inputs. Multi-modal models will also require a tokenizer to be passed. If not provided, the default image processor for the given `model` will be loaded (if it is a string). If `model` is not specified or not a string, then the default image processor for `config` is loaded (if it is a string).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.pipeline[[transformers.pipeline]]", "char_start": 11837, "char_end": 12652, "token_estimate": 203, "prev_chunk_id": 722, "next_chunk_id": 724, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 724, "text": "processor (`str` or [ProcessorMixin](/docs/transformers/v5.6.2/en/main_classes/processors#transformers.ProcessorMixin), *optional*) : The processor that will be used by the pipeline to preprocess data for the model. This can be a model identifier or an actual processor inheriting from [ProcessorMixin](/docs/transformers/v5.6.2/en/main_classes/processors#transformers.ProcessorMixin). Processors are used for multi-modal models that require multi-modal inputs, for example, a model that requires both text and image inputs. If not provided, the default processor for the given `model` will be loaded (if it is a string). If `model` is not specified or not a string, then the default processor for `config` is loaded (if it is a string).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.pipeline[[transformers.pipeline]]", "char_start": 12654, "char_end": 13393, "token_estimate": 184, "prev_chunk_id": 723, "next_chunk_id": 725, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 725, "text": "revision (`str`, *optional*, defaults to `\"main\"`) : When passing a task name or a string model identifier: The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git.\n\nuse_fast (`bool`, *optional*, defaults to `True`) : Whether or not to use a Fast tokenizer if possible (a [PreTrainedTokenizerFast](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.TokenizersBackend)).\n\ntoken (`str` or *bool*, *optional*) : The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated when running `hf auth login`.\n\ndevice (`int` or `str` or `torch.device`) : Defines the device (*e.g.*, `\"cpu\"`, `\"cuda:1\"`, `\"mps\"`, or a GPU ordinal rank like `1`) on which this pipeline will be allocated.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.pipeline[[transformers.pipeline]]", "char_start": 13395, "char_end": 14301, "token_estimate": 226, "prev_chunk_id": 724, "next_chunk_id": 726, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 726, "text": "device_map (`str` or `dict[str, Union[int, str, torch.device]`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut). When `accelerate` library is present, set `device_map=\"auto\"` to compute the most optimized `device_map` automatically (see [here](https://huggingface.co/docs/accelerate/main/en/package_reference/big_modeling#accelerate.cpu_offload) for more information). Do not use `device_map` AND `device` at the same time as they will conflict \n\ndtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.pipeline[[transformers.pipeline]]", "char_start": 14303, "char_end": 14981, "token_estimate": 169, "prev_chunk_id": 725, "next_chunk_id": 727, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 727, "text": "trust_remote_code (`bool`, *optional*, defaults to `False`) : Whether or not to allow for custom code defined on the Hub in their own modeling, configuration, tokenization or even pipeline files. This option should only be set to `True` for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine.\n\nmodel_kwargs (`dict[str, Any]`, *optional*) : Additional dictionary of keyword arguments passed along to the model's `from_pretrained(..., **model_kwargs)` function.\n\nkwargs (`dict[str, Any]`, *optional*) : Additional keyword arguments passed along to the specific pipeline init (see the documentation for the corresponding pipeline class for possible values).\n\n**Returns:**\n\n`[Pipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.Pipeline)`\n\nA suitable pipeline for the task.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.pipeline[[transformers.pipeline]]", "char_start": 14983, "char_end": 15849, "token_estimate": 216, "prev_chunk_id": 726, "next_chunk_id": 728, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 728, "text": "## Pipeline batching\n\nAll pipelines can use batching. This will work\nwhenever the pipeline uses its streaming ability (so when passing lists or `Dataset` or `generator`).\n\n```python\nfrom transformers import pipeline\nfrom transformers.pipelines.pt_utils import KeyDataset\nimport datasets\n\ndataset = datasets.load_dataset(\"imdb\", name=\"plain_text\", split=\"unsupervised\")\npipe = pipeline(\"text-classification\", device=0)\nfor out in pipe(KeyDataset(dataset, \"text\"), batch_size=8, truncation=\"only_first\"):\n print(out)\n # [{'label': 'POSITIVE', 'score': 0.9998743534088135}]\n # Exactly the same output as before, but the content are passed\n # as batches to the model\n```\n\nHowever, this is not automatically a win for performance. It can be either a 10x speedup or 5x slowdown depending\non hardware, data and the actual model being used.\n\nExample where it's mostly a speedup:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "Pipeline batching", "char_start": 15851, "char_end": 16733, "token_estimate": 220, "prev_chunk_id": 727, "next_chunk_id": 729, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 729, "text": "```python\nfrom transformers import pipeline\nfrom torch.utils.data import Dataset\nfrom tqdm.auto import tqdm\n\npipe = pipeline(\"text-classification\", device=0)\n\nclass MyDataset(Dataset):\n def __len__(self):\n return 5000\n\n def __getitem__(self, i):\n return \"This is a test\"\n\ndataset = MyDataset()\n\nfor batch_size in [1, 8, 64, 256]:\n print(\"-\" * 30)\n print(f\"Streaming batch_size={batch_size}\")\n for out in tqdm(pipe(dataset, batch_size=batch_size), total=len(dataset)):\n pass\n```\n\n```text", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "Pipeline batching", "char_start": 16735, "char_end": 17257, "token_estimate": 130, "prev_chunk_id": 728, "next_chunk_id": 730, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 730, "text": "# On GTX 970\n------------------------------\nStreaming no batching\n100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5000/5000 [00:26\n for out in tqdm(pipe(dataset, batch_size=256), total=len(dataset)):\n....\n q = q / math.sqrt(dim_per_head) # (bs, n_heads, q_length, dim_per_head)\nRuntimeError: CUDA out of memory. Tried to allocate 376.00 MiB (GPU 0; 3.95 GiB total capacity; 1.72 GiB already allocated; 354.88 MiB free; 2.46 GiB reserved in total by PyTorch)\n```\n\nThere are no good (general) solutions for this problem, and your mileage may vary depending on your use cases. Rule of\nthumb:\n\nFor users, a rule of thumb is:\n\n- **Measure performance on your load, with your hardware. Measure, measure, and keep measuring. Real numbers are the\n only way to go.**\n- If you are latency constrained (live product doing inference), don't batch.\n- If you are using CPU, don't batch.\n- If you are using throughput (you want to run your model on a bunch of static data), on GPU, then:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "On GTX 970", "char_start": 17258, "char_end": 18267, "token_estimate": 252, "prev_chunk_id": 729, "next_chunk_id": 731, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 731, "text": "- If you have no clue about the size of the sequence_length (\"natural\" data), by default don't batch, measure and\n try tentatively to add it, add OOM checks to recover when it will fail (and it will at some point if you don't\n control the sequence_length.)\n - If your sequence_length is super regular, then batching is more likely to be VERY interesting, measure and push\n it until you get OOMs.\n - The larger the GPU the more likely batching is going to be more interesting\n- As soon as you enable batching, make sure you can handle OOMs nicely.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "On GTX 970", "char_start": 18271, "char_end": 18828, "token_estimate": 139, "prev_chunk_id": 730, "next_chunk_id": 732, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 732, "text": "## Pipeline chunk batching\n\n`zero-shot-classification` and `question-answering` are slightly specific in the sense, that a single input might yield\nmultiple forward pass of a model. Under normal circumstances, this would yield issues with `batch_size` argument.\n\nIn order to circumvent this issue, both of these pipelines are a bit specific, they are `ChunkPipeline` instead of\nregular `Pipeline`. In short:\n\n```python\npreprocessed = pipe.preprocess(inputs)\nmodel_outputs = pipe.forward(preprocessed)\noutputs = pipe.postprocess(model_outputs)\n```\n\nNow becomes:\n\n```python\nall_model_outputs = []\nfor preprocessed in pipe.preprocess(inputs):\n model_outputs = pipe.forward(preprocessed)\n all_model_outputs.append(model_outputs)\noutputs = pipe.postprocess(all_model_outputs)\n```\n\nThis should be very transparent to your code because the pipelines are used in\nthe same way.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "Pipeline chunk batching", "char_start": 18830, "char_end": 19704, "token_estimate": 218, "prev_chunk_id": 731, "next_chunk_id": 733, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 733, "text": "This is a simplified view, since the pipeline can handle automatically the batch to ! Meaning you don't have to care\nabout how many forward passes you inputs are actually going to trigger, you can optimize the `batch_size`\nindependently of the inputs. The caveats from the previous section still apply.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "Pipeline chunk batching", "char_start": 19706, "char_end": 20008, "token_estimate": 75, "prev_chunk_id": 732, "next_chunk_id": 734, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 734, "text": "## Pipeline FP16 inference\n\nModels can be run in FP16 which can be significantly faster on GPU while saving memory. Most models will not suffer noticeable performance loss from this. The larger the model, the less likely that it will.\n\nTo enable FP16 inference, you can simply pass `dtype=torch.float16` or `dtype='float16'` to the pipeline constructor. Note that this only works for models with a PyTorch backend. Your inputs will be converted to FP16 internally.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "Pipeline FP16 inference", "char_start": 20010, "char_end": 20474, "token_estimate": 116, "prev_chunk_id": 733, "next_chunk_id": 735, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 735, "text": "## Pipeline custom code\n\nIf you want to override a specific pipeline.\n\nDon't hesitate to create an issue for your task at hand, the goal of the pipeline is to be easy to use and support most\ncases, so `transformers` could maybe support your use case.\n\nIf you want to try simply you can:\n\n- Subclass your pipeline of choice\n\n```python\nclass MyPipeline(TextClassificationPipeline):\n def postprocess():\n # Your code goes here\n scores = scores * 100\n # And here\n\nmy_pipeline = MyPipeline(model=model, tokenizer=tokenizer, ...)", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "Pipeline custom code", "char_start": 20476, "char_end": 21022, "token_estimate": 136, "prev_chunk_id": 734, "next_chunk_id": 736, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 736, "text": "# or if you use *pipeline* function, then:\nmy_pipeline = pipeline(model=\"xxxx\", pipeline_class=MyPipeline)\n```\n\nThat should enable you to do all the custom code you want.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "or if you use *pipeline* function, then:", "char_start": 21023, "char_end": 21193, "token_estimate": 42, "prev_chunk_id": 735, "next_chunk_id": 737, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 737, "text": "## Implementing a pipeline\n\n[Implementing a new pipeline](../add_new_pipeline)", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "Implementing a pipeline", "char_start": 21195, "char_end": 21273, "token_estimate": 19, "prev_chunk_id": 736, "next_chunk_id": 738, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 738, "text": "## Audio\n\nPipelines available for audio tasks include the following.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "Audio", "char_start": 21275, "char_end": 21343, "token_estimate": 17, "prev_chunk_id": 737, "next_chunk_id": 739, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 739, "text": "### AudioClassificationPipeline[[transformers.AudioClassificationPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "AudioClassificationPipeline[[transformers.AudioClassificationPipeline]]", "char_start": 21345, "char_end": 21420, "token_estimate": 18, "prev_chunk_id": 738, "next_chunk_id": 740, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 740, "text": "#### transformers.AudioClassificationPipeline[[transformers.AudioClassificationPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/audio_classification.py#L67)\n\nAudio classification pipeline using any `AutoModelForAudioClassification`. This pipeline predicts the class of a\nraw waveform or an audio file. In case of an audio file, ffmpeg should be installed to support multiple audio\nformats.\n\nExample:\n\n```python\n>>> from transformers import pipeline\n\n>>> classifier = pipeline(model=\"superb/wav2vec2-base-superb-ks\")\n>>> classifier(\"https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac\")\n[{'score': 0.997, 'label': '_unknown_'}, {'score': 0.002, 'label': 'left'}, {'score': 0.0, 'label': 'yes'}, {'score': 0.0, 'label': 'down'}, {'score': 0.0, 'label': 'stop'}]\n```\n\nLearn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AudioClassificationPipeline[[transformers.AudioClassificationPipeline]]", "char_start": 21422, "char_end": 22355, "token_estimate": 233, "prev_chunk_id": 739, "next_chunk_id": 741, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 741, "text": "This pipeline can currently be loaded from [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline) using the following task identifier:\n`\"audio-classification\"`.\n\nSee the list of available models on\n[huggingface.co/models](https://huggingface.co/models?filter=audio-classification).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AudioClassificationPipeline[[transformers.AudioClassificationPipeline]]", "char_start": 22357, "char_end": 22671, "token_estimate": 78, "prev_chunk_id": 740, "next_chunk_id": 742, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 742, "text": "__call__transformers.AudioClassificationPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/audio_classification.py#L109[{\"name\": \"inputs\", \"val\": \": numpy.ndarray | bytes | str | dict\"}, {\"name\": \"**kwargs\", \"val\": \": typing.Any\"}]- **inputs** (`np.ndarray` or `bytes` or `str` or `dict`) --\n The inputs is either :\n - `str` that is the filename of the audio file, the file will be read at the correct sampling rate\n to get the waveform using *ffmpeg*. This requires *ffmpeg* to be installed on the system.\n - `bytes` it is supposed to be the content of an audio file and is interpreted by *ffmpeg* in the\n same way.\n - (`np.ndarray` of shape (n, ) of type `np.float32` or `np.float64`)\n Raw audio at the correct sampling rate (no further check will be done)\n - `dict` form can be used to pass raw audio sampled at arbitrary `sampling_rate` and let this\n pipeline do the resampling. The dict must be either be in the format `{\"sampling_rate\": int,\n \"raw\": np.array}`, or `{\"sampling_rate\": int, \"array\": np.array}`, where the key `\"raw\"` or\n `\"array\"` is used to denote the raw audio waveform.\n- **top_k** (`int`, *optional*, defaults to None) --\n The number of top labels that will be returned by the pipeline. If the provided number is `None` or\n higher than the number of labels available in the model configuration, it will default to the number of\n labels.\n- **function_to_apply** (`str`, *optional*, defaults to \"softmax\") --\n The function to apply to the model output. By default, the pipeline will apply the softmax function to\n the output of the model. Valid options: [\"softmax\", \"sigmoid\", \"none\"]. Note that passing Python's\n built-in `None` will default to \"softmax\", so you need to pass the string \"none\" to disable any\n post-processing.0A list of `dict` with the following keys- **label** (`str`) -- The label predicted.\n- **score** (`float`) -- The corresponding probability.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AudioClassificationPipeline[[transformers.AudioClassificationPipeline]]", "char_start": 22673, "char_end": 24642, "token_estimate": 492, "prev_chunk_id": 741, "next_chunk_id": 743, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 743, "text": "Classify the sequence(s) given as inputs. See the [AutomaticSpeechRecognitionPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.AutomaticSpeechRecognitionPipeline) documentation for more\ninformation.\n\n**Parameters:**\n\nmodel ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).\n\nfeature_extractor ([SequenceFeatureExtractor](/docs/transformers/v5.6.2/en/main_classes/feature_extractor#transformers.SequenceFeatureExtractor)) : The feature extractor that will be used by the pipeline to encode data for the model. This object inherits from [SequenceFeatureExtractor](/docs/transformers/v5.6.2/en/main_classes/feature_extractor#transformers.SequenceFeatureExtractor).\n\ntask (`str`, defaults to `\"\"`) : A task-identifier for the pipeline.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AudioClassificationPipeline[[transformers.AudioClassificationPipeline]]", "char_start": 24644, "char_end": 25652, "token_estimate": 252, "prev_chunk_id": 742, "next_chunk_id": 744, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 744, "text": "num_workers (`int`, *optional*, defaults to 8) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used.\n\nbatch_size (`int`, *optional*, defaults to 1) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .\n\nargs_parser ([ArgumentHandler](/docs/transformers/v5.6.2/en/internal/pipelines_utils#transformers.pipelines.ArgumentHandler), *optional*) : Reference to the object in charge of parsing supplied pipeline parameters.\n\ndevice (`int`, *optional*, defaults to -1) : Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AudioClassificationPipeline[[transformers.AudioClassificationPipeline]]", "char_start": 25654, "char_end": 26622, "token_estimate": 242, "prev_chunk_id": 743, "next_chunk_id": 745, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 745, "text": "dtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`)\n\nbinary_output (`bool`, *optional*, defaults to `False`) : Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text.\n\n**Returns:**\n\n`A list of `dict` with the following keys`\n\n- **label** (`str`) -- The label predicted.\n- **score** (`float`) -- The corresponding probability.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AudioClassificationPipeline[[transformers.AudioClassificationPipeline]]", "char_start": 26624, "char_end": 27175, "token_estimate": 137, "prev_chunk_id": 744, "next_chunk_id": 746, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 746, "text": "### AutomaticSpeechRecognitionPipeline[[transformers.AutomaticSpeechRecognitionPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "AutomaticSpeechRecognitionPipeline[[transformers.AutomaticSpeechRecognitionPipeline]]", "char_start": 27177, "char_end": 27266, "token_estimate": 22, "prev_chunk_id": 745, "next_chunk_id": 747, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 747, "text": "#### transformers.AutomaticSpeechRecognitionPipeline[[transformers.AutomaticSpeechRecognitionPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/automatic_speech_recognition.py#L112)\n\nPipeline that aims at extracting spoken text contained within some audio.\n\nThe input can be either a raw waveform or a audio file. In case of the audio file, ffmpeg should be installed for\nto support multiple audio formats\n\nUnless the model you're using explicitly sets these generation parameters in its configuration files\n(`generation_config.json`), the following default values will be used:\n- max_new_tokens: 256\n- num_beams: 5\n\nExample:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AutomaticSpeechRecognitionPipeline[[transformers.AutomaticSpeechRecognitionPipeline]]", "char_start": 27268, "char_end": 27946, "token_estimate": 169, "prev_chunk_id": 746, "next_chunk_id": 748, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 748, "text": "```python\n>>> from transformers import pipeline\n\n>>> transcriber = pipeline(model=\"openai/whisper-base\")\n>>> transcriber(\"https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac\")\n{'text': ' He hoped there would be stew for dinner, turnips and carrots and bruised potatoes and fat mutton pieces to be ladled out in thick, peppered flour-fatten sauce.'}\n```\n\nLearn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AutomaticSpeechRecognitionPipeline[[transformers.AutomaticSpeechRecognitionPipeline]]", "char_start": 27948, "char_end": 28415, "token_estimate": 116, "prev_chunk_id": 747, "next_chunk_id": 749, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 749, "text": "__call__transformers.AutomaticSpeechRecognitionPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/automatic_speech_recognition.py#L187[{\"name\": \"inputs\", \"val\": \": numpy.ndarray | bytes | str | dict\"}, {\"name\": \"**kwargs\", \"val\": \": typing.Any\"}]- **inputs** (`np.ndarray` or `bytes` or `str` or `dict`) --\n The inputs is either :\n - `str` that is either the filename of a local audio file, or a public URL address to download the\n audio file. The file will be read at the correct sampling rate to get the waveform using\n *ffmpeg*. This requires *ffmpeg* to be installed on the system.\n - `bytes` it is supposed to be the content of an audio file and is interpreted by *ffmpeg* in the\n same way.\n - (`np.ndarray` of shape (n, ) of type `np.float32` or `np.float64`)\n Raw audio at the correct sampling rate (no further check will be done)\n - `dict` form can be used to pass raw audio sampled at arbitrary `sampling_rate` and let this\n pipeline do the resampling. The dict must be in the format `{\"sampling_rate\": int, \"raw\":\n np.array}` with optionally a `\"stride\": (left: int, right: int)` than can ask the pipeline to\n treat the first `left` samples and last `right` samples to be ignored in decoding (but used at\n inference to provide more context to the model). Only use `stride` with CTC models.\n- **return_timestamps** (*optional*, `str` or `bool`) --\n Only available for pure CTC models (Wav2Vec2, HuBERT, etc) and the Whisper model. Not available for\n other sequence-to-sequence models.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AutomaticSpeechRecognitionPipeline[[transformers.AutomaticSpeechRecognitionPipeline]]", "char_start": 28417, "char_end": 29990, "token_estimate": 393, "prev_chunk_id": 748, "next_chunk_id": 750, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 750, "text": "For CTC models, timestamps can take one of two formats:\n - `\"char\"`: the pipeline will return timestamps along the text for every character in the text. For\n instance, if you get `[{\"text\": \"h\", \"timestamp\": (0.5, 0.6)}, {\"text\": \"i\", \"timestamp\": (0.7,\n 0.9)}]`, then it means the model predicts that the letter \"h\" was spoken after `0.5` and before\n `0.6` seconds.\n - `\"word\"`: the pipeline will return timestamps along the text for every word in the text. For\n instance, if you get `[{\"text\": \"hi \", \"timestamp\": (0.5, 0.9)}, {\"text\": \"there\", \"timestamp\":\n (1.0, 1.5)}]`, then it means the model predicts that the word \"hi\" was spoken after `0.5` and\n before `0.9` seconds.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AutomaticSpeechRecognitionPipeline[[transformers.AutomaticSpeechRecognitionPipeline]]", "char_start": 29994, "char_end": 30691, "token_estimate": 174, "prev_chunk_id": 749, "next_chunk_id": 751, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 751, "text": "For the Whisper model, timestamps can take one of two formats:\n - `\"word\"`: same as above for word-level CTC timestamps. Word-level timestamps are predicted\n through the *dynamic-time warping (DTW)* algorithm, an approximation to word-level timestamps\n by inspecting the cross-attention weights.\n - `True`: the pipeline will return timestamps along the text for *segments* of words in the text.\n For instance, if you get `[{\"text\": \" Hi there!\", \"timestamp\": (0.5, 1.5)}]`, then it means the\n model predicts that the segment \"Hi there!\" was spoken after `0.5` and before `1.5` seconds.\n Note that a segment of text refers to a sequence of one or more words, rather than individual\n words as with word-level timestamps.\n- **generate_kwargs** (`dict`, *optional*) --\n The dictionary of ad-hoc parametrization of `generate_config` to be used for the generation call. For a\n complete overview of generate, check the [following\n guide](https://huggingface.co/docs/transformers/en/main_classes/text_generation).0`Dict`A dictionary with the following keys:\n- **text** (`str`): The recognized text.\n- **chunks** (*optional(, `list[Dict]`)\n When using `return_timestamps`, the `chunks` will become a list containing all the various text\n chunks identified by the model, *e.g.* `[{\"text\": \"hi \", \"timestamp\": (0.5, 0.9)}, {\"text\":\n \"there\", \"timestamp\": (1.0, 1.5)}]`. The original full text can roughly be recovered by doing\n `\"\".join(chunk[\"text\"] for chunk in output[\"chunks\"])`.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AutomaticSpeechRecognitionPipeline[[transformers.AutomaticSpeechRecognitionPipeline]]", "char_start": 30695, "char_end": 32194, "token_estimate": 375, "prev_chunk_id": 750, "next_chunk_id": 752, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 752, "text": "Transcribe the audio sequence(s) given as inputs to text. See the [AutomaticSpeechRecognitionPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.AutomaticSpeechRecognitionPipeline)\ndocumentation for more information.\n\n**Parameters:**\n\nmodel ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).\n\nfeature_extractor ([SequenceFeatureExtractor](/docs/transformers/v5.6.2/en/main_classes/feature_extractor#transformers.SequenceFeatureExtractor), *optional*) : The feature extractor that will be used by the pipeline to encode waveform for the model.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AutomaticSpeechRecognitionPipeline[[transformers.AutomaticSpeechRecognitionPipeline]]", "char_start": 32196, "char_end": 33013, "token_estimate": 204, "prev_chunk_id": 751, "next_chunk_id": 753, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 753, "text": "tokenizer ([PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend), *optional*) : The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from [PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend).\n\ndecoder (`pyctcdecode.BeamSearchDecoderCTC`, *optional*) : [PyCTCDecode's BeamSearchDecoderCTC](https://github.com/kensho-technologies/pyctcdecode/blob/2fd33dc37c4111417e08d89ccd23d28e9b308d19/pyctcdecode/decoder.py#L180) can be passed for language model boosted decoding. See [Wav2Vec2ProcessorWithLM](/docs/transformers/v5.6.2/en/model_doc/wav2vec2#transformers.Wav2Vec2ProcessorWithLM) for more information.\n\ndevice (Union[`int`, `torch.device`], *optional*) : Device ordinal for CPU/GPU supports. Setting this to `None` will leverage CPU, a positive will run the model on the associated CUDA device id.\n\n**Returns:**\n\n``Dict``", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AutomaticSpeechRecognitionPipeline[[transformers.AutomaticSpeechRecognitionPipeline]]", "char_start": 33015, "char_end": 33981, "token_estimate": 241, "prev_chunk_id": 752, "next_chunk_id": 754, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 754, "text": "A dictionary with the following keys:\n- **text** (`str`): The recognized text.\n- **chunks** (*optional(, `list[Dict]`)\n When using `return_timestamps`, the `chunks` will become a list containing all the various text\n chunks identified by the model, *e.g.* `[{\"text\": \"hi \", \"timestamp\": (0.5, 0.9)}, {\"text\":\n \"there\", \"timestamp\": (1.0, 1.5)}]`. The original full text can roughly be recovered by doing\n `\"\".join(chunk[\"text\"] for chunk in output[\"chunks\"])`.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AutomaticSpeechRecognitionPipeline[[transformers.AutomaticSpeechRecognitionPipeline]]", "char_start": 31730, "char_end": 32194, "token_estimate": 116, "prev_chunk_id": 753, "next_chunk_id": 755, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 755, "text": "### TextToAudioPipeline[[transformers.TextToAudioPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "TextToAudioPipeline[[transformers.TextToAudioPipeline]]", "char_start": 34449, "char_end": 34508, "token_estimate": 14, "prev_chunk_id": 754, "next_chunk_id": 756, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 756, "text": "#### transformers.TextToAudioPipeline[[transformers.TextToAudioPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/text_to_audio.py#L45)\n\nText-to-audio generation pipeline using any `AutoModelForTextToWaveform` or `AutoModelForTextToSpectrogram`. This\npipeline generates an audio file from an input text and optional other conditional inputs.\n\nUnless the model you're using explicitly sets these generation parameters in its configuration files\n(`generation_config.json`), the following default values will be used:\n- max_new_tokens: 256\n\nExample:\n\n```python\n>>> from transformers import pipeline\n\n>>> pipe = pipeline(model=\"suno/bark-small\")\n>>> output = pipe(\"Hey it's HuggingFace on the phone!\")\n\n>>> audio = output[\"audio\"]\n>>> sampling_rate = output[\"sampling_rate\"]\n```\n\nLearn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TextToAudioPipeline[[transformers.TextToAudioPipeline]]", "char_start": 34510, "char_end": 35435, "token_estimate": 231, "prev_chunk_id": 755, "next_chunk_id": 757, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 757, "text": "You can specify parameters passed to the model by using `TextToAudioPipeline.__call__.forward_params` or\n`TextToAudioPipeline.__call__.generate_kwargs`.\n\nExample:\n\n```python\n>>> from transformers import pipeline\n\n>>> music_generator = pipeline(task=\"text-to-audio\", model=\"facebook/musicgen-small\")\n\n>>> # diversify the music generation by adding randomness with a high temperature and set a maximum music length\n>>> generate_kwargs = {\n... \"do_sample\": True,\n... \"temperature\": 0.7,\n... \"max_new_tokens\": 35,\n... }\n\n>>> outputs = music_generator(\"Techno music with high melodic riffs\", generate_kwargs=generate_kwargs)\n```\n\nThis pipeline can currently be loaded from [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline) using the following task identifiers: `\"text-to-speech\"` or\n`\"text-to-audio\"`.\n\nSee the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=text-to-speech).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TextToAudioPipeline[[transformers.TextToAudioPipeline]]", "char_start": 35437, "char_end": 36398, "token_estimate": 240, "prev_chunk_id": 756, "next_chunk_id": 758, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 758, "text": "__call__transformers.TextToAudioPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/text_to_audio.py#L243[{\"name\": \"text_inputs\", \"val\": \"\"}, {\"name\": \"**forward_params\", \"val\": \"\"}]- **text_inputs** (`str`, `list[str]`, `ChatType`, or `list[ChatType]`) --\n One or several texts to generate. If strings or a list of string are passed, this pipeline will\n generate the corresponding text. Alternatively, a \"chat\", in the form of a list of dicts with \"role\"\n and \"content\" keys, can be passed, or a list of such chats. When chats are passed, the model's chat\n template will be used to format them before passing them to the model.\n- **forward_params** (`dict`, *optional*) --\n Parameters passed to the model generation/forward method. `forward_params` are always passed to the\n underlying model.\n- **generate_kwargs** (`dict`, *optional*) --\n The dictionary of ad-hoc parametrization of `generate_config` to be used for the generation call. For a\n complete overview of generate, check the [following\n guide](https://huggingface.co/docs/transformers/en/main_classes/text_generation). `generate_kwargs` are\n only passed to the underlying model if the latter is a generative model.0`AudioOutput` or a list of `AudioOutput`, which is a `TypedDict` with two keys- **audio** (`np.ndarray` of shape `(nb_channels, audio_length)`) -- The generated audio waveform.\n- **sampling_rate** (`int`) -- The sampling rate of the generated audio waveform.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TextToAudioPipeline[[transformers.TextToAudioPipeline]]", "char_start": 36400, "char_end": 37893, "token_estimate": 373, "prev_chunk_id": 757, "next_chunk_id": 759, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 759, "text": "Generates speech/audio from the inputs. See the [TextToAudioPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.TextToAudioPipeline) documentation for more information.\n\n**Parameters:**\n\ntext_inputs (`str`, `list[str]`, `ChatType`, or `list[ChatType]`) : One or several texts to generate. If strings or a list of string are passed, this pipeline will generate the corresponding text. Alternatively, a \"chat\", in the form of a list of dicts with \"role\" and \"content\" keys, can be passed, or a list of such chats. When chats are passed, the model's chat template will be used to format them before passing them to the model.\n\nforward_params (`dict`, *optional*) : Parameters passed to the model generation/forward method. `forward_params` are always passed to the underlying model.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TextToAudioPipeline[[transformers.TextToAudioPipeline]]", "char_start": 37895, "char_end": 38697, "token_estimate": 200, "prev_chunk_id": 758, "next_chunk_id": 760, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 760, "text": "generate_kwargs (`dict`, *optional*) : The dictionary of ad-hoc parametrization of `generate_config` to be used for the generation call. For a complete overview of generate, check the [following guide](https://huggingface.co/docs/transformers/en/main_classes/text_generation). `generate_kwargs` are only passed to the underlying model if the latter is a generative model.\n\n**Returns:**\n\n``AudioOutput` or a list of `AudioOutput`, which is a `TypedDict` with two keys`\n\n- **audio** (`np.ndarray` of shape `(nb_channels, audio_length)`) -- The generated audio waveform.\n- **sampling_rate** (`int`) -- The sampling rate of the generated audio waveform.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TextToAudioPipeline[[transformers.TextToAudioPipeline]]", "char_start": 38699, "char_end": 39348, "token_estimate": 162, "prev_chunk_id": 759, "next_chunk_id": 761, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 761, "text": "### ZeroShotAudioClassificationPipeline[[transformers.ZeroShotAudioClassificationPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "ZeroShotAudioClassificationPipeline[[transformers.ZeroShotAudioClassificationPipeline]]", "char_start": 39350, "char_end": 39441, "token_estimate": 22, "prev_chunk_id": 760, "next_chunk_id": 762, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 762, "text": "#### transformers.ZeroShotAudioClassificationPipeline[[transformers.ZeroShotAudioClassificationPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/zero_shot_audio_classification.py#L32)\n\nZero shot audio classification pipeline using `ClapModel`. This pipeline predicts the class of an audio when you\nprovide an audio and a set of `candidate_labels`.\n\nThe default `hypothesis_template` is : `\"This is a sound of {}.\"`. Make sure you update it for your usage.\n\nExample:\n```python\n>>> from transformers import pipeline\n>>> from datasets import load_dataset\n\n>>> dataset = load_dataset(\"ashraq/esc50\")\n>>> audio = next(iter(dataset[\"train\"][\"audio\"]))[\"array\"]\n>>> classifier = pipeline(task=\"zero-shot-audio-classification\", model=\"laion/clap-htsat-unfused\")\n>>> classifier(audio, candidate_labels=[\"Sound of a dog\", \"Sound of vacuum cleaner\"])\n[{'score': 0.9996, 'label': 'Sound of a dog'}, {'score': 0.0004, 'label': 'Sound of vacuum cleaner'}]\n```", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotAudioClassificationPipeline[[transformers.ZeroShotAudioClassificationPipeline]]", "char_start": 39443, "char_end": 40442, "token_estimate": 249, "prev_chunk_id": 761, "next_chunk_id": 763, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 763, "text": "Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) This audio\nclassification pipeline can currently be loaded from [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline) using the following task identifier:\n`\"zero-shot-audio-classification\"`. See the list of available models on\n[huggingface.co/models](https://huggingface.co/models?filter=zero-shot-audio-classification).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotAudioClassificationPipeline[[transformers.ZeroShotAudioClassificationPipeline]]", "char_start": 40444, "char_end": 40895, "token_estimate": 112, "prev_chunk_id": 762, "next_chunk_id": 764, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 764, "text": "__call__transformers.ZeroShotAudioClassificationPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/zero_shot_audio_classification.py#L70[{\"name\": \"audios\", \"val\": \": numpy.ndarray | bytes | str | dict\"}, {\"name\": \"**kwargs\", \"val\": \": typing.Any\"}]- **audios** (`str`, `list[str]`, `np.array` or `list[np.array]`) --\n The pipeline handles three types of inputs:\n - A string containing a http link pointing to an audio\n - A string containing a local path to an audio\n - An audio loaded in numpy\n- **candidate_labels** (`list[str]`) --\n The candidate labels for this audio. They will be formatted using *hypothesis_template*.\n- **hypothesis_template** (`str`, *optional*, defaults to `\"This is a sound of {}\"`) --\n The format used in conjunction with *candidate_labels* to attempt the audio classification by\n replacing the placeholder with the candidate_labels. Pass \"{}\" if *candidate_labels* are\n already formatted.0A list of dictionaries containing one entry per proposed label. Each dictionary contains the\nfollowing keys:\n- **label** (`str`) -- One of the suggested *candidate_labels*.\n- **score** (`float`) -- The score attributed by the model to that label. It is a value between\n 0 and 1, computed as the `softmax` of `logits_per_audio`.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotAudioClassificationPipeline[[transformers.ZeroShotAudioClassificationPipeline]]", "char_start": 40897, "char_end": 42199, "token_estimate": 325, "prev_chunk_id": 763, "next_chunk_id": 765, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 765, "text": "Assign labels to the audio(s) passed as inputs.\n\n**Parameters:**\n\nmodel ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).\n\ntokenizer ([PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend)) : The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from [PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotAudioClassificationPipeline[[transformers.ZeroShotAudioClassificationPipeline]]", "char_start": 42201, "char_end": 42899, "token_estimate": 174, "prev_chunk_id": 764, "next_chunk_id": 766, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 766, "text": "feature_extractor ([SequenceFeatureExtractor](/docs/transformers/v5.6.2/en/main_classes/feature_extractor#transformers.SequenceFeatureExtractor)) : The feature extractor that will be used by the pipeline to encode data for the model. This object inherits from [SequenceFeatureExtractor](/docs/transformers/v5.6.2/en/main_classes/feature_extractor#transformers.SequenceFeatureExtractor).\n\ntask (`str`, defaults to `\"\"`) : A task-identifier for the pipeline.\n\nnum_workers (`int`, *optional*, defaults to 8) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used.\n\nbatch_size (`int`, *optional*, defaults to 1) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotAudioClassificationPipeline[[transformers.ZeroShotAudioClassificationPipeline]]", "char_start": 25196, "char_end": 26171, "token_estimate": 243, "prev_chunk_id": 765, "next_chunk_id": 767, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 767, "text": "args_parser ([ArgumentHandler](/docs/transformers/v5.6.2/en/internal/pipelines_utils#transformers.pipelines.ArgumentHandler), *optional*) : Reference to the object in charge of parsing supplied pipeline parameters.\n\ndevice (`int`, *optional*, defaults to -1) : Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too\n\ndtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`)\n\nbinary_output (`bool`, *optional*, defaults to `False`) : Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text.\n\n**Returns:**", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotAudioClassificationPipeline[[transformers.ZeroShotAudioClassificationPipeline]]", "char_start": 26173, "char_end": 27030, "token_estimate": 214, "prev_chunk_id": 766, "next_chunk_id": 768, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 768, "text": "A list of dictionaries containing one entry per proposed label. Each dictionary contains the\nfollowing keys:\n- **label** (`str`) -- One of the suggested *candidate_labels*.\n- **score** (`float`) -- The score attributed by the model to that label. It is a value between\n 0 and 1, computed as the `softmax` of `logits_per_audio`.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotAudioClassificationPipeline[[transformers.ZeroShotAudioClassificationPipeline]]", "char_start": 41871, "char_end": 42199, "token_estimate": 82, "prev_chunk_id": 767, "next_chunk_id": 769, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 769, "text": "## Computer vision\n\nPipelines available for computer vision tasks include the following.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "Computer vision", "char_start": 45067, "char_end": 45155, "token_estimate": 22, "prev_chunk_id": 768, "next_chunk_id": 770, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 770, "text": "### DepthEstimationPipeline[[transformers.DepthEstimationPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "DepthEstimationPipeline[[transformers.DepthEstimationPipeline]]", "char_start": 45157, "char_end": 45224, "token_estimate": 16, "prev_chunk_id": 769, "next_chunk_id": 771, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 771, "text": "#### transformers.DepthEstimationPipeline[[transformers.DepthEstimationPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/depth_estimation.py#L25)\n\nDepth estimation pipeline using any `AutoModelForDepthEstimation`. This pipeline predicts the depth of an image.\n\nExample:\n\n```python\n>>> from transformers import pipeline\n\n>>> depth_estimator = pipeline(task=\"depth-estimation\", model=\"LiheYoung/depth-anything-base-hf\")\n>>> output = depth_estimator(\"http://images.cocodataset.org/val2017/000000039769.jpg\")\n>>> # This is a tensor with the values being the depth expressed in meters for each pixel\n>>> output[\"predicted_depth\"].shape\ntorch.Size([1, 384, 384])\n```\n\nLearn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)\n\nThis depth estimation pipeline can currently be loaded from [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline) using the following task identifier:\n`\"depth-estimation\"`.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.DepthEstimationPipeline[[transformers.DepthEstimationPipeline]]", "char_start": 45226, "char_end": 46246, "token_estimate": 255, "prev_chunk_id": 770, "next_chunk_id": 772, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 772, "text": "See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=depth-estimation).\n\n__call__transformers.DepthEstimationPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/depth_estimation.py#L66[{\"name\": \"inputs\", \"val\": \": typing.Union[str, list[str], ForwardRef('Image.Image'), list['Image.Image']]\"}, {\"name\": \"**kwargs\", \"val\": \": typing.Any\"}]- **inputs** (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`) --\n The pipeline handles three types of images:\n\n - A string containing a http link pointing to an image\n - A string containing a local path to an image\n - An image loaded in PIL directly", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.DepthEstimationPipeline[[transformers.DepthEstimationPipeline]]", "char_start": 46248, "char_end": 46937, "token_estimate": 172, "prev_chunk_id": 771, "next_chunk_id": 773, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 773, "text": "The pipeline accepts either a single image or a batch of images, which must then be passed as a string.\n Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL\n images.\n- **parameters** (`Dict`, *optional*) --\n A dictionary of argument names to parameter values, to control pipeline behaviour.\n The only parameter available right now is `timeout`, which is the length of time, in seconds,\n that the pipeline should wait before giving up on trying to download an image.\n- **timeout** (`float`, *optional*, defaults to None) --\n The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and\n the call may block forever.0A dictionary or a list of dictionaries containing result. If the input is a single image, will return a\ndictionary, if the input is a list of several images, will return a list of dictionaries corresponding to\nthe images.\n\nThe dictionaries contain the following keys:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.DepthEstimationPipeline[[transformers.DepthEstimationPipeline]]", "char_start": 46941, "char_end": 47920, "token_estimate": 244, "prev_chunk_id": 772, "next_chunk_id": 774, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 774, "text": "- **predicted_depth** (`torch.Tensor`) -- The predicted depth by the model as a `torch.Tensor`.\n- **depth** (`PIL.Image`) -- The predicted depth by the model as a `PIL.Image`.\n\nPredict the depth(s) of the image(s) passed as inputs.\n\n**Parameters:**\n\nmodel ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).\n\nimage_processor ([BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor)) : The image processor that will be used by the pipeline to encode data for the model. This object inherits from [BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor).\n\ntask (`str`, defaults to `\"\"`) : A task-identifier for the pipeline.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.DepthEstimationPipeline[[transformers.DepthEstimationPipeline]]", "char_start": 47922, "char_end": 48906, "token_estimate": 246, "prev_chunk_id": 773, "next_chunk_id": 775, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 775, "text": "num_workers (`int`, *optional*, defaults to 8) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used.\n\nbatch_size (`int`, *optional*, defaults to 1) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .\n\nargs_parser ([ArgumentHandler](/docs/transformers/v5.6.2/en/internal/pipelines_utils#transformers.pipelines.ArgumentHandler), *optional*) : Reference to the object in charge of parsing supplied pipeline parameters.\n\ndevice (`int`, *optional*, defaults to -1) : Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.DepthEstimationPipeline[[transformers.DepthEstimationPipeline]]", "char_start": 25654, "char_end": 26622, "token_estimate": 242, "prev_chunk_id": 774, "next_chunk_id": 776, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 776, "text": "dtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`)\n\nbinary_output (`bool`, *optional*, defaults to `False`) : Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text.\n\n**Returns:**\n\nA dictionary or a list of dictionaries containing result. If the input is a single image, will return a\ndictionary, if the input is a list of several images, will return a list of dictionaries corresponding to\nthe images.\n\nThe dictionaries contain the following keys:\n\n- **predicted_depth** (`torch.Tensor`) -- The predicted depth by the model as a `torch.Tensor`.\n- **depth** (`PIL.Image`) -- The predicted depth by the model as a `PIL.Image`.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.DepthEstimationPipeline[[transformers.DepthEstimationPipeline]]", "char_start": 49878, "char_end": 50730, "token_estimate": 213, "prev_chunk_id": 775, "next_chunk_id": 777, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 777, "text": "### ImageClassificationPipeline[[transformers.ImageClassificationPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "ImageClassificationPipeline[[transformers.ImageClassificationPipeline]]", "char_start": 50732, "char_end": 50807, "token_estimate": 18, "prev_chunk_id": 776, "next_chunk_id": 778, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 778, "text": "#### transformers.ImageClassificationPipeline[[transformers.ImageClassificationPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/image_classification.py#L73)\n\nImage classification pipeline using any `AutoModelForImageClassification`. This pipeline predicts the class of an\nimage.\n\nExample:\n\n```python\n>>> from transformers import pipeline\n\n>>> classifier = pipeline(model=\"microsoft/beit-base-patch16-224-pt22k-ft22k\")\n>>> classifier(\"https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png\")\n[{'score': 0.442, 'label': 'macaw'}, {'score': 0.088, 'label': 'popinjay'}, {'score': 0.075, 'label': 'parrot'}, {'score': 0.073, 'label': 'parodist, lampooner'}, {'score': 0.046, 'label': 'poll, poll_parrot'}]\n```\n\nLearn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageClassificationPipeline[[transformers.ImageClassificationPipeline]]", "char_start": 50809, "char_end": 51684, "token_estimate": 218, "prev_chunk_id": 777, "next_chunk_id": 779, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 779, "text": "This image classification pipeline can currently be loaded from [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline) using the following task identifier:\n`\"image-classification\"`.\n\nSee the list of available models on\n[huggingface.co/models](https://huggingface.co/models?filter=image-classification).\n\n__call__transformers.ImageClassificationPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/image_classification.py#L127[{\"name\": \"inputs\", \"val\": \": typing.Union[str, list[str], ForwardRef('Image.Image'), list['Image.Image']]\"}, {\"name\": \"**kwargs\", \"val\": \": typing.Any\"}]- **inputs** (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`) --\n The pipeline handles three types of images:\n\n - A string containing a http link pointing to an image\n - A string containing a local path to an image\n - An image loaded in PIL directly", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageClassificationPipeline[[transformers.ImageClassificationPipeline]]", "char_start": 51686, "char_end": 52604, "token_estimate": 229, "prev_chunk_id": 778, "next_chunk_id": 780, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 780, "text": "The pipeline accepts either a single image or a batch of images, which must then be passed as a string.\n Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL\n images.\n- **function_to_apply** (`str`, *optional*, defaults to `\"default\"`) --\n The function to apply to the model outputs in order to retrieve the scores. Accepts four different\n values:\n\n If this argument is not specified, then it will apply the following functions according to the number\n of labels:\n\n - If the model has a single label, will apply the sigmoid function on the output.\n - If the model has several labels, will apply the softmax function on the output.\n\n Possible values are:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageClassificationPipeline[[transformers.ImageClassificationPipeline]]", "char_start": 52608, "char_end": 53320, "token_estimate": 178, "prev_chunk_id": 779, "next_chunk_id": 781, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 781, "text": "- `\"sigmoid\"`: Applies the sigmoid function on the output.\n - `\"softmax\"`: Applies the softmax function on the output.\n - `\"none\"`: Does not apply any function on the output.\n- **top_k** (`int`, *optional*, defaults to 5) --\n The number of top labels that will be returned by the pipeline. If the provided number is higher than\n the number of labels available in the model configuration, it will default to the number of labels.\n- **timeout** (`float`, *optional*, defaults to None) --\n The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and\n the call may block forever.0A dictionary or a list of dictionaries containing result. If the input is a single image, will return a\ndictionary, if the input is a list of several images, will return a list of dictionaries corresponding to\nthe images.\n\nThe dictionaries contain the following keys:\n\n- **label** (`str`) -- The label identified by the model.\n- **score** (`int`) -- The score attributed by the model for that label.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageClassificationPipeline[[transformers.ImageClassificationPipeline]]", "char_start": 53324, "char_end": 54346, "token_estimate": 255, "prev_chunk_id": 780, "next_chunk_id": 782, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 782, "text": "Assign labels to the image(s) passed as inputs.\n\n**Parameters:**\n\nmodel ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).\n\nimage_processor ([BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor)) : The image processor that will be used by the pipeline to encode data for the model. This object inherits from [BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor).\n\ntask (`str`, defaults to `\"\"`) : A task-identifier for the pipeline.\n\nnum_workers (`int`, *optional*, defaults to 8) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageClassificationPipeline[[transformers.ImageClassificationPipeline]]", "char_start": 54348, "char_end": 55326, "token_estimate": 244, "prev_chunk_id": 781, "next_chunk_id": 783, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 783, "text": "batch_size (`int`, *optional*, defaults to 1) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .\n\nargs_parser ([ArgumentHandler](/docs/transformers/v5.6.2/en/internal/pipelines_utils#transformers.pipelines.ArgumentHandler), *optional*) : Reference to the object in charge of parsing supplied pipeline parameters.\n\ndevice (`int`, *optional*, defaults to -1) : Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too\n\ndtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`)", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageClassificationPipeline[[transformers.ImageClassificationPipeline]]", "char_start": 25832, "char_end": 26825, "token_estimate": 248, "prev_chunk_id": 782, "next_chunk_id": 784, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 784, "text": "binary_output (`bool`, *optional*, defaults to `False`) : Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text.\n\nfunction_to_apply (`str`, *optional*, defaults to `\"default\"`) : The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `\"sigmoid\"`: Applies the sigmoid function on the output. - `\"softmax\"`: Applies the softmax function on the output. - `\"none\"`: Does not apply any function on the output.\n\n**Returns:**\n\nA dictionary or a list of dictionaries containing result. If the input is a single image, will return a\ndictionary, if the input is a list of several images, will return a list of dictionaries corresponding to\nthe images.\n\nThe dictionaries contain the following keys:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageClassificationPipeline[[transformers.ImageClassificationPipeline]]", "char_start": 56323, "char_end": 57317, "token_estimate": 248, "prev_chunk_id": 783, "next_chunk_id": 785, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 785, "text": "- **label** (`str`) -- The label identified by the model.\n- **score** (`int`) -- The score attributed by the model for that label.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageClassificationPipeline[[transformers.ImageClassificationPipeline]]", "char_start": 54216, "char_end": 54346, "token_estimate": 32, "prev_chunk_id": 784, "next_chunk_id": 786, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 786, "text": "### ImageSegmentationPipeline[[transformers.ImageSegmentationPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "ImageSegmentationPipeline[[transformers.ImageSegmentationPipeline]]", "char_start": 57451, "char_end": 57522, "token_estimate": 17, "prev_chunk_id": 785, "next_chunk_id": 787, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 787, "text": "#### transformers.ImageSegmentationPipeline[[transformers.ImageSegmentationPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/image_segmentation.py#L27)\n\nImage segmentation pipeline using any `AutoModelForXXXSegmentation`. This pipeline predicts masks of objects and\ntheir classes.\n\nExample:\n\n```python\n>>> from transformers import pipeline\n\n>>> segmenter = pipeline(model=\"facebook/detr-resnet-50-panoptic\")\n>>> segments = segmenter(\"https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png\")\n>>> len(segments)\n2\n\n>>> segments[0][\"label\"]\n'bird'\n\n>>> segments[1][\"label\"]\n'bird'\n\n>>> type(segments[0][\"mask\"]) # This is a black and white mask showing where is the bird on the original image.\n\n>>> segments[0][\"mask\"].size\n(768, 512)\n```\n\nThis image segmentation pipeline can currently be loaded from [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline) using the following task identifier:\n`\"image-segmentation\"`.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageSegmentationPipeline[[transformers.ImageSegmentationPipeline]]", "char_start": 57524, "char_end": 58542, "token_estimate": 254, "prev_chunk_id": 786, "next_chunk_id": 788, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 788, "text": "See the list of available models on\n[huggingface.co/models](https://huggingface.co/models?filter=image-segmentation).\n\n__call__transformers.ImageSegmentationPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/image_segmentation.py#L101[{\"name\": \"inputs\", \"val\": \": typing.Union[str, ForwardRef('Image.Image'), list[str], list['Image.Image']]\"}, {\"name\": \"**kwargs\", \"val\": \": typing.Any\"}]- **inputs** (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`) --\n The pipeline handles three types of images:\n\n - A string containing an HTTP(S) link pointing to an image\n - A string containing a local path to an image\n - An image loaded in PIL directly", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageSegmentationPipeline[[transformers.ImageSegmentationPipeline]]", "char_start": 58544, "char_end": 59244, "token_estimate": 175, "prev_chunk_id": 787, "next_chunk_id": 789, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 789, "text": "The pipeline accepts either a single image or a batch of images. Images in a batch must all be in the\n same format: all as HTTP(S) links, all as local paths, or all as PIL images.\n- **subtask** (`str`, *optional*) --\n Segmentation task to be performed, choose [`semantic`, `instance` and `panoptic`] depending on model\n capabilities. If not set, the pipeline will attempt tp resolve in the following order:\n `panoptic`, `instance`, `semantic`.\n- **threshold** (`float`, *optional*, defaults to 0.9) --\n Probability threshold to filter out predicted masks.\n- **mask_threshold** (`float`, *optional*, defaults to 0.5) --\n Threshold to use when turning the predicted masks into binary values.\n- **overlap_mask_area_threshold** (`float`, *optional*, defaults to 0.5) --\n Mask overlap threshold to eliminate small, disconnected segments.\n- **timeout** (`float`, *optional*, defaults to None) --\n The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and\n the call may block forever.0If the input is a single image, will return a list of dictionaries, if the input is a list of several images,\nwill return a list of list of dictionaries corresponding to each image.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageSegmentationPipeline[[transformers.ImageSegmentationPipeline]]", "char_start": 59248, "char_end": 60459, "token_estimate": 303, "prev_chunk_id": 788, "next_chunk_id": 790, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 790, "text": "The dictionaries contain the mask, label and score (where applicable) of each detected object and contains\nthe following keys:\n\n- **label** (`str`) -- The class label identified by the model.\n- **mask** (`PIL.Image`) -- A binary mask of the detected object as a Pil Image of shape (width, height) of\n the original image. Returns a mask filled with zeros if no object is found.\n- **score** (*optional* `float`) -- Optionally, when the model is capable of estimating a confidence of the\n \"object\" described by the label and the mask.\n\nPerform segmentation (detect masks & classes) in the image(s) passed as inputs.\n\n**Parameters:**\n\nmodel ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageSegmentationPipeline[[transformers.ImageSegmentationPipeline]]", "char_start": 60461, "char_end": 61402, "token_estimate": 235, "prev_chunk_id": 789, "next_chunk_id": 791, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 791, "text": "image_processor ([BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor)) : The image processor that will be used by the pipeline to encode data for the model. This object inherits from [BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor).\n\ntask (`str`, defaults to `\"\"`) : A task-identifier for the pipeline.\n\nnum_workers (`int`, *optional*, defaults to 8) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used.\n\nbatch_size (`int`, *optional*, defaults to 1) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageSegmentationPipeline[[transformers.ImageSegmentationPipeline]]", "char_start": 48482, "char_end": 49425, "token_estimate": 235, "prev_chunk_id": 790, "next_chunk_id": 792, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 792, "text": "args_parser ([ArgumentHandler](/docs/transformers/v5.6.2/en/internal/pipelines_utils#transformers.pipelines.ArgumentHandler), *optional*) : Reference to the object in charge of parsing supplied pipeline parameters.\n\ndevice (`int`, *optional*, defaults to -1) : Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too\n\ndtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`)\n\nbinary_output (`bool`, *optional*, defaults to `False`) : Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text.\n\n**Returns:**", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageSegmentationPipeline[[transformers.ImageSegmentationPipeline]]", "char_start": 26173, "char_end": 27030, "token_estimate": 214, "prev_chunk_id": 791, "next_chunk_id": 793, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 793, "text": "If the input is a single image, will return a list of dictionaries, if the input is a list of several images,\nwill return a list of list of dictionaries corresponding to each image.\n\nThe dictionaries contain the mask, label and score (where applicable) of each detected object and contains\nthe following keys:\n\n- **label** (`str`) -- The class label identified by the model.\n- **mask** (`PIL.Image`) -- A binary mask of the detected object as a Pil Image of shape (width, height) of\n the original image. Returns a mask filled with zeros if no object is found.\n- **score** (*optional* `float`) -- Optionally, when the model is capable of estimating a confidence of the\n \"object\" described by the label and the mask.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageSegmentationPipeline[[transformers.ImageSegmentationPipeline]]", "char_start": 60278, "char_end": 60994, "token_estimate": 179, "prev_chunk_id": 792, "next_chunk_id": 794, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 794, "text": "### KeypointMatchingPipeline[[transformers.KeypointMatchingPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "KeypointMatchingPipeline[[transformers.KeypointMatchingPipeline]]", "char_start": 63926, "char_end": 63995, "token_estimate": 17, "prev_chunk_id": 793, "next_chunk_id": 795, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 795, "text": "#### transformers.KeypointMatchingPipeline[[transformers.KeypointMatchingPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/keypoint_matching.py#L69)\n\nKeypoint matching pipeline using any `AutoModelForKeypointMatching`. This pipeline matches keypoints between two images.\n\n__call__transformers.KeypointMatchingPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/keypoint_matching.py#L98[{\"name\": \"inputs\", \"val\": \": list[collections.abc.Sequence[typing.Union[ForwardRef('Image.Image'), str]]] | collections.abc.Sequence[typing.Union[ForwardRef('Image.Image'), str]]\"}, {\"name\": \"threshold\", \"val\": \": float = 0.0\"}, {\"name\": \"**kwargs\", \"val\": \": typing.Any\"}]- **inputs** (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`) --\n The pipeline handles three types of images:\n\n - A string containing a http link pointing to an image\n - A string containing a local path to an image\n - An image loaded in PIL directly", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.KeypointMatchingPipeline[[transformers.KeypointMatchingPipeline]]", "char_start": 63997, "char_end": 65017, "token_estimate": 255, "prev_chunk_id": 794, "next_chunk_id": 796, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 796, "text": "The pipeline accepts either a single pair of images or a batch of image pairs, which must then be passed as a string.\n Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL\n images.\n\n- **threshold** (`float`, *optional*, defaults to 0.0) --\n The threshold to use for keypoint matching. Keypoints matched with a lower matching score will be filtered out.\n A value of 0 means that all matched keypoints will be returned.\n\n- **kwargs** --\n `timeout (`float`, *optional*, defaults to None)`\n The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and\n the call may block forever.0Union[list[Match], list[list[Match]]]A list of matches or a list if a single image pair is provided, or of lists of matches if a batch\nof image pairs is provided. Each match is a dictionary containing the following keys:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.KeypointMatchingPipeline[[transformers.KeypointMatchingPipeline]]", "char_start": 65021, "char_end": 65915, "token_estimate": 223, "prev_chunk_id": 795, "next_chunk_id": 797, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 797, "text": "- **keypoint_image_0** (`Keypoint`): The keypoint in the first image (x, y coordinates).\n- **keypoint_image_1** (`Keypoint`): The keypoint in the second image (x, y coordinates).\n- **score** (`float`): The matching score between the two keypoints.\n\nFind matches between keypoints in two images.\n\n**Parameters:**\n\ninputs (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`) : The pipeline handles three types of images: - A string containing a http link pointing to an image - A string containing a local path to an image - An image loaded in PIL directly The pipeline accepts either a single pair of images or a batch of image pairs, which must then be passed as a string. Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL images.\n\nthreshold (`float`, *optional*, defaults to 0.0) : The threshold to use for keypoint matching. Keypoints matched with a lower matching score will be filtered out. A value of 0 means that all matched keypoints will be returned.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.KeypointMatchingPipeline[[transformers.KeypointMatchingPipeline]]", "char_start": 0, "char_end": 1015, "token_estimate": 253, "prev_chunk_id": 796, "next_chunk_id": 798, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 798, "text": "kwargs : `timeout (`float`, *optional*, defaults to None)` The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and the call may block forever.\n\n**Returns:**\n\n`Union[list[Match], list[list[Match]]]`\n\nA list of matches or a list if a single image pair is provided, or of lists of matches if a batch\nof image pairs is provided. Each match is a dictionary containing the following keys:\n\n- **keypoint_image_0** (`Keypoint`): The keypoint in the first image (x, y coordinates).\n- **keypoint_image_1** (`Keypoint`): The keypoint in the second image (x, y coordinates).\n- **score** (`float`): The matching score between the two keypoints.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.KeypointMatchingPipeline[[transformers.KeypointMatchingPipeline]]", "char_start": 66936, "char_end": 67612, "token_estimate": 169, "prev_chunk_id": 797, "next_chunk_id": 799, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 799, "text": "### ObjectDetectionPipeline[[transformers.ObjectDetectionPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "ObjectDetectionPipeline[[transformers.ObjectDetectionPipeline]]", "char_start": 67614, "char_end": 67681, "token_estimate": 16, "prev_chunk_id": 798, "next_chunk_id": 800, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 800, "text": "#### transformers.ObjectDetectionPipeline[[transformers.ObjectDetectionPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/object_detection.py#L26)\n\nObject detection pipeline using any `AutoModelForObjectDetection`. This pipeline predicts bounding boxes of objects\nand their classes.\n\nExample:\n\n```python\n>>> from transformers import pipeline\n\n>>> detector = pipeline(model=\"facebook/detr-resnet-50\")\n>>> detector(\"https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png\")\n[{'score': 0.997, 'label': 'bird', 'box': {'xmin': 69, 'ymin': 171, 'xmax': 396, 'ymax': 507}}, {'score': 0.999, 'label': 'bird', 'box': {'xmin': 398, 'ymin': 105, 'xmax': 767, 'ymax': 507}}]\n\n>>> # x, y are expressed relative to the top left hand corner.\n```\n\nLearn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ObjectDetectionPipeline[[transformers.ObjectDetectionPipeline]]", "char_start": 67683, "char_end": 68582, "token_estimate": 224, "prev_chunk_id": 799, "next_chunk_id": 801, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 801, "text": "This object detection pipeline can currently be loaded from [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline) using the following task identifier:\n`\"object-detection\"`.\n\nSee the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=object-detection).\n\n__call__transformers.ObjectDetectionPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/object_detection.py#L81[{\"name\": \"*args\", \"val\": \"\"}, {\"name\": \"**kwargs\", \"val\": \"\"}]- **inputs** (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`) --\n The pipeline handles three types of images:\n\n - A string containing an HTTP(S) link pointing to an image\n - A string containing a local path to an image\n - An image loaded in PIL directly", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ObjectDetectionPipeline[[transformers.ObjectDetectionPipeline]]", "char_start": 68584, "char_end": 69394, "token_estimate": 202, "prev_chunk_id": 800, "next_chunk_id": 802, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 802, "text": "The pipeline accepts either a single image or a batch of images. Images in a batch must all be in the\n same format: all as HTTP(S) links, all as local paths, or all as PIL images.\n- **threshold** (`float`, *optional*, defaults to 0.5) --\n The probability necessary to make a prediction.\n- **timeout** (`float`, *optional*, defaults to None) --\n The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and\n the call may block forever.0A list of dictionaries or a list of list of dictionaries containing the result. If the input is a single\nimage, will return a list of dictionaries, if the input is a list of several images, will return a list of\nlist of dictionaries corresponding to each image.\n\nThe dictionaries contain the following keys:\n\n- **label** (`str`) -- The class label identified by the model.\n- **score** (`float`) -- The score attributed by the model for that label.\n- **box** (`list[dict[str, int]]`) -- The bounding box of detected object in image's original size.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ObjectDetectionPipeline[[transformers.ObjectDetectionPipeline]]", "char_start": 69398, "char_end": 70424, "token_estimate": 256, "prev_chunk_id": 801, "next_chunk_id": 803, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 803, "text": "Detect objects (bounding boxes & classes) in the image(s) passed as inputs.\n\n**Parameters:**\n\nmodel ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).\n\nimage_processor ([BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor)) : The image processor that will be used by the pipeline to encode data for the model. This object inherits from [BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor).\n\ntask (`str`, defaults to `\"\"`) : A task-identifier for the pipeline.\n\nnum_workers (`int`, *optional*, defaults to 8) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ObjectDetectionPipeline[[transformers.ObjectDetectionPipeline]]", "char_start": 70426, "char_end": 71432, "token_estimate": 251, "prev_chunk_id": 802, "next_chunk_id": 804, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 804, "text": "batch_size (`int`, *optional*, defaults to 1) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .\n\nargs_parser ([ArgumentHandler](/docs/transformers/v5.6.2/en/internal/pipelines_utils#transformers.pipelines.ArgumentHandler), *optional*) : Reference to the object in charge of parsing supplied pipeline parameters.\n\ndevice (`int`, *optional*, defaults to -1) : Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too\n\ndtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`)", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ObjectDetectionPipeline[[transformers.ObjectDetectionPipeline]]", "char_start": 25832, "char_end": 26825, "token_estimate": 248, "prev_chunk_id": 803, "next_chunk_id": 805, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 805, "text": "binary_output (`bool`, *optional*, defaults to `False`) : Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text.\n\n**Returns:**\n\nA list of dictionaries or a list of list of dictionaries containing the result. If the input is a single\nimage, will return a list of dictionaries, if the input is a list of several images, will return a list of\nlist of dictionaries corresponding to each image.\n\nThe dictionaries contain the following keys:\n\n- **label** (`str`) -- The class label identified by the model.\n- **score** (`float`) -- The score attributed by the model for that label.\n- **box** (`list[dict[str, int]]`) -- The bounding box of detected object in image's original size.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ObjectDetectionPipeline[[transformers.ObjectDetectionPipeline]]", "char_start": 72429, "char_end": 73181, "token_estimate": 188, "prev_chunk_id": 804, "next_chunk_id": 806, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 806, "text": "### VideoClassificationPipeline[[transformers.VideoClassificationPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "VideoClassificationPipeline[[transformers.VideoClassificationPipeline]]", "char_start": 73183, "char_end": 73258, "token_estimate": 18, "prev_chunk_id": 805, "next_chunk_id": 807, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 807, "text": "#### transformers.VideoClassificationPipeline[[transformers.VideoClassificationPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/video_classification.py#L41)\n\nVideo classification pipeline using any `AutoModelForVideoClassification`. This pipeline predicts the class of a\nvideo.\n\nThis video classification pipeline can currently be loaded from [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline) using the following task identifier:\n`\"video-classification\"`.\n\nSee the list of available models on\n[huggingface.co/models](https://huggingface.co/models?filter=video-classification).\n\n__call__transformers.VideoClassificationPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/video_classification.py#L90[{\"name\": \"inputs\", \"val\": \": str | list[str] | None\"}, {\"name\": \"**kwargs\", \"val\": \"\"}]- **inputs** (`str`, `list[str]`) --\n The pipeline handles three types of videos:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.VideoClassificationPipeline[[transformers.VideoClassificationPipeline]]", "char_start": 73260, "char_end": 74268, "token_estimate": 252, "prev_chunk_id": 806, "next_chunk_id": 808, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 808, "text": "- A string containing a http link pointing to a video\n - A string containing a local path to a video", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.VideoClassificationPipeline[[transformers.VideoClassificationPipeline]]", "char_start": 74272, "char_end": 74373, "token_estimate": 25, "prev_chunk_id": 807, "next_chunk_id": 809, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 809, "text": "The pipeline accepts either a single video or a batch of videos, which must then be passed as a string.\n Videos in a batch must all be in the same format: all as http links or all as local paths.\n- **top_k** (`int`, *optional*, defaults to 5) --\n The number of top labels that will be returned by the pipeline. If the provided number is higher than\n the number of labels available in the model configuration, it will default to the number of labels.\n- **num_frames** (`int`, *optional*, defaults to `self.model.config.num_frames`) --\n The number of frames sampled from the video to run the classification on. If not provided, will default\n to the number of frames specified in the model configuration.\n- **frame_sampling_rate** (`int`, *optional*, defaults to 1) --\n The sampling rate used to select frames from the video. If not provided, will default to 1, i.e. every\n frame will be used.\n- **function_to_apply(`str`,** *optional*, defaults to \"softmax\") --\n The function to apply to the model output. By default, the pipeline will apply the softmax function to\n the output of the model. Valid options: [\"softmax\", \"sigmoid\", \"none\"]. Note that passing Python's\n built-in `None` will default to \"softmax\", so you need to pass the string \"none\" to disable any\n post-processing.0A list of dictionaries or a list of list of dictionaries containing result. If the input is a single video,\nwill return a list of `top_k` dictionaries, if the input is a list of several videos, will return a list of list of\n`top_k` dictionaries corresponding to the videos.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.VideoClassificationPipeline[[transformers.VideoClassificationPipeline]]", "char_start": 74377, "char_end": 75940, "token_estimate": 391, "prev_chunk_id": 808, "next_chunk_id": 810, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 810, "text": "The dictionaries contain the following keys:\n\n- **label** (`str`) -- The label identified by the model.\n- **score** (`int`) -- The score attributed by the model for that label.\n\nAssign labels to the video(s) passed as inputs.\n\n**Parameters:**\n\nmodel ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).\n\nimage_processor ([BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor)) : The image processor that will be used by the pipeline to encode data for the model. This object inherits from [BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor).\n\ntask (`str`, defaults to `\"\"`) : A task-identifier for the pipeline.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.VideoClassificationPipeline[[transformers.VideoClassificationPipeline]]", "char_start": 75942, "char_end": 76920, "token_estimate": 244, "prev_chunk_id": 809, "next_chunk_id": 811, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 811, "text": "num_workers (`int`, *optional*, defaults to 8) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used.\n\nbatch_size (`int`, *optional*, defaults to 1) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .\n\nargs_parser ([ArgumentHandler](/docs/transformers/v5.6.2/en/internal/pipelines_utils#transformers.pipelines.ArgumentHandler), *optional*) : Reference to the object in charge of parsing supplied pipeline parameters.\n\ndevice (`int`, *optional*, defaults to -1) : Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.VideoClassificationPipeline[[transformers.VideoClassificationPipeline]]", "char_start": 25654, "char_end": 26622, "token_estimate": 242, "prev_chunk_id": 810, "next_chunk_id": 812, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 812, "text": "dtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`)\n\nbinary_output (`bool`, *optional*, defaults to `False`) : Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text.\n\n**Returns:**\n\nA list of dictionaries or a list of list of dictionaries containing result. If the input is a single video,\nwill return a list of `top_k` dictionaries, if the input is a list of several videos, will return a list of list of\n`top_k` dictionaries corresponding to the videos.\n\nThe dictionaries contain the following keys:\n\n- **label** (`str`) -- The label identified by the model.\n- **score** (`int`) -- The score attributed by the model for that label.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.VideoClassificationPipeline[[transformers.VideoClassificationPipeline]]", "char_start": 77892, "char_end": 78751, "token_estimate": 214, "prev_chunk_id": 811, "next_chunk_id": 813, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 813, "text": "### ZeroShotImageClassificationPipeline[[transformers.ZeroShotImageClassificationPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "ZeroShotImageClassificationPipeline[[transformers.ZeroShotImageClassificationPipeline]]", "char_start": 78753, "char_end": 78844, "token_estimate": 22, "prev_chunk_id": 812, "next_chunk_id": 814, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 814, "text": "#### transformers.ZeroShotImageClassificationPipeline[[transformers.ZeroShotImageClassificationPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/zero_shot_image_classification.py#L29)\n\nZero shot image classification pipeline using `CLIPModel`. This pipeline predicts the class of an image when you\nprovide an image and a set of `candidate_labels`.\n\nExample:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotImageClassificationPipeline[[transformers.ZeroShotImageClassificationPipeline]]", "char_start": 78846, "char_end": 79257, "token_estimate": 102, "prev_chunk_id": 813, "next_chunk_id": 815, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 815, "text": "```python\n>>> from transformers import pipeline\n\n>>> classifier = pipeline(model=\"google/siglip-so400m-patch14-384\")\n>>> classifier(\n... \"https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png\",\n... candidate_labels=[\"animals\", \"humans\", \"landscape\"],\n... )\n[{'score': 0.965, 'label': 'animals'}, {'score': 0.03, 'label': 'humans'}, {'score': 0.005, 'label': 'landscape'}]\n\n>>> classifier(\n... \"https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png\",\n... candidate_labels=[\"black and white\", \"photorealist\", \"painting\"],\n... )\n[{'score': 0.996, 'label': 'black and white'}, {'score': 0.003, 'label': 'photorealist'}, {'score': 0.0, 'label': 'painting'}]\n```\n\nLearn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotImageClassificationPipeline[[transformers.ZeroShotImageClassificationPipeline]]", "char_start": 79259, "char_end": 80065, "token_estimate": 201, "prev_chunk_id": 814, "next_chunk_id": 816, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 816, "text": "This image classification pipeline can currently be loaded from [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline) using the following task identifier:\n`\"zero-shot-image-classification\"`.\n\nSee the list of available models on\n[huggingface.co/models](https://huggingface.co/models?filter=zero-shot-image-classification).\n\n__call__transformers.ZeroShotImageClassificationPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/zero_shot_image_classification.py#L83[{\"name\": \"image\", \"val\": \": typing.Union[str, list[str], ForwardRef('Image.Image'), list['Image.Image']]\"}, {\"name\": \"candidate_labels\", \"val\": \": list\"}, {\"name\": \"**kwargs\", \"val\": \": typing.Any\"}]- **image** (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`) --\n The pipeline handles three types of images:\n\n - A string containing a http link pointing to an image\n - A string containing a local path to an image\n - An image loaded in PIL directly", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotImageClassificationPipeline[[transformers.ZeroShotImageClassificationPipeline]]", "char_start": 80067, "char_end": 81067, "token_estimate": 250, "prev_chunk_id": 815, "next_chunk_id": 817, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 817, "text": "- **candidate_labels** (`list[str]`) --\n The candidate labels for this image. They will be formatted using *hypothesis_template*.\n\n- **hypothesis_template** (`str`, *optional*, defaults to `\"This is a photo of {}\"`) --\n The format used in conjunction with *candidate_labels* to attempt the image classification by\n replacing the placeholder with the candidate_labels. Pass \"{}\" if *candidate_labels* are\n already formatted.\n\n- **timeout** (`float`, *optional*, defaults to None) --\n The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and\n the call may block forever.0A list of dictionaries containing one entry per proposed label. Each dictionary contains the\nfollowing keys:\n- **label** (`str`) -- One of the suggested *candidate_labels*.\n- **score** (`float`) -- The score attributed by the model to that label. It is a value between\n 0 and 1, computed as the `softmax` of `logits_per_image`.\n\nAssign labels to the image(s) passed as inputs.\n\n**Parameters:**", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotImageClassificationPipeline[[transformers.ZeroShotImageClassificationPipeline]]", "char_start": 81069, "char_end": 82082, "token_estimate": 253, "prev_chunk_id": 816, "next_chunk_id": 818, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 818, "text": "model ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).\n\nimage_processor ([BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor)) : The image processor that will be used by the pipeline to encode data for the model. This object inherits from [BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor).\n\ntask (`str`, defaults to `\"\"`) : A task-identifier for the pipeline.\n\nnum_workers (`int`, *optional*, defaults to 8) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotImageClassificationPipeline[[transformers.ZeroShotImageClassificationPipeline]]", "char_start": 48172, "char_end": 49084, "token_estimate": 228, "prev_chunk_id": 817, "next_chunk_id": 819, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 819, "text": "batch_size (`int`, *optional*, defaults to 1) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .\n\nargs_parser ([ArgumentHandler](/docs/transformers/v5.6.2/en/internal/pipelines_utils#transformers.pipelines.ArgumentHandler), *optional*) : Reference to the object in charge of parsing supplied pipeline parameters.\n\ndevice (`int`, *optional*, defaults to -1) : Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too\n\ndtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`)", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotImageClassificationPipeline[[transformers.ZeroShotImageClassificationPipeline]]", "char_start": 25832, "char_end": 26825, "token_estimate": 248, "prev_chunk_id": 818, "next_chunk_id": 820, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 820, "text": "binary_output (`bool`, *optional*, defaults to `False`) : Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text.\n\n**Returns:**\n\nA list of dictionaries containing one entry per proposed label. Each dictionary contains the\nfollowing keys:\n- **label** (`str`) -- One of the suggested *candidate_labels*.\n- **score** (`float`) -- The score attributed by the model to that label. It is a value between\n 0 and 1, computed as the `softmax` of `logits_per_image`.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotImageClassificationPipeline[[transformers.ZeroShotImageClassificationPipeline]]", "char_start": 83993, "char_end": 84526, "token_estimate": 133, "prev_chunk_id": 819, "next_chunk_id": 821, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 821, "text": "### ZeroShotObjectDetectionPipeline[[transformers.ZeroShotObjectDetectionPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "ZeroShotObjectDetectionPipeline[[transformers.ZeroShotObjectDetectionPipeline]]", "char_start": 84528, "char_end": 84611, "token_estimate": 20, "prev_chunk_id": 820, "next_chunk_id": 822, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 822, "text": "#### transformers.ZeroShotObjectDetectionPipeline[[transformers.ZeroShotObjectDetectionPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/zero_shot_object_detection.py#L23)\n\nZero shot object detection pipeline using `OwlViTForObjectDetection`. This pipeline predicts bounding boxes of\nobjects when you provide an image and a set of `candidate_labels`.\n\nExample:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotObjectDetectionPipeline[[transformers.ZeroShotObjectDetectionPipeline]]", "char_start": 84613, "char_end": 85027, "token_estimate": 103, "prev_chunk_id": 821, "next_chunk_id": 823, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 823, "text": "```python\n>>> from transformers import pipeline\n\n>>> detector = pipeline(model=\"google/owlvit-base-patch32\", task=\"zero-shot-object-detection\")\n>>> detector(\n... \"http://images.cocodataset.org/val2017/000000039769.jpg\",\n... candidate_labels=[\"cat\", \"couch\"],\n... )\n[{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.254, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}]\n\n>>> detector(\n... \"https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png\",\n... candidate_labels=[\"head\", \"bird\"],\n... )\n[{'score': 0.119, 'label': 'bird', 'box': {'xmin': 71, 'ymin': 170, 'xmax': 410, 'ymax': 508}}]\n```\n\nLearn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotObjectDetectionPipeline[[transformers.ZeroShotObjectDetectionPipeline]]", "char_start": 85029, "char_end": 85926, "token_estimate": 224, "prev_chunk_id": 822, "next_chunk_id": 824, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 824, "text": "This object detection pipeline can currently be loaded from [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline) using the following task identifier:\n`\"zero-shot-object-detection\"`.\n\nSee the list of available models on\n[huggingface.co/models](https://huggingface.co/models?filter=zero-shot-object-detection).\n\n__call__transformers.ZeroShotObjectDetectionPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/zero_shot_object_detection.py#L75[{\"name\": \"image\", \"val\": \": typing.Union[str, ForwardRef('Image.Image'), list[dict[str, typing.Any]]]\"}, {\"name\": \"candidate_labels\", \"val\": \": str | list[str] | None = None\"}, {\"name\": \"**kwargs\", \"val\": \": typing.Any\"}]- **image** (`str`, `PIL.Image` or `list[dict[str, Any]]`) --\n The pipeline handles three types of images:\n\n - A string containing an http url pointing to an image\n - A string containing a local path to an image\n - An image loaded in PIL directly", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotObjectDetectionPipeline[[transformers.ZeroShotObjectDetectionPipeline]]", "char_start": 85928, "char_end": 86922, "token_estimate": 248, "prev_chunk_id": 823, "next_chunk_id": 825, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 825, "text": "You can use this parameter to send directly a list of images, or a dataset or a generator like so:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotObjectDetectionPipeline[[transformers.ZeroShotObjectDetectionPipeline]]", "char_start": 86926, "char_end": 87024, "token_estimate": 25, "prev_chunk_id": 824, "next_chunk_id": 826, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 826, "text": "```python\n>>> from transformers import pipeline\n\n>>> detector = pipeline(model=\"google/owlvit-base-patch32\", task=\"zero-shot-object-detection\")\n>>> detector(\n... [\n... {\n... \"image\": \"http://images.cocodataset.org/val2017/000000039769.jpg\",\n... \"candidate_labels\": [\"cat\", \"couch\"],\n... },\n... {\n... \"image\": \"http://images.cocodataset.org/val2017/000000039769.jpg\",\n... \"candidate_labels\": [\"cat\", \"couch\"],\n... },\n... ]\n... )\n[[{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.25, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}], [{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.254, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}]]\n```", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotObjectDetectionPipeline[[transformers.ZeroShotObjectDetectionPipeline]]", "char_start": 87026, "char_end": 88107, "token_estimate": 270, "prev_chunk_id": 825, "next_chunk_id": 827, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 827, "text": "- **candidate_labels** (`str` or `list[str]` or `list[list[str]]`) --\n What the model should recognize in the image.\n\n- **threshold** (`float`, *optional*, defaults to 0.1) --\n The probability necessary to make a prediction.\n\n- **top_k** (`int`, *optional*, defaults to None) --\n The number of top predictions that will be returned by the pipeline. If the provided number is `None`\n or higher than the number of predictions available, it will default to the number of predictions.\n\n- **timeout** (`float`, *optional*, defaults to None) --\n The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and\n the call may block forever.0A list of lists containing prediction results, one list per input image. Each list contains dictionaries\nwith the following keys:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotObjectDetectionPipeline[[transformers.ZeroShotObjectDetectionPipeline]]", "char_start": 88109, "char_end": 88914, "token_estimate": 201, "prev_chunk_id": 826, "next_chunk_id": 828, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 828, "text": "- **label** (`str`) -- Text query corresponding to the found object.\n- **score** (`float`) -- Score corresponding to the object (between 0 and 1).\n- **box** (`dict[str,int]`) -- Bounding box of the detected object in image's original size. It is a\n dictionary with `x_min`, `x_max`, `y_min`, `y_max` keys.\n\nDetect objects (bounding boxes & classes) in the image(s) passed as inputs.\n\n**Parameters:**\n\nmodel ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotObjectDetectionPipeline[[transformers.ZeroShotObjectDetectionPipeline]]", "char_start": 88916, "char_end": 89626, "token_estimate": 177, "prev_chunk_id": 827, "next_chunk_id": 829, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 829, "text": "image_processor ([BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor)) : The image processor that will be used by the pipeline to encode data for the model. This object inherits from [BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor).\n\ntask (`str`, defaults to `\"\"`) : A task-identifier for the pipeline.\n\nnum_workers (`int`, *optional*, defaults to 8) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used.\n\nbatch_size (`int`, *optional*, defaults to 1) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotObjectDetectionPipeline[[transformers.ZeroShotObjectDetectionPipeline]]", "char_start": 48482, "char_end": 49425, "token_estimate": 235, "prev_chunk_id": 828, "next_chunk_id": 830, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 830, "text": "args_parser ([ArgumentHandler](/docs/transformers/v5.6.2/en/internal/pipelines_utils#transformers.pipelines.ArgumentHandler), *optional*) : Reference to the object in charge of parsing supplied pipeline parameters.\n\ndevice (`int`, *optional*, defaults to -1) : Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too\n\ndtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`)\n\nbinary_output (`bool`, *optional*, defaults to `False`) : Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text.\n\n**Returns:**\n\nA list of lists containing prediction results, one list per input image. Each list contains dictionaries\nwith the following keys:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotObjectDetectionPipeline[[transformers.ZeroShotObjectDetectionPipeline]]", "char_start": 90573, "char_end": 91561, "token_estimate": 247, "prev_chunk_id": 829, "next_chunk_id": 831, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 831, "text": "- **label** (`str`) -- Text query corresponding to the found object.\n- **score** (`float`) -- Score corresponding to the object (between 0 and 1).\n- **box** (`dict[str,int]`) -- Bounding box of the detected object in image's original size. It is a\n dictionary with `x_min`, `x_max`, `y_min`, `y_max` keys.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotObjectDetectionPipeline[[transformers.ZeroShotObjectDetectionPipeline]]", "char_start": 88916, "char_end": 89222, "token_estimate": 76, "prev_chunk_id": 830, "next_chunk_id": 832, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 832, "text": "## Natural Language Processing\n\nPipelines available for natural language processing tasks include the following.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "Natural Language Processing", "char_start": 91871, "char_end": 91983, "token_estimate": 28, "prev_chunk_id": 831, "next_chunk_id": 833, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 833, "text": "### FillMaskPipeline[[transformers.FillMaskPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "FillMaskPipeline[[transformers.FillMaskPipeline]]", "char_start": 91985, "char_end": 92038, "token_estimate": 13, "prev_chunk_id": 832, "next_chunk_id": 834, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 834, "text": "#### transformers.FillMaskPipeline[[transformers.FillMaskPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/fill_mask.py#L28)", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.FillMaskPipeline[[transformers.FillMaskPipeline]]", "char_start": 92040, "char_end": 92218, "token_estimate": 44, "prev_chunk_id": 833, "next_chunk_id": 835, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 835, "text": "__call__transformers.FillMaskPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/fill_mask.py#L234[{\"name\": \"inputs\", \"val\": \": str | list[str]\"}, {\"name\": \"**kwargs\", \"val\": \": typing.Any\"}]- **inputs** (`str` or `list[str]`) --\n One or several texts (or one list of prompts) with masked tokens.\n- **targets** (`str` or `list[str]`, *optional*) --\n When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n vocab. If the provided targets are not in the model vocab, they will be tokenized and the first\n resulting token will be used (with a warning, and that might be slower).\n- **top_k** (`int`, *optional*) --\n When passed, overrides the number of predictions to return.0A list or a list of list of `dict`Each result comes as list of dictionaries with the following keys:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.FillMaskPipeline[[transformers.FillMaskPipeline]]", "char_start": 92220, "char_end": 93092, "token_estimate": 218, "prev_chunk_id": 834, "next_chunk_id": 836, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 836, "text": "- **sequence** (`str`) -- The corresponding input with the mask token prediction.\n- **score** (`float`) -- The corresponding probability.\n- **token** (`int`) -- The predicted token id (to replace the masked one).\n- **token_str** (`str`) -- The predicted token (to replace the masked one).\n\nFill the masked token in the text(s) given as inputs.\n\n**Parameters:**\n\nmodel ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).\n\ntokenizer ([PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend)) : The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from [PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.FillMaskPipeline[[transformers.FillMaskPipeline]]", "char_start": 93094, "char_end": 94088, "token_estimate": 248, "prev_chunk_id": 835, "next_chunk_id": 837, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 837, "text": "task (`str`, defaults to `\"\"`) : A task-identifier for the pipeline.\n\nnum_workers (`int`, *optional*, defaults to 8) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used.\n\nbatch_size (`int`, *optional*, defaults to 1) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .\n\nargs_parser ([ArgumentHandler](/docs/transformers/v5.6.2/en/internal/pipelines_utils#transformers.pipelines.ArgumentHandler), *optional*) : Reference to the object in charge of parsing supplied pipeline parameters.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.FillMaskPipeline[[transformers.FillMaskPipeline]]", "char_start": 25584, "char_end": 26387, "token_estimate": 200, "prev_chunk_id": 836, "next_chunk_id": 838, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 838, "text": "device (`int`, *optional*, defaults to -1) : Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too\n\ndtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`)\n\nbinary_output (`bool`, *optional*, defaults to `False`) : Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text.\n\ntop_k (`int`, *optional*, defaults to 5) : The number of predictions to return.\n\ntargets (`str` or `list[str]`, *optional*) : When passed, the model will limit the scores to the passed targets instead of looking up in the whole vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting token will be used (with a warning, and that might be slower).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.FillMaskPipeline[[transformers.FillMaskPipeline]]", "char_start": 94895, "char_end": 95920, "token_estimate": 256, "prev_chunk_id": 837, "next_chunk_id": 839, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 839, "text": "tokenizer_kwargs (`dict`, *optional*) : Additional dictionary of keyword arguments passed along to the tokenizer.\n\n**Returns:**\n\n`A list or a list of list of `dict``\n\nEach result comes as list of dictionaries with the following keys:\n\n- **sequence** (`str`) -- The corresponding input with the mask token prediction.\n- **score** (`float`) -- The corresponding probability.\n- **token** (`int`) -- The predicted token id (to replace the masked one).\n- **token_str** (`str`) -- The predicted token (to replace the masked one).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.FillMaskPipeline[[transformers.FillMaskPipeline]]", "char_start": 95922, "char_end": 96445, "token_estimate": 130, "prev_chunk_id": 838, "next_chunk_id": 840, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 840, "text": "### TableQuestionAnsweringPipeline[[transformers.TableQuestionAnsweringPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "TableQuestionAnsweringPipeline[[transformers.TableQuestionAnsweringPipeline]]", "char_start": 96447, "char_end": 96528, "token_estimate": 20, "prev_chunk_id": 839, "next_chunk_id": 841, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 841, "text": "#### transformers.TableQuestionAnsweringPipeline[[transformers.TableQuestionAnsweringPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/table_question_answering.py#L78)\n\nTable Question Answering pipeline using a `ModelForTableQuestionAnswering`. This pipeline is only available in\nPyTorch.\n\nUnless the model you're using explicitly sets these generation parameters in its configuration files\n(`generation_config.json`), the following default values will be used:\n- max_new_tokens: 256\n\nExample:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TableQuestionAnsweringPipeline[[transformers.TableQuestionAnsweringPipeline]]", "char_start": 96530, "char_end": 97077, "token_estimate": 136, "prev_chunk_id": 840, "next_chunk_id": 842, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 842, "text": "```python\n>>> from transformers import pipeline\n\n>>> oracle = pipeline(model=\"google/tapas-base-finetuned-wtq\")\n>>> table = {\n... \"Repository\": [\"Transformers\", \"Datasets\", \"Tokenizers\"],\n... \"Stars\": [\"36542\", \"4512\", \"3934\"],\n... \"Contributors\": [\"651\", \"77\", \"34\"],\n... \"Programming language\": [\"Python\", \"Python\", \"Rust, Python and NodeJS\"],\n... }\n>>> oracle(query=\"How many stars does the transformers repository have?\", table=table)\n{'answer': 'AVERAGE > 36542', 'coordinates': [(0, 1)], 'cells': ['36542'], 'aggregator': 'AVERAGE'}\n```\n\nLearn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)\n\nThis tabular question answering pipeline can currently be loaded from [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline) using the following task\nidentifier: `\"table-question-answering\"`.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TableQuestionAnsweringPipeline[[transformers.TableQuestionAnsweringPipeline]]", "char_start": 97079, "char_end": 97961, "token_estimate": 220, "prev_chunk_id": 841, "next_chunk_id": 843, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 843, "text": "The models that this pipeline can use are models that have been fine-tuned on a tabular question answering task.\nSee the up-to-date list of available models on\n[huggingface.co/models](https://huggingface.co/models?filter=table-question-answering).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TableQuestionAnsweringPipeline[[transformers.TableQuestionAnsweringPipeline]]", "char_start": 97963, "char_end": 98210, "token_estimate": 61, "prev_chunk_id": 842, "next_chunk_id": 844, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 844, "text": "__call__transformers.TableQuestionAnsweringPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/table_question_answering.py#L208[{\"name\": \"*args\", \"val\": \"\"}, {\"name\": \"**kwargs\", \"val\": \"\"}]- **table** (`pd.DataFrame` or `Dict`) --\n Pandas DataFrame or dictionary that will be converted to a DataFrame containing all the table values.\n See above for an example of dictionary.\n- **query** (`str` or `list[str]`) --\n Query or list of queries that will be sent to the model alongside the table.\n- **sequential** (`bool`, *optional*, defaults to `False`) --\n Whether to do inference sequentially or as a batch. Batching is faster, but models like SQA require the\n inference to be done sequentially to extract relations within sequences, given their conversational\n nature.\n- **padding** (`bool`, `str` or [PaddingStrategy](/docs/transformers/v5.6.2/en/internal/file_utils#transformers.utils.PaddingStrategy), *optional*, defaults to `False`) --\n Activates and controls padding. Accepts the following values:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TableQuestionAnsweringPipeline[[transformers.TableQuestionAnsweringPipeline]]", "char_start": 98212, "char_end": 99270, "token_estimate": 264, "prev_chunk_id": 843, "next_chunk_id": 845, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 845, "text": "- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single\n sequence if provided).\n - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n\n- **truncation** (`bool`, `str` or `TapasTruncationStrategy`, *optional*, defaults to `False`) --\n Activates and controls truncation. Accepts the following values:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TableQuestionAnsweringPipeline[[transformers.TableQuestionAnsweringPipeline]]", "char_start": 99274, "char_end": 99863, "token_estimate": 147, "prev_chunk_id": 844, "next_chunk_id": 846, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 846, "text": "- `True` or `'drop_rows_to_fit'`: Truncate to a maximum length specified with the argument `max_length`\n or to the maximum acceptable input length for the model if that argument is not provided. This will\n truncate row by row, removing rows from the table.\n - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).0A dictionary or a list of dictionaries containing resultsEach result is a dictionary with the following\nkeys:\n\n- **answer** (`str`) -- The answer of the query given the table. If there is an aggregator, the answer will\n be preceded by `AGGREGATOR >`.\n- **coordinates** (`list[tuple[int, int]]`) -- Coordinates of the cells of the answers.\n- **cells** (`list[str]`) -- List of strings made up of the answer cell values.\n- **aggregator** (`str`) -- If the model has an aggregator, this returns the aggregator.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TableQuestionAnsweringPipeline[[transformers.TableQuestionAnsweringPipeline]]", "char_start": 99867, "char_end": 100803, "token_estimate": 234, "prev_chunk_id": 845, "next_chunk_id": 847, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 847, "text": "Answers queries according to a table. The pipeline accepts several types of inputs which are detailed below:\n\n- `pipeline(table, query)`\n- `pipeline(table, [query])`\n- `pipeline(table=table, query=query)`\n- `pipeline(table=table, query=[query])`\n- `pipeline({\"table\": table, \"query\": query})`\n- `pipeline({\"table\": table, \"query\": [query]})`\n- `pipeline([{\"table\": table, \"query\": query}, {\"table\": table, \"query\": query}])`\n\nThe `table` argument should be a dict or a DataFrame built from that dict, containing the whole table:\n\nExample:\n\n```python\ndata = {\n \"actors\": [\"brad pitt\", \"leonardo di caprio\", \"george clooney\"],\n \"age\": [\"56\", \"45\", \"59\"],\n \"number of movies\": [\"87\", \"53\", \"69\"],\n \"date of birth\": [\"7 february 1967\", \"10 june 1996\", \"28 november 1967\"],\n}\n```\n\nThis dictionary can be passed in as such, or can be converted to a pandas DataFrame:\n\nExample:\n\n```python\nimport pandas as pd\n\ntable = pd.DataFrame.from_dict(data)\n```\n\n**Parameters:**", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TableQuestionAnsweringPipeline[[transformers.TableQuestionAnsweringPipeline]]", "char_start": 100805, "char_end": 101777, "token_estimate": 243, "prev_chunk_id": 846, "next_chunk_id": 848, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 848, "text": "model ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).\n\ntokenizer ([PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend)) : The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from [PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend).\n\ntask (`str`, defaults to `\"\"`) : A task-identifier for the pipeline.\n\nnum_workers (`int`, *optional*, defaults to 8) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TableQuestionAnsweringPipeline[[transformers.TableQuestionAnsweringPipeline]]", "char_start": 93456, "char_end": 94336, "token_estimate": 220, "prev_chunk_id": 847, "next_chunk_id": 849, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 849, "text": "batch_size (`int`, *optional*, defaults to 1) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .\n\nargs_parser ([ArgumentHandler](/docs/transformers/v5.6.2/en/internal/pipelines_utils#transformers.pipelines.ArgumentHandler), *optional*) : Reference to the object in charge of parsing supplied pipeline parameters.\n\ndevice (`int`, *optional*, defaults to -1) : Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too\n\ndtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`)", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TableQuestionAnsweringPipeline[[transformers.TableQuestionAnsweringPipeline]]", "char_start": 25832, "char_end": 26825, "token_estimate": 248, "prev_chunk_id": 848, "next_chunk_id": 850, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 850, "text": "binary_output (`bool`, *optional*, defaults to `False`) : Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text.\n\n**Returns:**\n\n`A dictionary or a list of dictionaries containing results`\n\nEach result is a dictionary with the following\nkeys:\n\n- **answer** (`str`) -- The answer of the query given the table. If there is an aggregator, the answer will\n be preceded by `AGGREGATOR >`.\n- **coordinates** (`list[tuple[int, int]]`) -- Coordinates of the cells of the answers.\n- **cells** (`list[str]`) -- List of strings made up of the answer cell values.\n- **aggregator** (`str`) -- If the model has an aggregator, this returns the aggregator.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TableQuestionAnsweringPipeline[[transformers.TableQuestionAnsweringPipeline]]", "char_start": 103656, "char_end": 104373, "token_estimate": 179, "prev_chunk_id": 849, "next_chunk_id": 851, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 851, "text": "### TextClassificationPipeline[[transformers.TextClassificationPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "TextClassificationPipeline[[transformers.TextClassificationPipeline]]", "char_start": 104375, "char_end": 104448, "token_estimate": 18, "prev_chunk_id": 850, "next_chunk_id": 852, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 852, "text": "#### transformers.TextClassificationPipeline[[transformers.TextClassificationPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/text_classification.py#L43)\n\nText classification pipeline using any `ModelForSequenceClassification`. See the [sequence classification\nexamples](../task_summary#sequence-classification) for more information.\n\nExample:\n\n```python\n>>> from transformers import pipeline\n\n>>> classifier = pipeline(model=\"distilbert/distilbert-base-uncased-finetuned-sst-2-english\")\n>>> classifier(\"This movie is disgustingly good !\")\n[{'label': 'POSITIVE', 'score': 1.0}]\n\n>>> classifier(\"Director tried too much.\")\n[{'label': 'NEGATIVE', 'score': 0.996}]\n```\n\nLearn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TextClassificationPipeline[[transformers.TextClassificationPipeline]]", "char_start": 104450, "char_end": 105268, "token_estimate": 204, "prev_chunk_id": 851, "next_chunk_id": 853, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 853, "text": "This text classification pipeline can currently be loaded from [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline) using the following task identifier:\n`\"sentiment-analysis\"` (for classifying sequences according to positive or negative sentiments).\n\nIf multiple classification labels are available (`model.config.num_labels >= 2`), the pipeline will run a softmax\nover the results. If there is a single label, the pipeline will run a sigmoid over the result. In case of regression\ntasks (`model.config.problem_type == \"regression\"`), will not apply any function on the output.\n\nThe models that this pipeline can use are models that have been fine-tuned on a sequence classification task. See\nthe up-to-date list of available models on\n[huggingface.co/models](https://huggingface.co/models?filter=text-classification).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TextClassificationPipeline[[transformers.TextClassificationPipeline]]", "char_start": 105270, "char_end": 106123, "token_estimate": 213, "prev_chunk_id": 852, "next_chunk_id": 854, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 854, "text": "__call__transformers.TextClassificationPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/text_classification.py#L105[{\"name\": \"inputs\", \"val\": \": str | list[str] | dict[str, str] | list[dict[str, str]]\"}, {\"name\": \"**kwargs\", \"val\": \": typing.Any\"}]- **inputs** (`str` or `list[str]` or `dict[str]`, or `list[dict[str]]`) --\n One or several texts to classify. In order to use text pairs for your classification, you can send a\n dictionary containing `{\"text\", \"text_pair\"}` keys, or a list of those.\n- **top_k** (`int`, *optional*, defaults to `1`) --\n How many results to return.\n- **function_to_apply** (`str`, *optional*, defaults to `\"default\"`) --\n The function to apply to the model outputs in order to retrieve the scores. Accepts four different\n values:\n\n If this argument is not specified, then it will apply the following functions according to the number\n of labels:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TextClassificationPipeline[[transformers.TextClassificationPipeline]]", "char_start": 106125, "char_end": 107059, "token_estimate": 233, "prev_chunk_id": 853, "next_chunk_id": 855, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 855, "text": "- If problem type is regression, will not apply any function on the output.\n - If the model has a single label, will apply the sigmoid function on the output.\n - If the model has several labels, will apply the softmax function on the output.\n\n Possible values are:\n\n - `\"sigmoid\"`: Applies the sigmoid function on the output.\n - `\"softmax\"`: Applies the softmax function on the output.\n - `\"none\"`: Does not apply any function on the output.0A list of `dict`Each result comes as list of dictionaries with the following keys:\n\n- **label** (`str`) -- The label predicted.\n- **score** (`float`) -- The corresponding probability.\n\nIf `top_k` is used, one such dictionary is returned per label.\n\nClassify the text(s) given as inputs.\n\n**Parameters:**", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TextClassificationPipeline[[transformers.TextClassificationPipeline]]", "char_start": 107063, "char_end": 107814, "token_estimate": 187, "prev_chunk_id": 854, "next_chunk_id": 856, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 856, "text": "model ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).\n\ntokenizer ([PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend)) : The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from [PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend).\n\ntask (`str`, defaults to `\"\"`) : A task-identifier for the pipeline.\n\nnum_workers (`int`, *optional*, defaults to 8) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TextClassificationPipeline[[transformers.TextClassificationPipeline]]", "char_start": 93456, "char_end": 94336, "token_estimate": 220, "prev_chunk_id": 855, "next_chunk_id": 857, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 857, "text": "batch_size (`int`, *optional*, defaults to 1) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .\n\nargs_parser ([ArgumentHandler](/docs/transformers/v5.6.2/en/internal/pipelines_utils#transformers.pipelines.ArgumentHandler), *optional*) : Reference to the object in charge of parsing supplied pipeline parameters.\n\ndevice (`int`, *optional*, defaults to -1) : Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too\n\ndtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`)", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TextClassificationPipeline[[transformers.TextClassificationPipeline]]", "char_start": 25832, "char_end": 26825, "token_estimate": 248, "prev_chunk_id": 856, "next_chunk_id": 858, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 858, "text": "binary_output (`bool`, *optional*, defaults to `False`) : Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text.\n\nfunction_to_apply (`str`, *optional*, defaults to `\"default\"`) : The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. In case of regression tasks, will not apply any function on the output. - `\"sigmoid\"`: Applies the sigmoid function on the output. - `\"softmax\"`: Applies the softmax function on the output. - `\"none\"`: Does not apply any function on the output.\n\n**Returns:**\n\n`A list of `dict``\n\nEach result comes as list of dictionaries with the following keys:\n\n- **label** (`str`) -- The label predicted.\n- **score** (`float`) -- The corresponding probability.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TextClassificationPipeline[[transformers.TextClassificationPipeline]]", "char_start": 109693, "char_end": 110679, "token_estimate": 246, "prev_chunk_id": 857, "next_chunk_id": 859, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 859, "text": "If `top_k` is used, one such dictionary is returned per label.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TextClassificationPipeline[[transformers.TextClassificationPipeline]]", "char_start": 107696, "char_end": 107758, "token_estimate": 15, "prev_chunk_id": 858, "next_chunk_id": 860, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 860, "text": "### TextGenerationPipeline[[transformers.TextGenerationPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "TextGenerationPipeline[[transformers.TextGenerationPipeline]]", "char_start": 110745, "char_end": 110810, "token_estimate": 16, "prev_chunk_id": 859, "next_chunk_id": 861, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 861, "text": "#### transformers.TextGenerationPipeline[[transformers.TextGenerationPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/text_generation.py#L23)\n\nLanguage generation pipeline using any `ModelWithLMHead` or `ModelForCausalLM`. This pipeline predicts the words\nthat will follow a specified text prompt. When the underlying model is a conversational model, it can also accept\none or more chats, in which case the pipeline will operate in chat mode and will continue the chat(s) by adding\nits response(s). Each chat takes the form of a list of dicts, where each dict contains \"role\" and \"content\" keys.\n\nUnless the model you're using explicitly sets these generation parameters in its configuration files\n(`generation_config.json`), the following default values will be used:\n- max_new_tokens: 256\n- do_sample: True\n- temperature: 0.7\n\nExamples:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TextGenerationPipeline[[transformers.TextGenerationPipeline]]", "char_start": 110812, "char_end": 111705, "token_estimate": 223, "prev_chunk_id": 860, "next_chunk_id": 862, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 862, "text": "```python\n>>> from transformers import pipeline\n\n>>> generator = pipeline(model=\"openai-community/gpt2\")\n>>> generator(\"I can't believe you did such a \", do_sample=False)\n[{'generated_text': \"I can't believe you did such a icky thing to me. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I\"}]\n\n>>> # These parameters will return suggestions, and only the newly created text making it easier for prompting suggestions.\n>>> outputs = generator(\"My tart needs some\", num_return_sequences=4, return_full_text=False)\n```", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TextGenerationPipeline[[transformers.TextGenerationPipeline]]", "char_start": 111707, "char_end": 112273, "token_estimate": 141, "prev_chunk_id": 861, "next_chunk_id": 863, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 863, "text": "```python\n>>> from transformers import pipeline\n\n>>> generator = pipeline(model=\"HuggingFaceH4/zephyr-7b-beta\")\n>>> # Zephyr-beta is a conversational model, so let's pass it a chat instead of a single string\n>>> generator([{\"role\": \"user\", \"content\": \"What is the capital of France? Answer in one word.\"}], do_sample=False, max_new_tokens=2)\n[{'generated_text': [{'role': 'user', 'content': 'What is the capital of France? Answer in one word.'}, {'role': 'assistant', 'content': 'Paris'}]}]\n```\n\nLearn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial). You can pass text\ngeneration parameters to this pipeline to control stopping criteria, decoding strategy, and more. Learn more about\ntext generation parameters in [Text generation strategies](../generation_strategies) and [Text\ngeneration](text_generation).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TextGenerationPipeline[[transformers.TextGenerationPipeline]]", "char_start": 112275, "char_end": 113126, "token_estimate": 212, "prev_chunk_id": 862, "next_chunk_id": 864, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 864, "text": "This language generation pipeline can currently be loaded from [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline) using the following task identifier:\n`\"text-generation\"`.\n\nThe models that this pipeline can use are models that have been trained with an autoregressive language modeling\nobjective. See the list of available [text completion models](https://huggingface.co/models?filter=text-generation)\nand the list of [conversational models](https://huggingface.co/models?other=conversational)\non [huggingface.co/models].", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TextGenerationPipeline[[transformers.TextGenerationPipeline]]", "char_start": 113128, "char_end": 113686, "token_estimate": 139, "prev_chunk_id": 863, "next_chunk_id": 865, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 865, "text": "__call__transformers.TextGenerationPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/text_generation.py#L249[{\"name\": \"text_inputs\", \"val\": \"\"}, {\"name\": \"**kwargs\", \"val\": \"\"}]- **text_inputs** (`str`, `list[str]`, `ChatType`, or `list[ChatType]`) --\n One or several prompts (or one list of prompts) to complete. If strings or a list of string are\n passed, this pipeline will continue each prompt. Alternatively, a \"chat\", in the form of a list\n of dicts with \"role\" and \"content\" keys, can be passed, or a list of such chats. When chats are passed,\n the model's chat template will be used to format them before passing them to the model.\n- **return_tensors** (`bool`, *optional*, defaults to `False`) --\n Returns the tensors of predictions (as token indices) in the outputs. If set to\n `True`, the decoded text is not returned.\n- **return_text** (`bool`, *optional*) --\n Returns the decoded texts in the outputs.\n- **return_full_text** (`bool`, *optional*, defaults to `True`) --\n If set to `False` only added text is returned, otherwise the full text is returned. Cannot be\n specified at the same time as `return_text`.\n- **clean_up_tokenization_spaces** (`bool`, *optional*, defaults to `True`) --\n Whether or not to clean up the potential extra spaces in the text output.\n- **continue_final_message(** `bool`, *optional*) -- This indicates that you want the model to continue the\n last message in the input chat rather than starting a new one, allowing you to \"prefill\" its response.\n By default this is `True` when the final message in the input chat has the `assistant` role and\n `False` otherwise, but you can manually override that behaviour by setting this flag.\n- **prefix** (`str`, *optional*) --\n Prefix added to prompt.\n- **handle_long_generation** (`str`, *optional*) --\n By default, this pipelines does not handle long generation (ones that exceed in one form or the other\n the model maximum length). There is no perfect way to address this (more info\n :https://github.com/huggingface/transformers/issues/14033#issuecomment-948385227). This provides common\n strategies to work around that problem depending on your use case.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TextGenerationPipeline[[transformers.TextGenerationPipeline]]", "char_start": 113688, "char_end": 115896, "token_estimate": 552, "prev_chunk_id": 864, "next_chunk_id": 866, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 866, "text": "- `None` : default strategy where nothing in particular happens\n - `\"hole\"`: Truncates left of input, and leaves a gap wide enough to let generation happen (might\n truncate a lot of the prompt and not suitable when generation exceed the model capacity)\n- **tokenizer_encode_kwargs** (`dict`, *optional*) --\n Additional keyword arguments to pass along to the encoding step of the tokenizer. If the text input is\n a chat, it is passed to `apply_chat_template`. Otherwise, it is passed to `__call__`.\n- **generate_kwargs** (`dict`, *optional*) --\n Additional keyword arguments to pass along to the generate method of the model (see the generate method\n [here](./text_generation)).0A list or a list of lists of `dict`Returns one of the following dictionaries (cannot return a combination\nof both `generated_text` and `generated_token_ids`):", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TextGenerationPipeline[[transformers.TextGenerationPipeline]]", "char_start": 115900, "char_end": 116744, "token_estimate": 211, "prev_chunk_id": 865, "next_chunk_id": 867, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 867, "text": "- **generated_text** (`str`, present when `return_text=True`) -- The generated text.\n- **generated_token_ids** (`torch.Tensor`, present when `return_tensors=True`) -- The token\n ids of the generated text.\n\nComplete the prompt(s) given as inputs.\n\n**Parameters:**\n\nmodel ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).\n\ntokenizer ([PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend)) : The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from [PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend).\n\ntask (`str`, defaults to `\"\"`) : A task-identifier for the pipeline.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TextGenerationPipeline[[transformers.TextGenerationPipeline]]", "char_start": 116746, "char_end": 117713, "token_estimate": 241, "prev_chunk_id": 866, "next_chunk_id": 868, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 868, "text": "num_workers (`int`, *optional*, defaults to 8) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used.\n\nbatch_size (`int`, *optional*, defaults to 1) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .\n\nargs_parser ([ArgumentHandler](/docs/transformers/v5.6.2/en/internal/pipelines_utils#transformers.pipelines.ArgumentHandler), *optional*) : Reference to the object in charge of parsing supplied pipeline parameters.\n\ndevice (`int`, *optional*, defaults to -1) : Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TextGenerationPipeline[[transformers.TextGenerationPipeline]]", "char_start": 25654, "char_end": 26622, "token_estimate": 242, "prev_chunk_id": 867, "next_chunk_id": 869, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 869, "text": "dtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`)\n\nbinary_output (`bool`, *optional*, defaults to `False`) : Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text.\n\n**Returns:**\n\n`A list or a list of lists of `dict``\n\nReturns one of the following dictionaries (cannot return a combination\nof both `generated_text` and `generated_token_ids`):\n\n- **generated_text** (`str`, present when `return_text=True`) -- The generated text.\n- **generated_token_ids** (`torch.Tensor`, present when `return_tensors=True`) -- The token\n ids of the generated text.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TextGenerationPipeline[[transformers.TextGenerationPipeline]]", "char_start": 118685, "char_end": 119462, "token_estimate": 194, "prev_chunk_id": 868, "next_chunk_id": 870, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 870, "text": "### TokenClassificationPipeline[[transformers.TokenClassificationPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "TokenClassificationPipeline[[transformers.TokenClassificationPipeline]]", "char_start": 119464, "char_end": 119539, "token_estimate": 18, "prev_chunk_id": 869, "next_chunk_id": 871, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 871, "text": "#### transformers.TokenClassificationPipeline[[transformers.TokenClassificationPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/token_classification.py#L92)\n\nNamed Entity Recognition pipeline using any `ModelForTokenClassification`. See the [named entity recognition\nexamples](../task_summary#named-entity-recognition) for more information.\n\nExample:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TokenClassificationPipeline[[transformers.TokenClassificationPipeline]]", "char_start": 119541, "char_end": 119946, "token_estimate": 101, "prev_chunk_id": 870, "next_chunk_id": 872, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 872, "text": "```python\n>>> from transformers import pipeline\n\n>>> token_classifier = pipeline(model=\"Jean-Baptiste/camembert-ner\", aggregation_strategy=\"simple\")\n>>> sentence = \"Je m'appelle jean-baptiste et je vis \u00e0 montr\u00e9al\"\n>>> tokens = token_classifier(sentence)\n>>> tokens\n[{'entity_group': 'PER', 'score': 0.9931, 'word': 'jean-baptiste', 'start': 12, 'end': 26}, {'entity_group': 'LOC', 'score': 0.998, 'word': 'montr\u00e9al', 'start': 38, 'end': 47}]\n\n>>> token = tokens[0]\n>>> # Start and end provide an easy way to highlight words in the original text.\n>>> sentence[token[\"start\"] : token[\"end\"]]\n' jean-baptiste'\n\n>>> # Some models use the same idea to do part of speech.\n>>> syntaxer = pipeline(model=\"vblagoje/bert-english-uncased-finetuned-pos\", aggregation_strategy=\"simple\")\n>>> syntaxer(\"My name is Sarah and I live in London\")\n[{'entity_group': 'PRON', 'score': 0.999, 'word': 'my', 'start': 0, 'end': 2}, {'entity_group': 'NOUN', 'score': 0.997, 'word': 'name', 'start': 3, 'end': 7}, {'entity_group': 'AUX', 'score': 0.994, 'word': 'is', 'start': 8, 'end': 10}, {'entity_group': 'PROPN', 'score': 0.999, 'word': 'sarah', 'start': 11, 'end': 16}, {'entity_group': 'CCONJ', 'score': 0.999, 'word': 'and', 'start': 17, 'end': 20}, {'entity_group': 'PRON', 'score': 0.999, 'word': 'i', 'start': 21, 'end': 22}, {'entity_group': 'VERB', 'score': 0.998, 'word': 'live', 'start': 23, 'end': 27}, {'entity_group': 'ADP', 'score': 0.999, 'word': 'in', 'start': 28, 'end': 30}, {'entity_group': 'PROPN', 'score': 0.999, 'word': 'london', 'start': 31, 'end': 37}]\n```", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TokenClassificationPipeline[[transformers.TokenClassificationPipeline]]", "char_start": 119948, "char_end": 121507, "token_estimate": 389, "prev_chunk_id": 871, "next_chunk_id": 873, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 873, "text": "Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)\n\nThis token recognition pipeline can currently be loaded from [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline) using the following task identifier:\n`\"ner\"` (for predicting the classes of tokens in a sequence: person, organisation, location or miscellaneous).\n\nThe models that this pipeline can use are models that have been fine-tuned on a token classification task. See the\nup-to-date list of available models on\n[huggingface.co/models](https://huggingface.co/models?filter=token-classification).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TokenClassificationPipeline[[transformers.TokenClassificationPipeline]]", "char_start": 121509, "char_end": 122142, "token_estimate": 158, "prev_chunk_id": 872, "next_chunk_id": 874, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 874, "text": "__call__transformers.TokenClassificationPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/token_classification.py#L209[{\"name\": \"inputs\", \"val\": \": str | list[str]\"}, {\"name\": \"**kwargs\", \"val\": \": typing.Any\"}]- **inputs** (`str` or `List[str]`) --\n One or several texts (or one list of texts) for token classification. Can be pre-tokenized when\n `is_split_into_words=True`.0A list or a list of list of `dict`Each result comes as a list of dictionaries (one for each token in the\ncorresponding input, or each entity if this pipeline was instantiated with an aggregation_strategy) with\nthe following keys:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TokenClassificationPipeline[[transformers.TokenClassificationPipeline]]", "char_start": 122144, "char_end": 122801, "token_estimate": 164, "prev_chunk_id": 873, "next_chunk_id": 875, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 875, "text": "- **word** (`str`) -- The token/word classified. This is obtained by decoding the selected tokens. If you\n want to have the exact string in the original sentence, use `start` and `end`.\n- **score** (`float`) -- The corresponding probability for `entity`.\n- **entity** (`str`) -- The entity predicted for that token/word (it is named *entity_group* when\n *aggregation_strategy* is not `\"none\"`.\n- **index** (`int`, only present when `aggregation_strategy=\"none\"`) -- The index of the corresponding\n token in the sentence.\n- **start** (`int`, *optional*) -- The index of the start of the corresponding entity in the sentence. Only\n exists if the offsets are available within the tokenizer\n- **end** (`int`, *optional*) -- The index of the end of the corresponding entity in the sentence. Only\n exists if the offsets are available within the tokenizer\n\nClassify each token of the text(s) given as inputs.\n\n**Parameters:**", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TokenClassificationPipeline[[transformers.TokenClassificationPipeline]]", "char_start": 122803, "char_end": 123726, "token_estimate": 230, "prev_chunk_id": 874, "next_chunk_id": 876, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 876, "text": "model ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).\n\ntokenizer ([PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend)) : The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from [PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend).\n\ntask (`str`, defaults to `\"\"`) : A task-identifier for the pipeline.\n\nnum_workers (`int`, *optional*, defaults to 8) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TokenClassificationPipeline[[transformers.TokenClassificationPipeline]]", "char_start": 93456, "char_end": 94336, "token_estimate": 220, "prev_chunk_id": 875, "next_chunk_id": 877, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 877, "text": "batch_size (`int`, *optional*, defaults to 1) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .\n\nargs_parser ([ArgumentHandler](/docs/transformers/v5.6.2/en/internal/pipelines_utils#transformers.pipelines.ArgumentHandler), *optional*) : Reference to the object in charge of parsing supplied pipeline parameters.\n\ndevice (`int`, *optional*, defaults to -1) : Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too\n\ndtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`)", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TokenClassificationPipeline[[transformers.TokenClassificationPipeline]]", "char_start": 25832, "char_end": 26825, "token_estimate": 248, "prev_chunk_id": 876, "next_chunk_id": 878, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 878, "text": "binary_output (`bool`, *optional*, defaults to `False`) : Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text.\n\nignore_labels (`list[str]`, defaults to `[\"O\"]`) : A list of labels to ignore.\n\nstride (`int`, *optional*) : If stride is provided, the pipeline is applied on all the text. The text is split into chunks of size model_max_length. Works only with fast tokenizers and `aggregation_strategy` different from `NONE`. The value of this argument defines the number of overlapping tokens between chunks. In other words, the model will shift forward by `tokenizer.model_max_length - stride` tokens each step.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TokenClassificationPipeline[[transformers.TokenClassificationPipeline]]", "char_start": 125605, "char_end": 126294, "token_estimate": 172, "prev_chunk_id": 877, "next_chunk_id": 879, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 879, "text": "aggregation_strategy (`str`, *optional*, defaults to `\"none\"`) : The strategy to fuse (or not) tokens based on the model prediction. - \"none\" : Will simply not do any aggregation and simply return raw results from the model - \"simple\" : Will attempt to group entities following the default schema. (A, B-TAG), (B, I-TAG), (C, I-TAG), (D, B-TAG2) (E, B-TAG2) will end up being [{\"word\": ABC, \"entity\": \"TAG\"}, {\"word\": \"D\", \"entity\": \"TAG2\"}, {\"word\": \"E\", \"entity\": \"TAG2\"}] Notice that two consecutive B tags will end up as different entities. On word based languages, we might end up splitting words undesirably : Imagine Microsoft being tagged as [{\"word\": \"Micro\", \"entity\": \"ENTERPRISE\"}, {\"word\": \"soft\", \"entity\": \"NAME\"}]. Look for FIRST, MAX, AVERAGE for ways to mitigate that and disambiguate words (on languages that support that meaning, which is basically tokens separated by a space). These mitigations will only work on real words, \"New york\" might still be tagged with two different entities. - \"first\" : (works only on word based models) Will use the `SIMPLE` strategy except that words, cannot end up with different tags. Words will simply use the tag of the first token of the word when there is ambiguity. - \"average\" : (works only on word based models) Will use the `SIMPLE` strategy except that words, cannot end up with different tags. scores will be averaged first across tokens, and then the maximum label is applied. - \"max\" : (works only on word based models) Will use the `SIMPLE` strategy except that words, cannot end up with different tags. Word entity will simply be the token with the maximum score.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TokenClassificationPipeline[[transformers.TokenClassificationPipeline]]", "char_start": 126296, "char_end": 127929, "token_estimate": 408, "prev_chunk_id": 878, "next_chunk_id": 880, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 880, "text": "**Returns:**\n\n`A list or a list of list of `dict``\n\nEach result comes as a list of dictionaries (one for each token in the\ncorresponding input, or each entity if this pipeline was instantiated with an aggregation_strategy) with\nthe following keys:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TokenClassificationPipeline[[transformers.TokenClassificationPipeline]]", "char_start": 127931, "char_end": 128178, "token_estimate": 61, "prev_chunk_id": 879, "next_chunk_id": 881, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 881, "text": "- **word** (`str`) -- The token/word classified. This is obtained by decoding the selected tokens. If you\n want to have the exact string in the original sentence, use `start` and `end`.\n- **score** (`float`) -- The corresponding probability for `entity`.\n- **entity** (`str`) -- The entity predicted for that token/word (it is named *entity_group* when\n *aggregation_strategy* is not `\"none\"`.\n- **index** (`int`, only present when `aggregation_strategy=\"none\"`) -- The index of the corresponding\n token in the sentence.\n- **start** (`int`, *optional*) -- The index of the start of the corresponding entity in the sentence. Only\n exists if the offsets are available within the tokenizer\n- **end** (`int`, *optional*) -- The index of the end of the corresponding entity in the sentence. Only\n exists if the offsets are available within the tokenizer", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.TokenClassificationPipeline[[transformers.TokenClassificationPipeline]]", "char_start": 122803, "char_end": 123656, "token_estimate": 213, "prev_chunk_id": 880, "next_chunk_id": 882, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 882, "text": "#### aggregate_words[[transformers.TokenClassificationPipeline.aggregate_words]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/token_classification.py#L521)\n\nOverride tokens from a given word that disagree to force agreement on word boundaries.\n\nExample: micro|soft| com|pany| B-ENT I-NAME I-ENT I-ENT will be rewritten with first strategy as microsoft|\ncompany| B-ENT I-ENT", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "aggregate_words[[transformers.TokenClassificationPipeline.aggregate_words]]", "char_start": 129034, "char_end": 129455, "token_estimate": 105, "prev_chunk_id": 881, "next_chunk_id": 883, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 883, "text": "#### gather_pre_entities[[transformers.TokenClassificationPipeline.gather_pre_entities]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/token_classification.py#L397)\n\nFuse various numpy arrays into dicts with all the information needed for aggregation", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "gather_pre_entities[[transformers.TokenClassificationPipeline.gather_pre_entities]]", "char_start": 129456, "char_end": 129753, "token_estimate": 74, "prev_chunk_id": 882, "next_chunk_id": 884, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 884, "text": "#### group_entities[[transformers.TokenClassificationPipeline.group_entities]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/token_classification.py#L584)\n\nFind and group together the adjacent tokens with the same entity predicted.\n\n**Parameters:**\n\nentities (`dict`) : The entities predicted by the pipeline.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "group_entities[[transformers.TokenClassificationPipeline.group_entities]]", "char_start": 129754, "char_end": 130110, "token_estimate": 89, "prev_chunk_id": 883, "next_chunk_id": 885, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 885, "text": "#### group_sub_entities[[transformers.TokenClassificationPipeline.group_sub_entities]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/token_classification.py#L549)\n\nGroup together the adjacent tokens with the same entity predicted.\n\n**Parameters:**\n\nentities (`dict`) : The entities predicted by the pipeline.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "group_sub_entities[[transformers.TokenClassificationPipeline.group_sub_entities]]", "char_start": 130111, "char_end": 130466, "token_estimate": 88, "prev_chunk_id": 884, "next_chunk_id": 886, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 886, "text": "### ZeroShotClassificationPipeline[[transformers.ZeroShotClassificationPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "ZeroShotClassificationPipeline[[transformers.ZeroShotClassificationPipeline]]", "char_start": 130468, "char_end": 130549, "token_estimate": 20, "prev_chunk_id": 885, "next_chunk_id": 887, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 887, "text": "#### transformers.ZeroShotClassificationPipeline[[transformers.ZeroShotClassificationPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/zero_shot_classification.py#L44)\n\nNLI-based zero-shot classification pipeline using a `ModelForSequenceClassification` trained on NLI (natural\nlanguage inference) tasks. Equivalent of `text-classification` pipelines, but these models don't require a\nhardcoded number of potential classes, they can be chosen at runtime. It usually means it's slower but it is\n**much** more flexible.\n\nAny combination of sequences and labels can be passed and each combination will be posed as a premise/hypothesis\npair and passed to the pretrained model. Then, the logit for *entailment* is taken as the logit for the candidate\nlabel being valid. Any NLI model can be used, but the id of the *entailment* label must be included in the model\nconfig's :attr:*~transformers.PreTrainedConfig.label2id*.\n\nExample:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotClassificationPipeline[[transformers.ZeroShotClassificationPipeline]]", "char_start": 130551, "char_end": 131531, "token_estimate": 245, "prev_chunk_id": 886, "next_chunk_id": 888, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 888, "text": "```python\n>>> from transformers import pipeline\n\n>>> oracle = pipeline(model=\"facebook/bart-large-mnli\")\n>>> oracle(\n... \"I have a problem with my iphone that needs to be resolved asap!!\",\n... candidate_labels=[\"urgent\", \"not urgent\", \"phone\", \"tablet\", \"computer\"],\n... )\n{'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['urgent', 'phone', 'computer', 'not urgent', 'tablet'], 'scores': [0.504, 0.479, 0.013, 0.003, 0.002]}\n\n>>> oracle(\n... \"I have a problem with my iphone that needs to be resolved asap!!\",\n... candidate_labels=[\"english\", \"german\"],\n... )\n{'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['english', 'german'], 'scores': [0.814, 0.186]}\n```\n\nLearn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotClassificationPipeline[[transformers.ZeroShotClassificationPipeline]]", "char_start": 131533, "char_end": 132393, "token_estimate": 215, "prev_chunk_id": 887, "next_chunk_id": 889, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 889, "text": "This NLI pipeline can currently be loaded from [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline) using the following task identifier:\n`\"zero-shot-classification\"`.\n\nThe models that this pipeline can use are models that have been fine-tuned on an NLI task. See the up-to-date list\nof available models on [huggingface.co/models](https://huggingface.co/models?search=nli).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotClassificationPipeline[[transformers.ZeroShotClassificationPipeline]]", "char_start": 132395, "char_end": 132802, "token_estimate": 101, "prev_chunk_id": 888, "next_chunk_id": 890, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 890, "text": "__call__transformers.ZeroShotClassificationPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/zero_shot_classification.py#L159[{\"name\": \"sequences\", \"val\": \": str | list[str]\"}, {\"name\": \"*args\", \"val\": \"\"}, {\"name\": \"**kwargs\", \"val\": \"\"}]- **sequences** (`str` or `list[str]`) --\n The sequence(s) to classify, will be truncated if the model input is too large.\n- **candidate_labels** (`str` or `list[str]`) --\n The set of possible class labels to classify each sequence into. Can be a single label, a string of\n comma-separated labels, or a list of labels.\n- **hypothesis_template** (`str`, *optional*, defaults to `\"This example is {}.\"`) --\n The template used to turn each label into an NLI-style hypothesis. This template must include a {} or\n similar syntax for the candidate label to be inserted into the template. For example, the default\n template is `\"This example is {}.\"` With the candidate label `\"sports\"`, this would be fed into the\n model like `\" sequence to classify This example is sports . \"`. The default template\n works well in many cases, but it may be worthwhile to experiment with different templates depending on\n the task setting.\n- **multi_label** (`bool`, *optional*, defaults to `False`) --\n Whether or not multiple candidate labels can be true. If `False`, the scores are normalized such that\n the sum of the label likelihoods for each sequence is 1. If `True`, the labels are considered\n independent and probabilities are normalized for each candidate by doing a softmax of the entailment\n score vs. the contradiction score.0A `dict` or a list of `dict`Each result comes as a dictionary with the following keys:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotClassificationPipeline[[transformers.ZeroShotClassificationPipeline]]", "char_start": 132804, "char_end": 134509, "token_estimate": 426, "prev_chunk_id": 889, "next_chunk_id": 891, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 891, "text": "- **sequence** (`str`) -- The sequence for which this is the output.\n- **labels** (`list[str]`) -- The labels sorted by order of likelihood.\n- **scores** (`list[float]`) -- The probabilities for each of the labels.\n\nClassify the sequence(s) given as inputs. See the [ZeroShotClassificationPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.ZeroShotClassificationPipeline) documentation for more\ninformation.\n\n**Parameters:**\n\nmodel ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotClassificationPipeline[[transformers.ZeroShotClassificationPipeline]]", "char_start": 134511, "char_end": 135269, "token_estimate": 189, "prev_chunk_id": 890, "next_chunk_id": 892, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 892, "text": "tokenizer ([PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend)) : The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from [PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend).\n\ntask (`str`, defaults to `\"\"`) : A task-identifier for the pipeline.\n\nnum_workers (`int`, *optional*, defaults to 8) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used.\n\nbatch_size (`int`, *optional*, defaults to 1) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotClassificationPipeline[[transformers.ZeroShotClassificationPipeline]]", "char_start": 93766, "char_end": 94677, "token_estimate": 227, "prev_chunk_id": 891, "next_chunk_id": 893, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 893, "text": "args_parser ([ArgumentHandler](/docs/transformers/v5.6.2/en/internal/pipelines_utils#transformers.pipelines.ArgumentHandler), *optional*) : Reference to the object in charge of parsing supplied pipeline parameters.\n\ndevice (`int`, *optional*, defaults to -1) : Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too\n\ndtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`)\n\nbinary_output (`bool`, *optional*, defaults to `False`) : Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text.\n\n**Returns:**\n\n`A `dict` or a list of `dict``\n\nEach result comes as a dictionary with the following keys:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotClassificationPipeline[[transformers.ZeroShotClassificationPipeline]]", "char_start": 136184, "char_end": 137133, "token_estimate": 237, "prev_chunk_id": 892, "next_chunk_id": 894, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 894, "text": "- **sequence** (`str`) -- The sequence for which this is the output.\n- **labels** (`list[str]`) -- The labels sorted by order of likelihood.\n- **scores** (`list[float]`) -- The probabilities for each of the labels.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ZeroShotClassificationPipeline[[transformers.ZeroShotClassificationPipeline]]", "char_start": 134511, "char_end": 134725, "token_estimate": 53, "prev_chunk_id": 893, "next_chunk_id": 895, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 895, "text": "## Multimodal\n\nPipelines available for multimodal tasks include the following.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "Multimodal", "char_start": 137351, "char_end": 137429, "token_estimate": 19, "prev_chunk_id": 894, "next_chunk_id": 896, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 896, "text": "### DocumentQuestionAnsweringPipeline[[transformers.DocumentQuestionAnsweringPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "DocumentQuestionAnsweringPipeline[[transformers.DocumentQuestionAnsweringPipeline]]", "char_start": 137431, "char_end": 137518, "token_estimate": 21, "prev_chunk_id": 895, "next_chunk_id": 897, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 897, "text": "#### transformers.DocumentQuestionAnsweringPipeline[[transformers.DocumentQuestionAnsweringPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/document_question_answering.py#L206)\n\nDocument Question Answering pipeline using any `AutoModelForDocumentQuestionAnswering`. The inputs/outputs are\nsimilar to the (extractive) question answering pipeline; however, the pipeline takes an image (and optional OCR'd\nwords/boxes) as input instead of text context.\n\nUnless the model you're using explicitly sets these generation parameters in its configuration files\n(`generation_config.json`), the following default values will be used:\n- max_new_tokens: 256\n\nExample:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.DocumentQuestionAnsweringPipeline[[transformers.DocumentQuestionAnsweringPipeline]]", "char_start": 137520, "char_end": 138229, "token_estimate": 177, "prev_chunk_id": 896, "next_chunk_id": 898, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 898, "text": "```python\n>>> from transformers import pipeline\n\n>>> document_qa = pipeline(model=\"impira/layoutlm-document-qa\")\n>>> document_qa(\n... image=\"https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png\",\n... question=\"What is the invoice number?\",\n... )\n[{'score': 0.425, 'answer': 'us-001', 'start': 16, 'end': 16}]\n```\n\nLearn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)\n\nThis document question answering pipeline can currently be loaded from [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline) using the following task\nidentifier: `\"document-question-answering\"`.\n\nThe models that this pipeline can use are models that have been fine-tuned on a document question answering task.\nSee the up-to-date list of available models on\n[huggingface.co/models](https://huggingface.co/models?filter=document-question-answering).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.DocumentQuestionAnsweringPipeline[[transformers.DocumentQuestionAnsweringPipeline]]", "char_start": 138231, "char_end": 139186, "token_estimate": 238, "prev_chunk_id": 897, "next_chunk_id": 899, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 899, "text": "__call__transformers.DocumentQuestionAnsweringPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/document_question_answering.py#L336[{\"name\": \"image\", \"val\": \": typing.Union[ForwardRef('Image.Image'), str, list[dict[str, typing.Any]]]\"}, {\"name\": \"question\", \"val\": \": str | None = None\"}, {\"name\": \"word_boxes\", \"val\": \": tuple[str, list[float]] | None = None\"}, {\"name\": \"**kwargs\", \"val\": \": typing.Any\"}]- **image** (`str` or `PIL.Image`) --\n The pipeline handles three types of images:\n\n - A string containing a http link pointing to an image\n - A string containing a local path to an image\n - An image loaded in PIL directly", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.DocumentQuestionAnsweringPipeline[[transformers.DocumentQuestionAnsweringPipeline]]", "char_start": 139188, "char_end": 139871, "token_estimate": 170, "prev_chunk_id": 898, "next_chunk_id": 900, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 900, "text": "The pipeline accepts either a single image or a batch of images. If given a single image, it can be\n broadcasted to multiple questions.\n- **question** (`str`) --\n A question to ask of the document.\n- **word_boxes** (`list[str, tuple[float, float, float, float]]`, *optional*) --\n A list of words and bounding boxes (normalized 0->1000). If you provide this optional input, then the\n pipeline will use these words and boxes instead of running OCR on the image to derive them for models\n that need them (e.g. LayoutLM). This allows you to reuse OCR'd results across many invocations of the\n pipeline without having to re-run it each time.\n- **top_k** (`int`, *optional*, defaults to 1) --\n The number of answers to return (will be chosen by order of likelihood). Note that we return less than\n top_k answers if there are not enough options available within the context.\n- **doc_stride** (`int`, *optional*, defaults to 128) --\n If the words in the document are too long to fit with the question for the model, it will be split in\n several chunks with some overlap. This argument controls the size of that overlap.\n- **max_answer_len** (`int`, *optional*, defaults to 15) --\n The maximum length of predicted answers (e.g., only answers with a shorter length are considered).\n- **max_seq_len** (`int`, *optional*, defaults to 384) --\n The maximum length of the total sentence (context + question) in tokens of each chunk passed to the\n model. The context will be split in several chunks (using `doc_stride` as overlap) if needed.\n- **max_question_len** (`int`, *optional*, defaults to 64) --\n The maximum length of the question after tokenization. It will be truncated if needed.\n- **handle_impossible_answer** (`bool`, *optional*, defaults to `False`) --\n Whether or not we accept impossible as an answer.\n- **lang** (`str`, *optional*) --\n Language to use while running OCR. Defaults to english.\n- **tesseract_config** (`str`, *optional*) --\n Additional flags to pass to tesseract while running OCR.\n- **timeout** (`float`, *optional*, defaults to None) --\n The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and\n the call may block forever.0A `dict` or a list of `dict`Each result comes as a dictionary with the following keys:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.DocumentQuestionAnsweringPipeline[[transformers.DocumentQuestionAnsweringPipeline]]", "char_start": 139875, "char_end": 142166, "token_estimate": 573, "prev_chunk_id": 899, "next_chunk_id": 901, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 901, "text": "- **score** (`float`) -- The probability associated to the answer.\n- **start** (`int`) -- The start word index of the answer (in the OCR'd version of the input or provided\n `word_boxes`).\n- **end** (`int`) -- The end word index of the answer (in the OCR'd version of the input or provided\n `word_boxes`).\n- **answer** (`str`) -- The answer to the question.\n- **words** (`list[int]`) -- The index of each word/box pair that is in the answer\n\nAnswer the question(s) given as inputs by using the document(s). A document is defined as an image and an\noptional list of (word, box) tuples which represent the text in the document. If the `word_boxes` are not\nprovided, it will use the Tesseract OCR engine (if available) to extract the words and boxes automatically for\nLayoutLM-like models which require them as input. For Donut, no OCR is run.\n\nYou can invoke the pipeline several ways:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.DocumentQuestionAnsweringPipeline[[transformers.DocumentQuestionAnsweringPipeline]]", "char_start": 142168, "char_end": 143052, "token_estimate": 221, "prev_chunk_id": 900, "next_chunk_id": 902, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 902, "text": "- `pipeline(image=image, question=question)`\n- `pipeline(image=image, question=question, word_boxes=word_boxes)`\n- `pipeline([{\"image\": image, \"question\": question}])`\n- `pipeline([{\"image\": image, \"question\": question, \"word_boxes\": word_boxes}])`\n\n**Parameters:**\n\nmodel ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).\n\ntokenizer ([PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend)) : The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from [PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.DocumentQuestionAnsweringPipeline[[transformers.DocumentQuestionAnsweringPipeline]]", "char_start": 143054, "char_end": 143953, "token_estimate": 224, "prev_chunk_id": 901, "next_chunk_id": 903, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 903, "text": "image_processor ([BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor)) : The image processor that will be used by the pipeline to encode data for the model. This object inherits from [BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor).\n\ntask (`str`, defaults to `\"\"`) : A task-identifier for the pipeline.\n\nnum_workers (`int`, *optional*, defaults to 8) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used.\n\nbatch_size (`int`, *optional*, defaults to 1) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.DocumentQuestionAnsweringPipeline[[transformers.DocumentQuestionAnsweringPipeline]]", "char_start": 48482, "char_end": 49425, "token_estimate": 235, "prev_chunk_id": 902, "next_chunk_id": 904, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 904, "text": "args_parser ([ArgumentHandler](/docs/transformers/v5.6.2/en/internal/pipelines_utils#transformers.pipelines.ArgumentHandler), *optional*) : Reference to the object in charge of parsing supplied pipeline parameters.\n\ndevice (`int`, *optional*, defaults to -1) : Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too\n\ndtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`)\n\nbinary_output (`bool`, *optional*, defaults to `False`) : Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text.\n\n**Returns:**\n\n`A `dict` or a list of `dict``\n\nEach result comes as a dictionary with the following keys:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.DocumentQuestionAnsweringPipeline[[transformers.DocumentQuestionAnsweringPipeline]]", "char_start": 136184, "char_end": 137133, "token_estimate": 237, "prev_chunk_id": 903, "next_chunk_id": 905, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 905, "text": "- **score** (`float`) -- The probability associated to the answer.\n- **start** (`int`) -- The start word index of the answer (in the OCR'd version of the input or provided\n `word_boxes`).\n- **end** (`int`) -- The end word index of the answer (in the OCR'd version of the input or provided\n `word_boxes`).\n- **answer** (`str`) -- The answer to the question.\n- **words** (`list[int]`) -- The index of each word/box pair that is in the answer", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.DocumentQuestionAnsweringPipeline[[transformers.DocumentQuestionAnsweringPipeline]]", "char_start": 142168, "char_end": 142609, "token_estimate": 110, "prev_chunk_id": 904, "next_chunk_id": 906, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 906, "text": "### FeatureExtractionPipeline[[transformers.FeatureExtractionPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "FeatureExtractionPipeline[[transformers.FeatureExtractionPipeline]]", "char_start": 146294, "char_end": 146365, "token_estimate": 17, "prev_chunk_id": 905, "next_chunk_id": 907, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 907, "text": "#### transformers.FeatureExtractionPipeline[[transformers.FeatureExtractionPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/feature_extraction.py#L15)\n\nFeature extraction pipeline uses no model head. This pipeline extracts the hidden states from the base\ntransformer, which can be used as features in downstream tasks.\n\nExample:\n\n```python\n>>> from transformers import pipeline\n\n>>> extractor = pipeline(model=\"google-bert/bert-base-uncased\", task=\"feature-extraction\")\n>>> result = extractor(\"This is a simple test.\", return_tensors=True)\n>>> result.shape # This is a tensor of shape [1, sequence_length, hidden_dimension] representing the input string.\ntorch.Size([1, 8, 768])\n```\n\nLearn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.FeatureExtractionPipeline[[transformers.FeatureExtractionPipeline]]", "char_start": 146367, "char_end": 147203, "token_estimate": 209, "prev_chunk_id": 906, "next_chunk_id": 908, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 908, "text": "This feature extraction pipeline can currently be loaded from [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline) using the task identifier:\n`\"feature-extraction\"`.\n\nAll models may be used for this pipeline. See a list of all models, including community-contributed models on\n[huggingface.co/models](https://huggingface.co/models).\n\n__call__transformers.FeatureExtractionPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/feature_extraction.py#L78[{\"name\": \"*args\", \"val\": \": str | list[str]\"}, {\"name\": \"**kwargs\", \"val\": \": typing.Any\"}]- **args** (`str` or `list[str]`) -- One or several texts (or one list of texts) to get the features of.0A nested list of `float`The features computed by the model.\n\nExtract the features of the input(s) text.\n\n**Parameters:**", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.FeatureExtractionPipeline[[transformers.FeatureExtractionPipeline]]", "char_start": 147205, "char_end": 148054, "token_estimate": 212, "prev_chunk_id": 907, "next_chunk_id": 909, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 909, "text": "model ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).\n\ntokenizer ([PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend)) : The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from [PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend).\n\ntask (`str`, defaults to `\"\"`) : A task-identifier for the pipeline.\n\nnum_workers (`int`, *optional*, defaults to 8) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.FeatureExtractionPipeline[[transformers.FeatureExtractionPipeline]]", "char_start": 93456, "char_end": 94336, "token_estimate": 220, "prev_chunk_id": 908, "next_chunk_id": 910, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 910, "text": "batch_size (`int`, *optional*, defaults to 1) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .\n\nargs_parser ([ArgumentHandler](/docs/transformers/v5.6.2/en/internal/pipelines_utils#transformers.pipelines.ArgumentHandler), *optional*) : Reference to the object in charge of parsing supplied pipeline parameters.\n\ndevice (`int`, *optional*, defaults to -1) : Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too\n\ndtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`)", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.FeatureExtractionPipeline[[transformers.FeatureExtractionPipeline]]", "char_start": 25832, "char_end": 26825, "token_estimate": 248, "prev_chunk_id": 909, "next_chunk_id": 911, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 911, "text": "tokenize_kwargs (`dict`, *optional*) : Additional dictionary of keyword arguments passed along to the tokenizer.\n\nreturn_tensors (`bool`, *optional*) : If `True`, returns a tensor according to the specified framework, otherwise returns a list.\n\n**Returns:**\n\n`A nested list of `float``\n\nThe features computed by the model.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.FeatureExtractionPipeline[[transformers.FeatureExtractionPipeline]]", "char_start": 149933, "char_end": 150255, "token_estimate": 80, "prev_chunk_id": 910, "next_chunk_id": 912, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 912, "text": "### ImageFeatureExtractionPipeline[[transformers.ImageFeatureExtractionPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "ImageFeatureExtractionPipeline[[transformers.ImageFeatureExtractionPipeline]]", "char_start": 150257, "char_end": 150338, "token_estimate": 20, "prev_chunk_id": 911, "next_chunk_id": 913, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 913, "text": "#### transformers.ImageFeatureExtractionPipeline[[transformers.ImageFeatureExtractionPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/image_feature_extraction.py#L23)\n\nImage feature extraction pipeline uses no model head. This pipeline extracts the hidden states from the base\ntransformer, which can be used as features in downstream tasks.\n\nExample:\n\n```python\n>>> from transformers import pipeline\n\n>>> extractor = pipeline(model=\"google/vit-base-patch16-224\", task=\"image-feature-extraction\")\n>>> result = extractor(\"https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png\", return_tensors=True)\n>>> result.shape # This is a tensor of shape [1, sequence_length, hidden_dimension] representing the input image.\ntorch.Size([1, 197, 768])\n```\n\nLearn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageFeatureExtractionPipeline[[transformers.ImageFeatureExtractionPipeline]]", "char_start": 150340, "char_end": 151252, "token_estimate": 228, "prev_chunk_id": 912, "next_chunk_id": 914, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 914, "text": "This image feature extraction pipeline can currently be loaded from [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline) using the task identifier:\n`\"image-feature-extraction\"`.\n\nAll vision models may be used for this pipeline. See a list of all models, including community-contributed models on\n[huggingface.co/models](https://huggingface.co/models).\n\n__call__transformers.ImageFeatureExtractionPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/image_feature_extraction.py#L94[{\"name\": \"*args\", \"val\": \": typing.Union[str, ForwardRef('Image.Image'), list['Image.Image'], list[str]]\"}, {\"name\": \"**kwargs\", \"val\": \": typing.Any\"}]- **images** (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`) --\n The pipeline handles three types of images:\n\n - A string containing a http link pointing to an image\n - A string containing a local path to an image\n - An image loaded in PIL directly", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageFeatureExtractionPipeline[[transformers.ImageFeatureExtractionPipeline]]", "char_start": 151254, "char_end": 152228, "token_estimate": 243, "prev_chunk_id": 913, "next_chunk_id": 915, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 915, "text": "The pipeline accepts either a single image or a batch of images, which must then be passed as a string.\n Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL\n images.\n- **timeout** (`float`, *optional*, defaults to None) --\n The maximum time in seconds to wait for fetching images from the web. If None, no timeout is used and\n the call may block forever.0A nested list of `float`The features computed by the model.\n\nExtract the features of the input(s).\n\n**Parameters:**\n\nmodel ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageFeatureExtractionPipeline[[transformers.ImageFeatureExtractionPipeline]]", "char_start": 152232, "char_end": 153067, "token_estimate": 208, "prev_chunk_id": 914, "next_chunk_id": 916, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 916, "text": "image_processor ([BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor)) : The image processor that will be used by the pipeline to encode data for the model. This object inherits from [BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor).\n\ntask (`str`, defaults to `\"\"`) : A task-identifier for the pipeline.\n\nnum_workers (`int`, *optional*, defaults to 8) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used.\n\nbatch_size (`int`, *optional*, defaults to 1) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageFeatureExtractionPipeline[[transformers.ImageFeatureExtractionPipeline]]", "char_start": 48482, "char_end": 49425, "token_estimate": 235, "prev_chunk_id": 915, "next_chunk_id": 917, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 917, "text": "args_parser ([ArgumentHandler](/docs/transformers/v5.6.2/en/internal/pipelines_utils#transformers.pipelines.ArgumentHandler), *optional*) : Reference to the object in charge of parsing supplied pipeline parameters.\n\ndevice (`int`, *optional*, defaults to -1) : Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too\n\ndtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`)\n\nbinary_output (`bool`, *optional*, defaults to `False`) : Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text.\n\nimage_processor_kwargs (`dict`, *optional*) : Additional dictionary of keyword arguments passed along to the image processor e.g. {\"size\": {\"height\": 100, \"width\": 100}}", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageFeatureExtractionPipeline[[transformers.ImageFeatureExtractionPipeline]]", "char_start": 154014, "char_end": 155028, "token_estimate": 253, "prev_chunk_id": 916, "next_chunk_id": 918, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 918, "text": "pool (`bool`, *optional*, defaults to `False`) : Whether or not to return the pooled output. If `False`, the model will return the raw hidden states.\n\n**Returns:**\n\n`A nested list of `float``\n\nThe features computed by the model.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageFeatureExtractionPipeline[[transformers.ImageFeatureExtractionPipeline]]", "char_start": 155030, "char_end": 155258, "token_estimate": 57, "prev_chunk_id": 917, "next_chunk_id": 919, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 919, "text": "### ImageTextToTextPipeline[[transformers.ImageTextToTextPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "ImageTextToTextPipeline[[transformers.ImageTextToTextPipeline]]", "char_start": 155260, "char_end": 155327, "token_estimate": 16, "prev_chunk_id": 918, "next_chunk_id": 920, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 920, "text": "#### transformers.ImageTextToTextPipeline[[transformers.ImageTextToTextPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/image_text_to_text.py#L53)\n\nImage-text-to-text pipeline using an `AutoModelForImageTextToText`. This pipeline generates text given an image and text.\nWhen the underlying model is a conversational model, it can also accept one or more chats,\nin which case the pipeline will operate in chat mode and will continue the chat(s) by adding its response(s).\nEach chat takes the form of a list of dicts, where each dict contains \"role\" and \"content\" keys.\n\nUnless the model you're using explicitly sets these generation parameters in its configuration files\n(`generation_config.json`), the following default values will be used:\n- max_new_tokens: 256\n\nExample:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageTextToTextPipeline[[transformers.ImageTextToTextPipeline]]", "char_start": 155329, "char_end": 156156, "token_estimate": 206, "prev_chunk_id": 919, "next_chunk_id": 921, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 921, "text": "```python\n>>> from transformers import pipeline\n\n>>> pipe = pipeline(task=\"image-text-to-text\", model=\"Salesforce/blip-image-captioning-base\")\n>>> pipe(\"https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png\", text=\"A photo of\")\n[{'generated_text': 'a photo of two birds'}]\n```", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageTextToTextPipeline[[transformers.ImageTextToTextPipeline]]", "char_start": 156158, "char_end": 156452, "token_estimate": 73, "prev_chunk_id": 920, "next_chunk_id": 922, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 922, "text": "```python\n>>> from transformers import pipeline\n\n>>> pipe = pipeline(\"image-text-to-text\", model=\"llava-hf/llava-interleave-qwen-0.5b-hf\")\n>>> messages = [\n>>> {\n>>> \"role\": \"user\",\n>>> \"content\": [\n>>> {\n>>> \"type\": \"image\",\n>>> \"url\": \"https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg\",\n>>> },\n>>> {\"type\": \"text\", \"text\": \"Describe this image.\"},\n>>> ],\n>>> },\n>>> {\n>>> \"role\": \"assistant\",\n>>> \"content\": [\n>>> {\"type\": \"text\", \"text\": \"There is a dog and\"},\n>>> ],\n>>> },\n>>> ]\n>>> pipe(text=messages, max_new_tokens=20, return_full_text=False)\n[{'input_text': [{'role': 'user',\n 'content': [{'type': 'image',\n 'url': 'https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg'},\n {'type': 'text', 'text': 'Describe this image.'}]},\n{'role': 'assistant',\n 'content': [{'type': 'text', 'text': 'There is a dog and'}]}],\n'generated_text': ' a person in the image. The dog is sitting on the sand, and the person is sitting on'}]\n```", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageTextToTextPipeline[[transformers.ImageTextToTextPipeline]]", "char_start": 156454, "char_end": 157584, "token_estimate": 282, "prev_chunk_id": 921, "next_chunk_id": 923, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 923, "text": "Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)\n\nThis image-text to text pipeline can currently be loaded from pipeline() using the following task identifier:\n\"image-text-to-text\".\n\nSee the list of available models on\n[huggingface.co/models](https://huggingface.co/models?pipeline_tag=image-text-to-text).\n\n__call__transformers.ImageTextToTextPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/image_text_to_text.py#L216[{\"name\": \"images\", \"val\": \": typing.Union[str, list[str], list[list[str]], ForwardRef('Image.Image'), list['Image.Image'], list[list['Image.Image']], list[dict], NoneType] = None\"}, {\"name\": \"text\", \"val\": \": str | list[str] | list[dict] | None = None\"}, {\"name\": \"**kwargs\", \"val\": \"\"}]- **images** (`str`, `list[str]`, `PIL.Image, `list[PIL.Image]`, `list[dict[str, Union[str, PIL.Image]]]`) --\n The pipeline handles three types of images:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageTextToTextPipeline[[transformers.ImageTextToTextPipeline]]", "char_start": 157586, "char_end": 158547, "token_estimate": 240, "prev_chunk_id": 922, "next_chunk_id": 924, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 924, "text": "- A string containing a HTTP(s) link pointing to an image\n - A string containing a local path to an image\n - An image loaded in PIL directly", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageTextToTextPipeline[[transformers.ImageTextToTextPipeline]]", "char_start": 158551, "char_end": 158693, "token_estimate": 36, "prev_chunk_id": 923, "next_chunk_id": 925, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 925, "text": "The pipeline accepts either a single image or a batch of images. Finally, this pipeline also supports\n the chat format (see `text`) containing images and text in this argument.\n- **text** (str, list[str], `list[dict[str, Union[str, PIL.Image]]]`) --\n The text to be used for generation. If a list of strings is passed, the length of the list should be\n the same as the number of images. Text can also follow the chat format: a list of dictionaries where\n each dictionary represents a message in a conversation. Each dictionary should have two keys: 'role'\n and 'content'. 'role' should be one of 'user', 'system' or 'assistant'. 'content' should be a list of\n dictionary containing the text of the message and the type of the message. The type of the message\n can be either 'text' or 'image'. If the type is 'image', no text is needed.\n- **return_tensors** (`bool`, *optional*, defaults to `False`) --\n Returns the tensors of predictions (as token indices) in the outputs. If set to\n `True`, the decoded text is not returned.\n- **return_text** (`bool`, *optional*) --\n Returns the decoded texts in the outputs.\n- **return_full_text** (`bool`, *optional*, defaults to `True`) --\n If set to `False` only added text is returned, otherwise the full text is returned. Cannot be\n specified at the same time as `return_text`.\n- **clean_up_tokenization_spaces** (`bool`, *optional*, defaults to `True`) --\n Whether or not to clean up the potential extra spaces in the text output.\n- **continue_final_message(** `bool`, *optional*) -- This indicates that you want the model to continue the\n last message in the input chat rather than starting a new one, allowing you to \"prefill\" its response.\n By default this is `True` when the final message in the input chat has the `assistant` role and\n `False` otherwise, but you can manually override that behaviour by setting this flag.0A list or a list of list of `dict`Each result comes as a dictionary with the following key (cannot\nreturn a combination of both `generated_text` and `generated_token_ids`):", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageTextToTextPipeline[[transformers.ImageTextToTextPipeline]]", "char_start": 158697, "char_end": 160754, "token_estimate": 514, "prev_chunk_id": 924, "next_chunk_id": 926, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 926, "text": "- **generated_text** (`str`, present when `return_text=True`) -- The generated text.\n- **generated_token_ids** (`torch.Tensor`, present when `return_tensors=True`) -- The token\n ids of the generated text.\n- **input_text** (`str`) -- The input text.\n\nGenerate a text given text and the image(s) passed as inputs.\n\n**Parameters:**\n\nmodel ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageTextToTextPipeline[[transformers.ImageTextToTextPipeline]]", "char_start": 160756, "char_end": 161395, "token_estimate": 159, "prev_chunk_id": 925, "next_chunk_id": 927, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 927, "text": "processor ([ProcessorMixin](/docs/transformers/v5.6.2/en/main_classes/processors#transformers.ProcessorMixin)) : The processor that will be used by the pipeline to encode data for the model. This object inherits from [ProcessorMixin](/docs/transformers/v5.6.2/en/main_classes/processors#transformers.ProcessorMixin). Processor is a composite object that might contain `tokenizer`, `feature_extractor`, and `image_processor`.\n\ntask (`str`, defaults to `\"\"`) : A task-identifier for the pipeline.\n\nnum_workers (`int`, *optional*, defaults to 8) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used.\n\nbatch_size (`int`, *optional*, defaults to 1) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageTextToTextPipeline[[transformers.ImageTextToTextPipeline]]", "char_start": 161397, "char_end": 162410, "token_estimate": 253, "prev_chunk_id": 926, "next_chunk_id": 928, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 928, "text": "args_parser ([ArgumentHandler](/docs/transformers/v5.6.2/en/internal/pipelines_utils#transformers.pipelines.ArgumentHandler), *optional*) : Reference to the object in charge of parsing supplied pipeline parameters.\n\ndevice (`int`, *optional*, defaults to -1) : Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too\n\ndtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`)\n\nbinary_output (`bool`, *optional*, defaults to `False`) : Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text.\n\n**Returns:**\n\n`A list or a list of list of `dict``", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageTextToTextPipeline[[transformers.ImageTextToTextPipeline]]", "char_start": 162412, "char_end": 163307, "token_estimate": 223, "prev_chunk_id": 927, "next_chunk_id": 929, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 929, "text": "Each result comes as a dictionary with the following key (cannot\nreturn a combination of both `generated_text` and `generated_token_ids`):\n\n- **generated_text** (`str`, present when `return_text=True`) -- The generated text.\n- **generated_token_ids** (`torch.Tensor`, present when `return_tensors=True`) -- The token\n ids of the generated text.\n- **input_text** (`str`) -- The input text.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.ImageTextToTextPipeline[[transformers.ImageTextToTextPipeline]]", "char_start": 160616, "char_end": 161005, "token_estimate": 97, "prev_chunk_id": 928, "next_chunk_id": 930, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 930, "text": "### AnyToAnyPipeline[[transformers.AnyToAnyPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "AnyToAnyPipeline[[transformers.AnyToAnyPipeline]]", "char_start": 163700, "char_end": 163753, "token_estimate": 13, "prev_chunk_id": 929, "next_chunk_id": 931, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 931, "text": "#### transformers.AnyToAnyPipeline[[transformers.AnyToAnyPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/any_to_any.py#L67)\n\nMultimodal Generation pipeline using an `AutoModelForMultimodalLM`. This pipeline generates text given any\ncombination of multimodal data and text.When the underlying model is a conversational model, it can also\naccept one or more chats, in which case the pipeline will operate in chat mode and will continue the\nchat(s) by adding its response(s). Each chat takes the form of a list of dicts, where each dict contains\n\"role\" and \"content\" keys.\n\nUnless the model you're using explicitly sets these generation parameters in its configuration files\n(`generation_config.json`), the following default values will be used:\n- max_new_tokens: 256\n\nExample:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AnyToAnyPipeline[[transformers.AnyToAnyPipeline]]", "char_start": 163755, "char_end": 164585, "token_estimate": 207, "prev_chunk_id": 930, "next_chunk_id": 932, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 932, "text": "```python\n>>> from transformers import pipeline\n\n>>> pipe = pipeline(task=\"any-to-any\", model=\"google/gemma-3n-E4B-it\")\n>>> pipe(\"https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png\", text=\"A photo of\")\n[{'generated_text': 'a photo of two birds'}]\n```", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AnyToAnyPipeline[[transformers.AnyToAnyPipeline]]", "char_start": 164587, "char_end": 164858, "token_estimate": 67, "prev_chunk_id": 931, "next_chunk_id": 933, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 933, "text": "```python\n>>> from transformers import pipeline\n\n>>> pipe = pipeline(\"any-to-any\", model=\"google/gemma-3n-E4B-it\")\n>>> messages = [\n>>> {\n>>> \"role\": \"user\",\n>>> \"content\": [\n>>> {\n>>> \"type\": \"image\",\n>>> \"url\": \"https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg\",\n>>> },\n>>> {\"type\": \"text\", \"text\": \"Describe this image.\"},\n>>> ],\n>>> },\n>>> {\n>>> \"role\": \"assistant\",\n>>> \"content\": [\n>>> {\"type\": \"text\", \"text\": \"There is a dog and\"},\n>>> ],\n>>> },\n>>> ]\n>>> pipe(text=messages, max_new_tokens=20, return_full_text=False)\n[{'input_text': [{'role': 'user',\n 'content': [{'type': 'image',\n 'url': 'https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg'},\n {'type': 'text', 'text': 'Describe this image.'}]},\n{'role': 'assistant',\n 'content': [{'type': 'text', 'text': 'There is a dog and'}]}],\n'generated_text': ' a person in the image. The dog is sitting on the sand, and the person is sitting on'}]\n```", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AnyToAnyPipeline[[transformers.AnyToAnyPipeline]]", "char_start": 164860, "char_end": 165966, "token_estimate": 276, "prev_chunk_id": 932, "next_chunk_id": 934, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 934, "text": "Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)\n\nThis multimodal pipeline can currently be loaded from pipeline() using the following task identifier:\n\"any-to-any\".\n\nSee the list of available models on\n[huggingface.co/models](https://huggingface.co/models?pipeline_tag=any-to-any).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AnyToAnyPipeline[[transformers.AnyToAnyPipeline]]", "char_start": 165968, "char_end": 166298, "token_estimate": 82, "prev_chunk_id": 933, "next_chunk_id": 935, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 935, "text": "__call__transformers.AnyToAnyPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/any_to_any.py#L258[{\"name\": \"text\", \"val\": \": str | list[str] | list[dict]\"}, {\"name\": \"images\", \"val\": \": typing.Union[str, list[str], list[list[str]], ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None\"}, {\"name\": \"videos\", \"val\": \": typing.Union[str, list[str], list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = None\"}, {\"name\": \"audio\", \"val\": \": typing.Union[str, list[str], numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = None\"}, {\"name\": \"**kwargs\", \"val\": \"\"}]- **text** (`str`, `list[str]`, `list[dict]`) --\n The text to be used for generation. If a list of strings is passed, the length of the list should be\n the same as the number of images. Text can also follow the chat format: a list of dictionaries where\n each dictionary represents a message in a conversation. Each dictionary should have two keys: 'role'\n and 'content'. 'role' should be one of 'user', 'system' or 'assistant'. 'content' should be a list of\n dictionary containing the text of the message and the type of the message.\n- **images** (`str`, `list[str]`, `ImageInput`) --\n The pipeline handles three types of images:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AnyToAnyPipeline[[transformers.AnyToAnyPipeline]]", "char_start": 166300, "char_end": 168108, "token_estimate": 452, "prev_chunk_id": 934, "next_chunk_id": 936, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 936, "text": "- A string containing a HTTP(s) link pointing to an image\n - A string containing a local path to an image\n - An image loaded in PIL directly\n\n The pipeline accepts either a single image or a batch of images. Finally, this pipeline also supports\n the chat format (see `text`) containing images and text in this argument.\n- **videos** (`str`, `list[str]`, `VideoInput`) --\n The pipeline handles three types of videos:\n\n - A string containing a HTTP(s) link pointing to a video\n - A string containing a local path to a video\n - A video loaded and decoded to array format\n\n The pipeline accepts either a single video or a batch of videos. Finally, this pipeline also supports\n the chat format (see `text`) containing videos and text in this argument.\n- **audio** (`str`, `list[str]`, `AudioInput`) --\n The pipeline handles three types of audios:\n\n - A string containing a HTTP(s) link pointing to an audio\n - A string containing a local path to an audio\n - An audio loaded in PIL directly", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AnyToAnyPipeline[[transformers.AnyToAnyPipeline]]", "char_start": 168112, "char_end": 169110, "token_estimate": 249, "prev_chunk_id": 935, "next_chunk_id": 937, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 937, "text": "The pipeline accepts either a single audios or a batch of audios. Finally, this pipeline also supports\n the chat format (see `text`) containing audios and text in this argument.\n- **return_tensors** (`bool`, *optional*, defaults to `False`) --\n Returns the tensors of predictions (as token indices) in the outputs. If set to\n `True`, the decoded text is not returned.\n- **return_text** (`bool`, *optional*) --\n Returns the decoded texts in the outputs.\n- **return_full_text** (`bool`, *optional*, defaults to `True`) --\n If set to `False` only added text is returned, otherwise the full text is returned. Cannot be\n specified at the same time as `return_text`.\n- **clean_up_tokenization_spaces** (`bool`, *optional*, defaults to `True`) --\n Whether or not to clean up the potential extra spaces in the text output.\n- **continue_final_message(** `bool`, *optional*) -- This indicates that you want the model to continue the\n last message in the input chat rather than starting a new one, allowing you to \"prefill\" its response.\n By default this is `True` when the final message in the input chat has the `assistant` role and\n `False` otherwise, but you can manually override that behaviour by setting this flag.0A list or a list of list of `dict`Each result comes as a dictionary with the following key (cannot\nreturn a combination of both `generated_text` and `generated_token_ids`):", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AnyToAnyPipeline[[transformers.AnyToAnyPipeline]]", "char_start": 169114, "char_end": 170507, "token_estimate": 348, "prev_chunk_id": 936, "next_chunk_id": 938, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 938, "text": "- **generated_text** (`str`, present when `return_text=True` and `generation_mode=\"text\"`) -- The generated text.\n- **generated_audio** (`np.ndarray`, present when `generation_mode=\"audio\"`) -- The generated audio.\n- **generated_image** (`PIL.Image.Image`, present when `generation_mode=\"image\"`) -- The generated image.\n- **generated_token_ids** (`torch.Tensor`, present when `return_tensors=True` and `generation_mode=\"text\"`) -- The token\n ids of the generated text.\n- **input_text** (`str`) -- The input text.\n\nGenerate a text given text and optionally multimodal data passed as inputs.\n\n**Parameters:**\n\nmodel ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AnyToAnyPipeline[[transformers.AnyToAnyPipeline]]", "char_start": 170509, "char_end": 171427, "token_estimate": 229, "prev_chunk_id": 937, "next_chunk_id": 939, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 939, "text": "processor ([ProcessorMixin](/docs/transformers/v5.6.2/en/main_classes/processors#transformers.ProcessorMixin)) : The processor that will be used by the pipeline to encode data for the model. This object inherits from [ProcessorMixin](/docs/transformers/v5.6.2/en/main_classes/processors#transformers.ProcessorMixin). Processor is a composite object that might contain `tokenizer`, `feature_extractor`, and `image_processor`.\n\ntask (`str`, defaults to `\"\"`) : A task-identifier for the pipeline.\n\nnum_workers (`int`, *optional*, defaults to 8) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used.\n\nbatch_size (`int`, *optional*, defaults to 1) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AnyToAnyPipeline[[transformers.AnyToAnyPipeline]]", "char_start": 161397, "char_end": 162410, "token_estimate": 253, "prev_chunk_id": 938, "next_chunk_id": 940, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 940, "text": "args_parser ([ArgumentHandler](/docs/transformers/v5.6.2/en/internal/pipelines_utils#transformers.pipelines.ArgumentHandler), *optional*) : Reference to the object in charge of parsing supplied pipeline parameters.\n\ndevice (`int`, *optional*, defaults to -1) : Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too\n\ndtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`)\n\nbinary_output (`bool`, *optional*, defaults to `False`) : Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text.\n\n**Returns:**\n\n`A list or a list of list of `dict``", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AnyToAnyPipeline[[transformers.AnyToAnyPipeline]]", "char_start": 162412, "char_end": 163307, "token_estimate": 223, "prev_chunk_id": 939, "next_chunk_id": 941, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 941, "text": "Each result comes as a dictionary with the following key (cannot\nreturn a combination of both `generated_text` and `generated_token_ids`):\n\n- **generated_text** (`str`, present when `return_text=True` and `generation_mode=\"text\"`) -- The generated text.\n- **generated_audio** (`np.ndarray`, present when `generation_mode=\"audio\"`) -- The generated audio.\n- **generated_image** (`PIL.Image.Image`, present when `generation_mode=\"image\"`) -- The generated image.\n- **generated_token_ids** (`torch.Tensor`, present when `return_tensors=True` and `generation_mode=\"text\"`) -- The token\n ids of the generated text.\n- **input_text** (`str`) -- The input text.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.AnyToAnyPipeline[[transformers.AnyToAnyPipeline]]", "char_start": 170369, "char_end": 171023, "token_estimate": 163, "prev_chunk_id": 940, "next_chunk_id": 942, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 942, "text": "### MaskGenerationPipeline[[transformers.MaskGenerationPipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "MaskGenerationPipeline[[transformers.MaskGenerationPipeline]]", "char_start": 173997, "char_end": 174062, "token_estimate": 16, "prev_chunk_id": 941, "next_chunk_id": 943, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 943, "text": "#### transformers.MaskGenerationPipeline[[transformers.MaskGenerationPipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/mask_generation.py#L36)\n\nAutomatic mask generation for images using `SamForMaskGeneration`. This pipeline predicts binary masks for an\nimage, given an image. It is a `ChunkPipeline` because you can separate the points in a mini-batch in order to\navoid OOM issues. Use the `points_per_batch` argument to control the number of points that will be processed at the\nsame time. Default is `64`.\n\nThe pipeline works in 3 steps:\n1. `preprocess`: A grid of 1024 points evenly separated is generated along with bounding boxes and point\n labels.\n For more details on how the points and bounding boxes are created, check the `_generate_crop_boxes`\n function. The image is also preprocessed using the `image_processor`. This function `yields` a minibatch of\n `points_per_batch`.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.MaskGenerationPipeline[[transformers.MaskGenerationPipeline]]", "char_start": 174064, "char_end": 175011, "token_estimate": 236, "prev_chunk_id": 942, "next_chunk_id": 944, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 944, "text": "2. `forward`: feeds the outputs of `preprocess` to the model. The image embedding is computed only once.\n Calls both `self.model.get_image_embeddings` and makes sure that the gradients are not computed, and the\n tensors and models are on the same device.\n\n3. `postprocess`: The most important part of the automatic mask generation happens here. Three steps\n are induced:\n - image_processor.postprocess_masks (run on each minibatch loop): takes in the raw output masks,\n resizes them according\n to the image size, and transforms there to binary masks.\n - image_processor.filter_masks (on each minibatch loop): uses both `pred_iou_thresh` and\n `stability_scores`. Also\n applies a variety of filters based on non maximum suppression to remove bad masks.\n - image_processor.postprocess_masks_for_amg applies the NSM on the mask to only keep relevant ones.\n\nExample:", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.MaskGenerationPipeline[[transformers.MaskGenerationPipeline]]", "char_start": 175013, "char_end": 175898, "token_estimate": 221, "prev_chunk_id": 943, "next_chunk_id": 945, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 945, "text": "```python\n>>> from transformers import pipeline\n\n>>> generator = pipeline(model=\"facebook/sam-vit-base\", task=\"mask-generation\")\n>>> outputs = generator(\n... \"http://images.cocodataset.org/val2017/000000039769.jpg\",\n... )\n\n>>> outputs = generator(\n... \"https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png\", points_per_batch=128\n... )\n```\n\nLearn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)\n\nThis segmentation pipeline can currently be loaded from [pipeline()](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.pipeline) using the following task identifier:\n`\"mask-generation\"`.\n\nSee the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=mask-generation).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.MaskGenerationPipeline[[transformers.MaskGenerationPipeline]]", "char_start": 175900, "char_end": 176682, "token_estimate": 195, "prev_chunk_id": 944, "next_chunk_id": 946, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 946, "text": "__call__transformers.MaskGenerationPipeline.__call__https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/mask_generation.py#L143[{\"name\": \"image\", \"val\": \": typing.Union[str, ForwardRef('Image.Image'), list[str], list['Image.Image']]\"}, {\"name\": \"*args\", \"val\": \": typing.Any\"}, {\"name\": \"**kwargs\", \"val\": \": typing.Any\"}]- **image** (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`) --\n Image or list of images.\n- **mask_threshold** (`float`, *optional*, defaults to 0.0) --\n Threshold to use when turning the predicted masks into binary values.\n- **pred_iou_thresh** (`float`, *optional*, defaults to 0.88) --\n A filtering threshold in `[0,1]` applied on the model's predicted mask quality.\n- **stability_score_thresh** (`float`, *optional*, defaults to 0.95) --\n A filtering threshold in `[0,1]`, using the stability of the mask under changes to the cutoff used to\n binarize the model's mask predictions.\n- **stability_score_offset** (`int`, *optional*, defaults to 1) --\n The amount to shift the cutoff when calculated the stability score.\n- **crops_nms_thresh** (`float`, *optional*, defaults to 0.7) --\n The box IoU cutoff used by non-maximal suppression to filter duplicate masks.\n- **crops_n_layers** (`int`, *optional*, defaults to 0) --\n If `crops_n_layers>0`, mask prediction will be run again on crops of the image. Sets the number of\n layers to run, where each layer has 2**i_layer number of image crops.\n- **crop_overlap_ratio** (`float`, *optional*, defaults to `512 / 1500`) --\n Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of\n the image length. Later layers with more crops scale down this overlap.\n- **crop_n_points_downscale_factor** (`int`, *optional*, defaults to `1`) --\n The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n.\n- **timeout** (`float`, *optional*, defaults to None) --\n The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and\n the call may block forever.0`Dict`A dictionary with the following keys:\n- **mask** (`PIL.Image`) -- A binary mask of the detected object as a PIL Image of shape `(width,\n height)` of the original image. Returns a mask filled with zeros if no object is found.\n- **score** (*optional* `float`) -- Optionally, when the model is capable of estimating a confidence of\n the \"object\" described by the label and the mask.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.MaskGenerationPipeline[[transformers.MaskGenerationPipeline]]", "char_start": 176684, "char_end": 179161, "token_estimate": 619, "prev_chunk_id": 945, "next_chunk_id": 947, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 947, "text": "Generates binary segmentation masks\n\n**Parameters:**\n\nmodel ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).\n\nimage_processor ([BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor)) : The image processor that will be used by the pipeline to encode data for the model. This object inherits from [BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor).\n\ntask (`str`, defaults to `\"\"`) : A task-identifier for the pipeline.\n\nnum_workers (`int`, *optional*, defaults to 8) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.MaskGenerationPipeline[[transformers.MaskGenerationPipeline]]", "char_start": 179163, "char_end": 180129, "token_estimate": 241, "prev_chunk_id": 946, "next_chunk_id": 948, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 948, "text": "batch_size (`int`, *optional*, defaults to 1) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .\n\nargs_parser ([ArgumentHandler](/docs/transformers/v5.6.2/en/internal/pipelines_utils#transformers.pipelines.ArgumentHandler), *optional*) : Reference to the object in charge of parsing supplied pipeline parameters.\n\ndevice (`int`, *optional*, defaults to -1) : Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too\n\ndtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`)", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.MaskGenerationPipeline[[transformers.MaskGenerationPipeline]]", "char_start": 25832, "char_end": 26825, "token_estimate": 248, "prev_chunk_id": 947, "next_chunk_id": 949, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 949, "text": "binary_output (`bool`, *optional*, defaults to `False`) : Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text.\n\npoints_per_batch (*optional*, int, default to 64) : Sets the number of points run simultaneously by the model. Higher numbers may be faster but use more GPU memory.\n\noutput_bboxes_mask (`bool`, *optional*, default to `False`) : Whether or not to output the bounding box predictions.\n\noutput_rle_masks (`bool`, *optional*, default to `False`) : Whether or not to output the masks in `RLE` format\n\n**Returns:**\n\n``Dict``\n\nA dictionary with the following keys:\n- **mask** (`PIL.Image`) -- A binary mask of the detected object as a PIL Image of shape `(width,\n height)` of the original image. Returns a mask filled with zeros if no object is found.\n- **score** (*optional* `float`) -- Optionally, when the model is capable of estimating a confidence of\n the \"object\" described by the label and the mask.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.MaskGenerationPipeline[[transformers.MaskGenerationPipeline]]", "char_start": 181126, "char_end": 182118, "token_estimate": 248, "prev_chunk_id": 948, "next_chunk_id": 950, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 950, "text": "## Parent class: `Pipeline`[[transformers.Pipeline]]", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "Parent class: `Pipeline`[[transformers.Pipeline]]", "char_start": 182120, "char_end": 182172, "token_estimate": 13, "prev_chunk_id": 949, "next_chunk_id": 951, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 951, "text": "#### transformers.Pipeline[[transformers.Pipeline]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/base.py#L737)\n\nThe Pipeline class is the class from which all pipelines inherit. Refer to this class for methods shared across\ndifferent pipelines.\n\nBase class implementing pipelined operations. Pipeline workflow is defined as a sequence of the following\noperations:\n\nInput -> Tokenization -> Model Inference -> Post-Processing (task dependent) -> Output\n\nPipeline supports running on CPU or GPU through the device argument (see below).\n\nSome pipeline, like for instance [FeatureExtractionPipeline](/docs/transformers/v5.6.2/en/main_classes/pipelines#transformers.FeatureExtractionPipeline) (`'feature-extraction'`) output large tensor object\nas nested-lists. In order to avoid dumping such large structure as textual data we provide the `binary_output`\nconstructor argument. If set to `True`, the output will be stored in the pickle format.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.Pipeline[[transformers.Pipeline]]", "char_start": 182174, "char_end": 183160, "token_estimate": 246, "prev_chunk_id": 950, "next_chunk_id": 952, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 952, "text": "check_model_typetransformers.Pipeline.check_model_typehttps://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/base.py#L1079[{\"name\": \"supported_models\", \"val\": \": list[str] | dict\"}]- **supported_models** (`list[str]` or `dict`) --\n The list of models supported by the pipeline, or a dictionary with model class values.0\n\nCheck if the model class is in supported by the pipeline.\n\n**Parameters:**\n\nmodel ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)) : The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.Pipeline[[transformers.Pipeline]]", "char_start": 183162, "char_end": 183896, "token_estimate": 183, "prev_chunk_id": 951, "next_chunk_id": 953, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 953, "text": "tokenizer ([PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend)) : The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from [PreTrainedTokenizer](/docs/transformers/v5.6.2/en/main_classes/tokenizer#transformers.PythonBackend).\n\nfeature_extractor ([SequenceFeatureExtractor](/docs/transformers/v5.6.2/en/main_classes/feature_extractor#transformers.SequenceFeatureExtractor)) : The feature extractor that will be used by the pipeline to encode data for the model. This object inherits from [SequenceFeatureExtractor](/docs/transformers/v5.6.2/en/main_classes/feature_extractor#transformers.SequenceFeatureExtractor).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.Pipeline[[transformers.Pipeline]]", "char_start": 42577, "char_end": 43287, "token_estimate": 177, "prev_chunk_id": 952, "next_chunk_id": 954, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 954, "text": "image_processor ([BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor)) : The image processor that will be used by the pipeline to encode data for the model. This object inherits from [BaseImageProcessor](/docs/transformers/v5.6.2/en/main_classes/image_processor#transformers.BaseImageProcessor).\n\nprocessor ([ProcessorMixin](/docs/transformers/v5.6.2/en/main_classes/processors#transformers.ProcessorMixin)) : The processor that will be used by the pipeline to encode data for the model. This object inherits from [ProcessorMixin](/docs/transformers/v5.6.2/en/main_classes/processors#transformers.ProcessorMixin). Processor is a composite object that might contain `tokenizer`, `feature_extractor`, and `image_processor`.\n\ntask (`str`, defaults to `\"\"`) : A task-identifier for the pipeline.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.Pipeline[[transformers.Pipeline]]", "char_start": 184610, "char_end": 185460, "token_estimate": 212, "prev_chunk_id": 953, "next_chunk_id": 955, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 955, "text": "num_workers (`int`, *optional*, defaults to 8) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of workers to be used.\n\nbatch_size (`int`, *optional*, defaults to 1) : When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of the batch to use, for inference this is not always beneficial, please read [Batching with pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .\n\nargs_parser ([ArgumentHandler](/docs/transformers/v5.6.2/en/internal/pipelines_utils#transformers.pipelines.ArgumentHandler), *optional*) : Reference to the object in charge of parsing supplied pipeline parameters.\n\ndevice (`int`, *optional*, defaults to -1) : Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.Pipeline[[transformers.Pipeline]]", "char_start": 25654, "char_end": 26622, "token_estimate": 242, "prev_chunk_id": 954, "next_chunk_id": 956, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 956, "text": "dtype (`str` or `torch.dtype`, *optional*) : Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model (`torch.float16`, `torch.bfloat16`, ... or `\"auto\"`)\n\nbinary_output (`bool`, *optional*, defaults to `False`) : Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as the raw output data e.g. text.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transformers.Pipeline[[transformers.Pipeline]]", "char_start": 26624, "char_end": 27016, "token_estimate": 98, "prev_chunk_id": 955, "next_chunk_id": 957, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 957, "text": "#### device_placement[[transformers.Pipeline.device_placement]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/base.py#L1015)\n\nContext Manager allowing tensor allocation on the user-specified device.\n\nExamples:\n\n```python", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "device_placement[[transformers.Pipeline.device_placement]]", "char_start": 186825, "char_end": 187092, "token_estimate": 66, "prev_chunk_id": 956, "next_chunk_id": 958, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 958, "text": "# Explicitly ask for tensor allocation on CUDA device :0\npipe = pipeline(..., device=0)\nwith pipe.device_placement():\n # Every tensor allocation will be done on the request device\n output = pipe(...)\n```\n\n**Returns:**\n\nContext manager", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "Explicitly ask for tensor allocation on CUDA device :0", "char_start": 187093, "char_end": 187333, "token_estimate": 60, "prev_chunk_id": 957, "next_chunk_id": 959, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 959, "text": "#### ensure_tensor_on_device[[transformers.Pipeline.ensure_tensor_on_device]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/base.py#L1047)\n\nEnsure PyTorch tensors are on the specified device.\n\n**Parameters:**\n\ninputs (keyword arguments that should be `torch.Tensor`, the rest is ignored) : The tensors to place on `self.device`.\n\nRecursive on lists **only**. --\n\n**Returns:**\n\n``dict[str, torch.Tensor]``\n\nThe same as `inputs` but on the proper device.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "ensure_tensor_on_device[[transformers.Pipeline.ensure_tensor_on_device]]", "char_start": 187334, "char_end": 187833, "token_estimate": 124, "prev_chunk_id": 958, "next_chunk_id": 960, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 960, "text": "#### postprocess[[transformers.Pipeline.postprocess]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/base.py#L1146)\n\nPostprocess will receive the raw outputs of the `_forward` method, generally tensors, and reformat them into\nsomething more friendly. Generally it will output a list or a dict or results (containing just strings and\nnumbers).", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "postprocess[[transformers.Pipeline.postprocess]]", "char_start": 187834, "char_end": 188222, "token_estimate": 97, "prev_chunk_id": 959, "next_chunk_id": 961, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 961, "text": "#### predict[[transformers.Pipeline.predict]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/base.py#L994)\n\nScikit / Keras interface to transformers' pipelines. This method will forward to __call__().", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "predict[[transformers.Pipeline.predict]]", "char_start": 188223, "char_end": 188469, "token_estimate": 61, "prev_chunk_id": 960, "next_chunk_id": 962, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 962, "text": "#### preprocess[[transformers.Pipeline.preprocess]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/base.py#L1125)\n\nPreprocess will take the `input_` of a specific pipeline and return a dictionary of everything necessary for\n`_forward` to run properly. It should contain at least one tensor, but might have arbitrary other items.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "preprocess[[transformers.Pipeline.preprocess]]", "char_start": 188470, "char_end": 188844, "token_estimate": 93, "prev_chunk_id": 961, "next_chunk_id": 963, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 963, "text": "#### push_to_hub[[transformers.Pipeline.push_to_hub]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/utils/hub.py#L720)\n\nUpload the pipeline file to the \ud83e\udd17 Model Hub.\n\nExamples:\n\n```python\nfrom transformers import pipeline\n\npipe = pipeline(\"google-bert/bert-base-cased\")", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "push_to_hub[[transformers.Pipeline.push_to_hub]]", "char_start": 188845, "char_end": 189150, "token_estimate": 76, "prev_chunk_id": 962, "next_chunk_id": 964, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 964, "text": "# Push the pipe to your namespace with the name \"my-finetuned-bert\".\npipe.push_to_hub(\"my-finetuned-bert\")", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "Push the pipe to your namespace with the name \"my-finetuned-bert\".", "char_start": 189152, "char_end": 189258, "token_estimate": 26, "prev_chunk_id": 963, "next_chunk_id": 965, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 965, "text": "# Push the pipe to an organization with the name \"my-finetuned-bert\".\npipe.push_to_hub(\"huggingface/my-finetuned-bert\")\n```\n\n**Parameters:**\n\nrepo_id (`str`) : The name of the repository you want to push your pipe to. It should contain your organization name when pushing to a given organization.\n\ncommit_message (`str`, *optional*) : Message to commit while pushing. Will default to `\"Upload pipe\"`.\n\ncommit_description (`str`, *optional*) : The description of the commit that will be created\n\nprivate (`bool`, *optional*) : Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.\n\ntoken (`bool` or `str`, *optional*) : The token to use as HTTP bearer authorization for remote files. If `True` (default), will use the token generated when running `hf auth login` (stored in `~/.huggingface`).\n\nrevision (`str`, *optional*) : Branch to push the uploaded files to.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "Push the pipe to an organization with the name \"my-finetuned-bert\".", "char_start": 189260, "char_end": 190242, "token_estimate": 245, "prev_chunk_id": 964, "next_chunk_id": 966, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 966, "text": "create_pr (`bool`, *optional*, defaults to `False`) : Whether or not to create a PR with the uploaded files or directly commit.\n\nmax_shard_size (`int` or `str`, *optional*, defaults to `\"50GB\"`) : Only applicable for models. The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size lower than this size. If expressed as a string, needs to be digits followed by a unit (like `\"5MB\"`).\n\ntags (`list[str]`, *optional*) : List of tags to push on the Hub.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "Push the pipe to an organization with the name \"my-finetuned-bert\".", "char_start": 190244, "char_end": 190737, "token_estimate": 123, "prev_chunk_id": 965, "next_chunk_id": 967, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 967, "text": "#### save_pretrained[[transformers.Pipeline.save_pretrained]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/base.py#L942)\n\nSave the pipeline's model and tokenizer.\n\n**Parameters:**\n\nsave_directory (`str` or `os.PathLike`) : A path to the directory where to saved. It will be created if it doesn't exist.\n\nkwargs (`dict[str, Any]`, *optional*) : Additional key word arguments passed along to the [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.utils.PushToHubMixin.push_to_hub) method.", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "save_pretrained[[transformers.Pipeline.save_pretrained]]", "char_start": 190738, "char_end": 191298, "token_estimate": 140, "prev_chunk_id": 966, "next_chunk_id": 968, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 968, "text": "#### transform[[transformers.Pipeline.transform]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/pipelines/base.py#L988)\n\nScikit / Keras interface to transformers' pipelines. This method will forward to __call__().", "source_file": "transformers/main_classes/pipelines.md", "section_heading": "transform[[transformers.Pipeline.transform]]", "char_start": 191299, "char_end": 191549, "token_estimate": 62, "prev_chunk_id": 967, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/main_classes/pipelines", "doc_title": "Pipelines" }, { "chunk_id": 969, "text": "# Trainer\n\nThe [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) class provides an API for feature-complete training in PyTorch, and it supports distributed training on multiple GPUs/TPUs, mixed precision for [NVIDIA GPUs](https://nvidia.github.io/apex/), [AMD GPUs](https://rocm.docs.amd.com/en/latest/rocm.html), and [`torch.amp`](https://pytorch.org/docs/stable/amp.html) for PyTorch. [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) goes hand-in-hand with the [TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments) class, which offers a wide range of options to customize how a model is trained. Together, these two classes provide a complete training API.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "Trainer", "char_start": 0, "char_end": 772, "token_estimate": 193, "prev_chunk_id": null, "next_chunk_id": 970, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 970, "text": "[Seq2SeqTrainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Seq2SeqTrainer) and [Seq2SeqTrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Seq2SeqTrainingArguments) inherit from the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) and [TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments) classes and they're adapted for training models for sequence-to-sequence tasks such as summarization or translation.\n\nThe [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) class is optimized for \ud83e\udd17 Transformers models and can have surprising behaviors\nwhen used with other models. When using it with your own model, make sure:", "source_file": "transformers/main_classes/trainer.md", "section_heading": "Trainer", "char_start": 774, "char_end": 1552, "token_estimate": 194, "prev_chunk_id": 969, "next_chunk_id": 971, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 971, "text": "- your model always return tuples or subclasses of [ModelOutput](/docs/transformers/v5.6.2/en/main_classes/output#transformers.utils.ModelOutput)\n- your model can compute the loss if a `labels` argument is provided and that loss is returned as the first\n element of the tuple (if your model returns tuples)\n- your model can accept multiple label arguments (use `label_names` in [TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments) to indicate their name to the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer)) but none of them should be named `\"label\"`", "source_file": "transformers/main_classes/trainer.md", "section_heading": "Trainer", "char_start": 1554, "char_end": 2190, "token_estimate": 159, "prev_chunk_id": 970, "next_chunk_id": 972, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 972, "text": "## Trainer[[api-reference]][[transformers.Trainer]]", "source_file": "transformers/main_classes/trainer.md", "section_heading": "Trainer[[api-reference]][[transformers.Trainer]]", "char_start": 2192, "char_end": 2243, "token_estimate": 12, "prev_chunk_id": 971, "next_chunk_id": 973, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 973, "text": "#### transformers.Trainer[[transformers.Trainer]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L255)\n\nTrainer is a simple but feature-complete training and eval loop for PyTorch, optimized for \ud83e\udd17 Transformers.\n\nImportant attributes:", "source_file": "transformers/main_classes/trainer.md", "section_heading": "transformers.Trainer[[transformers.Trainer]]", "char_start": 2245, "char_end": 2525, "token_estimate": 70, "prev_chunk_id": 972, "next_chunk_id": 974, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 974, "text": "- **model** -- Always points to the core model. If using a transformers model, it will be a [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel)\n subclass.\n- **model_wrapped** -- Always points to the most external model in case one or more other modules wrap the\n original model. This is the model that should be used for the forward pass. For example, under `DeepSpeed`,\n the inner model is wrapped in `DeepSpeed` and then again in `torch.nn.DistributedDataParallel`. If the inner\n model hasn't been wrapped, then `self.model_wrapped` is the same as `self.model`.\n- **is_model_parallel** -- Whether or not a model has been switched to a model parallel mode (different from\n data parallelism, this means some of the model layers are split on different GPUs).\n- **place_model_on_device** -- Whether or not to automatically place the model on the device. Defaults to\n `True` unless model parallel, DeepSpeed, FSDP, full fp16/bf16 eval, or SageMaker MP is active. Can be\n overridden by subclassing `TrainingArguments` and overriding the `place_model_on_device` property.\n- **is_in_train** -- Whether or not a model is currently running `train` (e.g. when `evaluate` is called while\n in `train`)", "source_file": "transformers/main_classes/trainer.md", "section_heading": "transformers.Trainer[[transformers.Trainer]]", "char_start": 2527, "char_end": 3769, "token_estimate": 310, "prev_chunk_id": 973, "next_chunk_id": 975, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 975, "text": "add_callbacktransformers.Trainer.add_callbackhttps://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L4350[{\"name\": \"callback\", \"val\": \": type[transformers.trainer_callback.TrainerCallback] | transformers.trainer_callback.TrainerCallback\"}]- **callback** (`type` or [`~transformers.TrainerCallback]`) --\n A [TrainerCallback](/docs/transformers/v5.6.2/en/main_classes/callback#transformers.TrainerCallback) class or an instance of a [TrainerCallback](/docs/transformers/v5.6.2/en/main_classes/callback#transformers.TrainerCallback). In the\n first case, will instantiate a member of that class.0\n\nAdd a callback to the current list of [TrainerCallback](/docs/transformers/v5.6.2/en/main_classes/callback#transformers.TrainerCallback).\n\n**Parameters:**", "source_file": "transformers/main_classes/trainer.md", "section_heading": "transformers.Trainer[[transformers.Trainer]]", "char_start": 3771, "char_end": 4550, "token_estimate": 194, "prev_chunk_id": 974, "next_chunk_id": 976, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 976, "text": "model ([PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel) or `torch.nn.Module`, *optional*) : The model to train, evaluate or use for predictions. If not provided, a `model_init` must be passed. [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) is optimized to work with the [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel) provided by the library. You can still use your own models defined as `torch.nn.Module` as long as they work the same way as the \ud83e\udd17 Transformers models. \n\nargs ([TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments), *optional*) : The arguments to tweak for training. Will default to a basic instance of [TrainingArguments](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.TrainingArguments) with the `output_dir` set to a directory named *tmp_trainer* in the current directory if not provided.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "transformers.Trainer[[transformers.Trainer]]", "char_start": 4552, "char_end": 5559, "token_estimate": 251, "prev_chunk_id": 975, "next_chunk_id": 977, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 977, "text": "data_collator (`DataCollator`, *optional*) : The function to use to form a batch from a list of elements of `train_dataset` or `eval_dataset`. Will default to [default_data_collator()](/docs/transformers/v5.6.2/en/main_classes/data_collator#transformers.default_data_collator) if no `processing_class` is provided, an instance of [DataCollatorWithPadding](/docs/transformers/v5.6.2/en/main_classes/data_collator#transformers.DataCollatorWithPadding) otherwise if the processing_class is a feature extractor or tokenizer.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "transformers.Trainer[[transformers.Trainer]]", "char_start": 5561, "char_end": 6081, "token_estimate": 130, "prev_chunk_id": 976, "next_chunk_id": 978, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 978, "text": "train_dataset (`torch.utils.data.Dataset` | `torch.utils.data.IterableDataset` | `datasets.Dataset`, *optional*) : The dataset to use for training. If it is a [Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset), columns not accepted by the `model.forward()` method are automatically removed. Note that if it's a `torch.utils.data.IterableDataset` with some randomization and you are training in a distributed fashion, your iterable dataset should either use a internal attribute `generator` that is a `torch.Generator` for the randomization that must be identical on all processes (and the Trainer will manually set the seed of this `generator` at each epoch) or have a `set_epoch()` method that internally sets the seed of the RNGs used.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "transformers.Trainer[[transformers.Trainer]]", "char_start": 6083, "char_end": 6876, "token_estimate": 198, "prev_chunk_id": 977, "next_chunk_id": 979, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 979, "text": "eval_dataset (`torch.utils.data.Dataset` | dict[str, `torch.utils.data.Dataset`] | `datasets.Dataset`, *optional*) : The dataset to use for evaluation. If it is a [Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset), columns not accepted by the `model.forward()` method are automatically removed. If it is a dictionary, it will evaluate on each dataset prepending the dictionary key to the metric name.\n\nprocessing_class (`PreTrainedTokenizerBase` or `BaseImageProcessor` or `FeatureExtractionMixin` or `ProcessorMixin`, *optional*) : Processing class used to process the data. If provided, will be used to automatically process the inputs for the model, and it will be saved along the model to make it easier to rerun an interrupted training or reuse the fine-tuned model.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "transformers.Trainer[[transformers.Trainer]]", "char_start": 6878, "char_end": 7704, "token_estimate": 206, "prev_chunk_id": 978, "next_chunk_id": 980, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 980, "text": "model_init (`Callable[[], PreTrainedModel]`, *optional*) : A function that instantiates the model to be used. If provided, each call to [train()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.train) will start from a new instance of the model as given by this function. The function may have zero argument, or a single one containing the optuna/Ray Tune trial object, to be able to choose different architectures according to hyperparameters (such as layer count, sizes of inner layers, dropout probabilities etc).\n\ncompute_loss_func (`Callable`, *optional*) : A function that accepts the raw model outputs, labels, and the number of items in the entire accumulated batch (batch_size * gradient_accumulation_steps) and returns the loss. For example, see the default [loss function](https://github.com/huggingface/transformers/blob/052e652d6d53c2b26ffde87e039b723949a53493/src/transformers/trainer.py#L3618) used by [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer).", "source_file": "transformers/main_classes/trainer.md", "section_heading": "transformers.Trainer[[transformers.Trainer]]", "char_start": 7706, "char_end": 8729, "token_estimate": 255, "prev_chunk_id": 979, "next_chunk_id": 981, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 981, "text": "compute_metrics (`Callable[[EvalPrediction], Dict]`, *optional*) : The function that will be used to compute metrics at evaluation. Must take a [EvalPrediction](/docs/transformers/v5.6.2/en/internal/trainer_utils#transformers.EvalPrediction) and return a dictionary string to metric values. *Note* When passing TrainingArgs with `batch_eval_metrics` set to `True`, your compute_metrics function must take a boolean `compute_result` argument. This will be triggered after the last eval batch to signal that the function needs to calculate and return the global summary statistics rather than accumulating the batch-level statistics", "source_file": "transformers/main_classes/trainer.md", "section_heading": "transformers.Trainer[[transformers.Trainer]]", "char_start": 8731, "char_end": 9361, "token_estimate": 157, "prev_chunk_id": 980, "next_chunk_id": 982, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 982, "text": "callbacks (List of [TrainerCallback](/docs/transformers/v5.6.2/en/main_classes/callback#transformers.TrainerCallback), *optional*) : A list of callbacks to customize the training loop. Will add those to the list of default callbacks detailed in [here](callback). If you want to remove one of the default callbacks used, use the [Trainer.remove_callback()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.remove_callback) method.\n\noptimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`, *optional*, defaults to `(None, None)`) : A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your model and a scheduler given by [get_linear_schedule_with_warmup()](/docs/transformers/v5.6.2/en/main_classes/optimizer_schedules#transformers.get_linear_schedule_with_warmup) controlled by `args`.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "transformers.Trainer[[transformers.Trainer]]", "char_start": 9363, "char_end": 10240, "token_estimate": 219, "prev_chunk_id": 981, "next_chunk_id": 983, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 983, "text": "optimizer_cls_and_kwargs (`tuple[Type[torch.optim.Optimizer], dict[str, Any]]`, *optional*) : A tuple containing the optimizer class and keyword arguments to use. Overrides `optim` and `optim_args` in `args`. Incompatible with the `optimizers` argument. Unlike `optimizers`, this argument avoids the need to place model parameters on the correct devices before initializing the Trainer.\n\npreprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`, *optional*) : A function that preprocess the logits right before caching them at each evaluation step. Must take two tensors, the logits and the labels, and return the logits once processed as desired. The modifications made by this function will be reflected in the predictions received by `compute_metrics`. Note that the labels (second parameter) will be `None` if the dataset does not have them.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "transformers.Trainer[[transformers.Trainer]]", "char_start": 10242, "char_end": 11118, "token_estimate": 219, "prev_chunk_id": 982, "next_chunk_id": 984, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 984, "text": "#### autocast_smart_context_manager[[transformers.Trainer.autocast_smart_context_manager]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L2037)\n\nA helper wrapper that creates an appropriate context manager for `autocast` while feeding it the desired\narguments, depending on the situation. We rely on accelerate for autocast, hence we do nothing here.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "autocast_smart_context_manager[[transformers.Trainer.autocast_smart_context_manager]]", "char_start": 11119, "char_end": 11517, "token_estimate": 99, "prev_chunk_id": 983, "next_chunk_id": 985, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 985, "text": "#### call_model_init[[transformers.Trainer.call_model_init]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L4241)\n\nInvoke `model_init` to get a fresh model instance, optionally conditioned on a hyperparameter trial.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "call_model_init[[transformers.Trainer.call_model_init]]", "char_start": 11518, "char_end": 11781, "token_estimate": 65, "prev_chunk_id": 984, "next_chunk_id": 986, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 986, "text": "#### compute_loss[[transformers.Trainer.compute_loss]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L1941)\n\nHow the loss is computed by Trainer. By default, all models return the loss in the first element.\n\nSubclass and override for custom behavior. If you are not using `num_items_in_batch` when computing your loss,\nmake sure to overwrite `self.model_accepts_loss_kwargs` to `False`. Otherwise, the loss calculation might be slightly inaccurate when performing gradient accumulation.\n\n**Parameters:**\n\nmodel (`nn.Module`) : The model to compute the loss for.\n\ninputs (`dict[str, torch.Tensor | Any]`) : The input data for the model.\n\nreturn_outputs (`bool`, *optional*, defaults to `False`) : Whether to return the model outputs along with the loss.\n\nnum_items_in_batch (Optional[torch.Tensor], *optional*) : The number of items in the batch. If not passed, the loss is computed using the default batch size reduction logic.\n\n**Returns:**", "source_file": "transformers/main_classes/trainer.md", "section_heading": "compute_loss[[transformers.Trainer.compute_loss]]", "char_start": 11782, "char_end": 12771, "token_estimate": 247, "prev_chunk_id": 985, "next_chunk_id": 987, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 987, "text": "The loss of the model along with its output if return_outputs was set to True", "source_file": "transformers/main_classes/trainer.md", "section_heading": "compute_loss[[transformers.Trainer.compute_loss]]", "char_start": 12773, "char_end": 12850, "token_estimate": 19, "prev_chunk_id": 986, "next_chunk_id": 988, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 988, "text": "#### compute_loss_context_manager[[transformers.Trainer.compute_loss_context_manager]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L2025)\n\nA helper wrapper to group together context managers.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "compute_loss_context_manager[[transformers.Trainer.compute_loss_context_manager]]", "char_start": 12851, "char_end": 13092, "token_estimate": 60, "prev_chunk_id": 987, "next_chunk_id": 989, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 989, "text": "#### create_accelerator_and_postprocess[[transformers.Trainer.create_accelerator_and_postprocess]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L752)\n\nCreate the accelerator and perform post-creation setup (FSDP, DeepSpeed, etc.).", "source_file": "transformers/main_classes/trainer.md", "section_heading": "create_accelerator_and_postprocess[[transformers.Trainer.create_accelerator_and_postprocess]]", "char_start": 13093, "char_end": 13372, "token_estimate": 69, "prev_chunk_id": 988, "next_chunk_id": 990, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 990, "text": "#### create_model_card[[transformers.Trainer.create_model_card]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L3925)\n\nCreates a draft of a model card using the information available to the `Trainer`.\n\n**Parameters:**\n\nlanguage (`str`, *optional*) : The language of the model (if applicable)\n\nlicense (`str`, *optional*) : The license of the model. Will default to the license of the pretrained model used, if the original model given to the `Trainer` comes from a repo on the Hub.\n\ntags (`str` or `list[str]`, *optional*) : Some tags to be included in the metadata of the model card.\n\nmodel_name (`str`, *optional*) : The name of the model.\n\nfinetuned_from (`str`, *optional*) : The name of the model used to fine-tune this one (if applicable). Will default to the name of the repo of the original model given to the `Trainer` (if it comes from the Hub).", "source_file": "transformers/main_classes/trainer.md", "section_heading": "create_model_card[[transformers.Trainer.create_model_card]]", "char_start": 13373, "char_end": 14276, "token_estimate": 225, "prev_chunk_id": 989, "next_chunk_id": 991, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 991, "text": "tasks (`str` or `list[str]`, *optional*) : One or several task identifiers, to be included in the metadata of the model card.\n\ndataset_tags (`str` or `list[str]`, *optional*) : One or several dataset tags, to be included in the metadata of the model card.\n\ndataset (`str` or `list[str]`, *optional*) : One or several dataset identifiers, to be included in the metadata of the model card.\n\ndataset_args (`str` or `list[str]`, *optional*) : One or several dataset arguments, to be included in the metadata of the model card.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "create_model_card[[transformers.Trainer.create_model_card]]", "char_start": 14278, "char_end": 14800, "token_estimate": 130, "prev_chunk_id": 990, "next_chunk_id": 992, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 992, "text": "#### create_optimizer[[transformers.Trainer.create_optimizer]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L1146)\n\nSetup the optimizer.\n\nWe provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the\nTrainer's init through `optimizers`, or subclass and override this method in a subclass.\n\n**Returns:**\n\n``torch.optim.Optimizer``\n\nThe optimizer instance.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "create_optimizer[[transformers.Trainer.create_optimizer]]", "char_start": 14801, "char_end": 15254, "token_estimate": 113, "prev_chunk_id": 991, "next_chunk_id": 993, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 993, "text": "#### create_optimizer_and_scheduler[[transformers.Trainer.create_optimizer_and_scheduler]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L1135)\n\nSetup the optimizer and the learning rate scheduler.\n\nWe provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the\nTrainer's init through `optimizers`, or subclass and override this method (or `create_optimizer` and/or\n`create_scheduler`) in a subclass.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "create_optimizer_and_scheduler[[transformers.Trainer.create_optimizer_and_scheduler]]", "char_start": 15255, "char_end": 15752, "token_estimate": 124, "prev_chunk_id": 992, "next_chunk_id": 994, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 994, "text": "#### create_scheduler[[transformers.Trainer.create_scheduler]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L1222)\n\nSetup the scheduler. The optimizer of the trainer must have been set up either before this method is called or\npassed as an argument.\n\n**Parameters:**\n\nnum_training_steps (int) : The number of training steps to do.\n\n**Returns:**\n\n``torch.optim.lr_scheduler.LRScheduler``\n\nThe learning rate scheduler instance.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "create_scheduler[[transformers.Trainer.create_scheduler]]", "char_start": 15753, "char_end": 16227, "token_estimate": 118, "prev_chunk_id": 993, "next_chunk_id": 995, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 995, "text": "#### evaluate[[transformers.Trainer.evaluate]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L2515)\n\nRun evaluation and returns metrics.\n\nThe calling script will be responsible for providing a method to compute metrics, as they are task-dependent\n(pass it to the init `compute_metrics` argument).\n\nYou can also subclass and override this method to inject custom behavior.\n\n**Parameters:**", "source_file": "transformers/main_classes/trainer.md", "section_heading": "evaluate[[transformers.Trainer.evaluate]]", "char_start": 16228, "char_end": 16664, "token_estimate": 109, "prev_chunk_id": 994, "next_chunk_id": 996, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 996, "text": "eval_dataset (`Dataset` | dict[str, `Dataset`], *optional*) : Pass a dataset if you wish to override `self.eval_dataset`. If it is a [Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset), columns not accepted by the `model.forward()` method are automatically removed. If it is a dictionary, it will evaluate on each dataset, prepending the dictionary key to the metric name. Datasets must implement the `__len__` method. If you pass a dictionary with names of datasets as keys and datasets as values, evaluate will run separate evaluations on each dataset. This can be useful to monitor how training affects other datasets or simply to get a more fine-grained evaluation. When used with `load_best_model_at_end`, make sure `metric_for_best_model` references exactly one of the datasets. If you, for example, pass in `{\"data1\": data1, \"data2\": data2}` for two datasets `data1` and `data2`, you could specify `metric_for_best_model=\"eval_data1_loss\"` for using the loss on `data1` and `metric_for_best_model=\"eval_data2_loss\"` for the loss on `data2`.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "evaluate[[transformers.Trainer.evaluate]]", "char_start": 16666, "char_end": 17770, "token_estimate": 276, "prev_chunk_id": 995, "next_chunk_id": 997, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 997, "text": "ignore_keys (`list[str]`, *optional*) : A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions.\n\nmetric_key_prefix (`str`, *optional*, defaults to `\"eval\"`) : An optional prefix to be used as the metrics key prefix. For example the metrics \"bleu\" will be named \"eval_bleu\" if the prefix is \"eval\" (default)\n\n**Returns:**\n\nA dictionary containing the evaluation loss and the potential metrics computed from the predictions. The\ndictionary also contains the epoch number which comes from the training state.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "evaluate[[transformers.Trainer.evaluate]]", "char_start": 17775, "char_end": 18342, "token_estimate": 141, "prev_chunk_id": 996, "next_chunk_id": 998, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 998, "text": "#### evaluation_loop[[transformers.Trainer.evaluation_loop]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L2615)\n\nPrediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`.\n\nWorks both with or without labels.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "evaluation_loop[[transformers.Trainer.evaluation_loop]]", "char_start": 18343, "char_end": 18625, "token_estimate": 70, "prev_chunk_id": 997, "next_chunk_id": 999, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 999, "text": "#### floating_point_ops[[transformers.Trainer.floating_point_ops]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L3886)\n\nFor models that inherit from [PreTrainedModel](/docs/transformers/v5.6.2/en/main_classes/model#transformers.PreTrainedModel), uses that method to compute the number of floating point\noperations for every backward + forward pass. If using another model, either implement such a method in the\nmodel or subclass and override this method.\n\n**Parameters:**\n\ninputs (`dict[str, torch.Tensor | Any]`) : The inputs and targets of the model.\n\n**Returns:**\n\n``int``\n\nThe number of floating-point operations.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "floating_point_ops[[transformers.Trainer.floating_point_ops]]", "char_start": 18626, "char_end": 19292, "token_estimate": 166, "prev_chunk_id": 998, "next_chunk_id": 1000, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1000, "text": "#### get_batch_samples[[transformers.Trainer.get_batch_samples]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L2095)\n\nCollects a specified number of batches from the epoch iterator and optionally counts the number of items in the batches to properly scale the loss.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "get_batch_samples[[transformers.Trainer.get_batch_samples]]", "char_start": 19293, "char_end": 19607, "token_estimate": 78, "prev_chunk_id": 999, "next_chunk_id": 1001, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1001, "text": "#### get_cp_size[[transformers.Trainer.get_cp_size]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L2386)\n\nGet the context parallel size", "source_file": "transformers/main_classes/trainer.md", "section_heading": "get_cp_size[[transformers.Trainer.get_cp_size]]", "char_start": 19608, "char_end": 19792, "token_estimate": 46, "prev_chunk_id": 1000, "next_chunk_id": 1002, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1002, "text": "#### get_decay_parameter_names[[transformers.Trainer.get_decay_parameter_names]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L1283)\n\nGet all parameter names that weight decay will be applied to.\n\nThis function filters out parameters in two ways:\n1. By layer type (instances of layers specified in ALL_LAYERNORM_LAYERS)\n2. By parameter name patterns (containing 'bias', or variation of 'norm')", "source_file": "transformers/main_classes/trainer.md", "section_heading": "get_decay_parameter_names[[transformers.Trainer.get_decay_parameter_names]]", "char_start": 19793, "char_end": 20235, "token_estimate": 110, "prev_chunk_id": 1001, "next_chunk_id": 1003, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1003, "text": "#### get_eval_dataloader[[transformers.Trainer.get_eval_dataloader]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L885)\n\nReturns the evaluation `~torch.utils.data.DataLoader`.\n\nSubclass and override this method if you want to inject some custom behavior.\n\n**Parameters:**\n\neval_dataset (`str` or `torch.utils.data.Dataset`, *optional*) : If a `str`, will use `self.eval_dataset[eval_dataset]` as the evaluation dataset. If a `Dataset`, will override `self.eval_dataset` and must implement `__len__`. If it is a [Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset), columns not accepted by the `model.forward()` method are automatically removed.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "get_eval_dataloader[[transformers.Trainer.get_eval_dataloader]]", "char_start": 20236, "char_end": 20982, "token_estimate": 186, "prev_chunk_id": 1002, "next_chunk_id": 1004, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1004, "text": "#### get_learning_rates[[transformers.Trainer.get_learning_rates]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer_pt_utils.py#L982)\n\nReturns the learning rate of each parameter from self.optimizer.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "get_learning_rates[[transformers.Trainer.get_learning_rates]]", "char_start": 20983, "char_end": 21224, "token_estimate": 60, "prev_chunk_id": 1003, "next_chunk_id": 1005, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1005, "text": "#### get_num_trainable_parameters[[transformers.Trainer.get_num_trainable_parameters]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer_pt_utils.py#L974)\n\nGet the number of trainable parameters.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "get_num_trainable_parameters[[transformers.Trainer.get_num_trainable_parameters]]", "char_start": 21225, "char_end": 21461, "token_estimate": 59, "prev_chunk_id": 1004, "next_chunk_id": 1006, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1006, "text": "#### get_optimizer_cls_and_kwargs[[transformers.Trainer.get_optimizer_cls_and_kwargs]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L1252)\n\nReturns the optimizer class and optimizer parameters based on the training arguments.\n\n**Parameters:**\n\nargs (`transformers.training_args.TrainingArguments`) : The training arguments for the training session.\n\nmodel (`PreTrainedModel`, *optional*) : The model being trained. Required for some optimizers (GaLore, Apollo, LOMO).\n\n**Returns:**\n\nA tuple containing the optimizer class and a dictionary of optimizer keyword arguments.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "get_optimizer_cls_and_kwargs[[transformers.Trainer.get_optimizer_cls_and_kwargs]]", "char_start": 21462, "char_end": 22081, "token_estimate": 154, "prev_chunk_id": 1005, "next_chunk_id": 1007, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1007, "text": "#### get_optimizer_group[[transformers.Trainer.get_optimizer_group]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer_pt_utils.py#L992)\n\nReturns optimizer group for a parameter if given, else returns all optimizer groups for params.\n\n**Parameters:**\n\nparam (`str` or `torch.nn.parameter.Parameter`, *optional*) : The parameter for which optimizer group needs to be returned.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "get_optimizer_group[[transformers.Trainer.get_optimizer_group]]", "char_start": 22082, "char_end": 22498, "token_estimate": 104, "prev_chunk_id": 1006, "next_chunk_id": 1008, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1008, "text": "#### get_sp_size[[transformers.Trainer.get_sp_size]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L2378)\n\nGet the sequence parallel size", "source_file": "transformers/main_classes/trainer.md", "section_heading": "get_sp_size[[transformers.Trainer.get_sp_size]]", "char_start": 22499, "char_end": 22684, "token_estimate": 46, "prev_chunk_id": 1007, "next_chunk_id": 1009, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1009, "text": "#### get_test_dataloader[[transformers.Trainer.get_test_dataloader]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L924)\n\nReturns the test `~torch.utils.data.DataLoader`.\n\nSubclass and override this method if you want to inject some custom behavior.\n\n**Parameters:**\n\ntest_dataset (`torch.utils.data.Dataset`, *optional*) : The test dataset to use. If it is a [Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset), columns not accepted by the `model.forward()` method are automatically removed. It must implement `__len__`.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "get_test_dataloader[[transformers.Trainer.get_test_dataloader]]", "char_start": 22685, "char_end": 23308, "token_estimate": 155, "prev_chunk_id": 1008, "next_chunk_id": 1010, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1010, "text": "#### get_total_train_batch_size[[transformers.Trainer.get_total_train_batch_size]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L2360)\n\nCalculates total batch size (micro_batch * grad_accum * dp_world_size).\n\nAccounts for all parallelism dimensions: TP, CP, and SP.\n\nFormula: dp_world_size = world_size // (tp_size * cp_size * sp_size)\n\nWhere:\n- TP (Tensor Parallelism): Model layers split across GPUs\n- CP (Context Parallelism): Sequences split using Ring Attention (FSDP2)\n- SP (Sequence Parallelism): Sequences split using ALST/Ulysses (DeepSpeed)\n\nAll dimensions are separate and multiplicative: world_size = dp_size * tp_size * cp_size * sp_size", "source_file": "transformers/main_classes/trainer.md", "section_heading": "get_total_train_batch_size[[transformers.Trainer.get_total_train_batch_size]]", "char_start": 23309, "char_end": 24008, "token_estimate": 174, "prev_chunk_id": 1009, "next_chunk_id": 1011, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1011, "text": "#### get_tp_size[[transformers.Trainer.get_tp_size]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L2394)\n\nGet the tensor parallel size from either the model or DeepSpeed config.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "get_tp_size[[transformers.Trainer.get_tp_size]]", "char_start": 24009, "char_end": 24235, "token_estimate": 56, "prev_chunk_id": 1010, "next_chunk_id": 1012, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1012, "text": "#### get_train_dataloader[[transformers.Trainer.get_train_dataloader]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L865)\n\nReturns the training `~torch.utils.data.DataLoader`.\n\nWill use no sampler if `train_dataset` does not implement `__len__`, a random sampler (adapted to distributed\ntraining if necessary) otherwise.\n\nSubclass and override this method if you want to inject some custom behavior.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "get_train_dataloader[[transformers.Trainer.get_train_dataloader]]", "char_start": 24236, "char_end": 24684, "token_estimate": 112, "prev_chunk_id": 1011, "next_chunk_id": 1013, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1013, "text": "#### hyperparameter_search[[transformers.Trainer.hyperparameter_search]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L4160)\n\nLaunch a hyperparameter search using `optuna` or `Ray Tune`. The optimized quantity is determined\nby `compute_objective`, which defaults to a function returning the evaluation loss when no metric is provided,\nthe sum of all metrics otherwise.\n\nTo use this method, you need to have provided a `model_init` when initializing your [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer): we need to\nreinitialize the model at each new run. This is incompatible with the `optimizers` argument, so you need to\nsubclass [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) and override the method [create_optimizer_and_scheduler()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.create_optimizer_and_scheduler) for custom\noptimizer/scheduler.\n\n**Parameters:**", "source_file": "transformers/main_classes/trainer.md", "section_heading": "hyperparameter_search[[transformers.Trainer.hyperparameter_search]]", "char_start": 24685, "char_end": 25691, "token_estimate": 251, "prev_chunk_id": 1012, "next_chunk_id": 1014, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1014, "text": "hp_space (`Callable[[\"optuna.Trial\"], dict[str, float]]`, *optional*) : A function that defines the hyperparameter search space. Will default to `default_hp_space_optuna()` or `default_hp_space_ray()` depending on your backend.\n\ncompute_objective (`Callable[[dict[str, float]], float]`, *optional*) : A function computing the objective to minimize or maximize from the metrics returned by the `evaluate` method. Will default to `default_compute_objective()`.\n\nn_trials (`int`, *optional*, defaults to 100) : The number of trial runs to test.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "hyperparameter_search[[transformers.Trainer.hyperparameter_search]]", "char_start": 25693, "char_end": 26234, "token_estimate": 135, "prev_chunk_id": 1013, "next_chunk_id": 1015, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1015, "text": "direction (`str` or `list[str]`, *optional*, defaults to `\"minimize\"`) : If it's single objective optimization, direction is `str`, can be `\"minimize\"` or `\"maximize\"`, you should pick `\"minimize\"` when optimizing the validation loss, `\"maximize\"` when optimizing one or several metrics. If it's multi objectives optimization, direction is `list[str]`, can be List of `\"minimize\"` and `\"maximize\"`, you should pick `\"minimize\"` when optimizing the validation loss, `\"maximize\"` when optimizing one or several metrics.\n\nbackend (`str` or `~training_utils.HPSearchBackend`, *optional*) : The backend to use for hyperparameter search. Will default to optuna or Ray Tune, depending on which one is installed. If all are installed, will default to optuna.\n\nhp_name (`Callable[[\"optuna.Trial\"], str]]`, *optional*) : A function that defines the trial/run name. Will default to None.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "hyperparameter_search[[transformers.Trainer.hyperparameter_search]]", "char_start": 26236, "char_end": 27112, "token_estimate": 219, "prev_chunk_id": 1014, "next_chunk_id": 1016, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1016, "text": "kwargs (`dict[str, Any]`, *optional*) : Additional keyword arguments for each backend: - `optuna`: parameters from [optuna.study.create_study](https://optuna.readthedocs.io/en/stable/reference/generated/optuna.study.create_study.html) and also the parameters `timeout`, `n_jobs` and `gc_after_trial` from [optuna.study.Study.optimize](https://optuna.readthedocs.io/en/stable/reference/generated/optuna.study.Study.html#optuna.study.Study.optimize) - `ray`: parameters from [tune.run](https://docs.ray.io/en/latest/tune/api_docs/execution.html#tune-run). If `resources_per_trial` is not set in the `kwargs`, it defaults to 1 CPU core and 1 GPU (if available). If `progress_reporter` is not set in the `kwargs`, [ray.tune.CLIReporter](https://docs.ray.io/en/latest/tune/api/doc/ray.tune.CLIReporter.html) is used.\n\n**Returns:**\n\n`[`trainer_utils.BestRun` or `list[trainer_utils.BestRun]`]`", "source_file": "transformers/main_classes/trainer.md", "section_heading": "hyperparameter_search[[transformers.Trainer.hyperparameter_search]]", "char_start": 27114, "char_end": 28002, "token_estimate": 222, "prev_chunk_id": 1015, "next_chunk_id": 1017, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1017, "text": "All the information about the best run or best\nruns for multi-objective optimization. Experiment summary can be found in `run_summary` attribute for Ray\nbackend.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "hyperparameter_search[[transformers.Trainer.hyperparameter_search]]", "char_start": 28004, "char_end": 28165, "token_estimate": 40, "prev_chunk_id": 1016, "next_chunk_id": 1018, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1018, "text": "#### init_hf_repo[[transformers.Trainer.init_hf_repo]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L3907)\n\nInitializes a git repo in `self.args.hub_model_id`.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "init_hf_repo[[transformers.Trainer.init_hf_repo]]", "char_start": 28166, "char_end": 28374, "token_estimate": 52, "prev_chunk_id": 1017, "next_chunk_id": 1019, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1019, "text": "#### is_local_process_zero[[transformers.Trainer.is_local_process_zero]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L4390)\n\nWhether or not this process is the local (e.g., on one machine if training in a distributed fashion on several\nmachines) main process.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "is_local_process_zero[[transformers.Trainer.is_local_process_zero]]", "char_start": 28375, "char_end": 28684, "token_estimate": 77, "prev_chunk_id": 1018, "next_chunk_id": 1020, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1020, "text": "#### is_world_process_zero[[transformers.Trainer.is_world_process_zero]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L4397)\n\nWhether or not this process is the global main process (when training in a distributed fashion on several\nmachines, this is only going to be `True` for one process).", "source_file": "transformers/main_classes/trainer.md", "section_heading": "is_world_process_zero[[transformers.Trainer.is_world_process_zero]]", "char_start": 28685, "char_end": 29025, "token_estimate": 85, "prev_chunk_id": 1019, "next_chunk_id": 1021, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1021, "text": "#### log[[transformers.Trainer.log]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L3851)\n\nLog `logs` on the various objects watching training.\n\nSubclass and override this method to inject custom behavior.\n\n**Parameters:**\n\nlogs (`dict[str, float]`) : The values to log.\n\nstart_time (`Optional[float]`) : The start of training.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "log[[transformers.Trainer.log]]", "char_start": 29026, "char_end": 29401, "token_estimate": 93, "prev_chunk_id": 1020, "next_chunk_id": 1022, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1022, "text": "#### log_metrics[[transformers.Trainer.log_metrics]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer_pt_utils.py#L830)\n\nLog metrics in a specially formatted way.\n\nUnder distributed environment this is done only for a process with rank 0.\n\nNotes on memory reports:\n\nIn order to get memory usage report you need to install `psutil`. You can do that with `pip install psutil`.\n\nNow when this method is run, you will see a report that will include:\n\n```\ninit_mem_cpu_alloc_delta = 1301MB\ninit_mem_cpu_peaked_delta = 154MB\ninit_mem_gpu_alloc_delta = 230MB\ninit_mem_gpu_peaked_delta = 0MB\ntrain_mem_cpu_alloc_delta = 1345MB\ntrain_mem_cpu_peaked_delta = 0MB\ntrain_mem_gpu_alloc_delta = 693MB\ntrain_mem_gpu_peaked_delta = 7MB\n```\n\n**Understanding the reports:**", "source_file": "transformers/main_classes/trainer.md", "section_heading": "log_metrics[[transformers.Trainer.log_metrics]]", "char_start": 29402, "char_end": 30250, "token_estimate": 212, "prev_chunk_id": 1021, "next_chunk_id": 1023, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1023, "text": "- the first segment, e.g., `train__`, tells you which stage the metrics are for. Reports starting with `init_`\n will be added to the first stage that gets run. So that if only evaluation is run, the memory usage for the\n `__init__` will be reported along with the `eval_` metrics.\n- the third segment, is either `cpu` or `gpu`, tells you whether it's the general RAM or the gpu0 memory\n metric.\n- `*_alloc_delta` - is the difference in the used/allocated memory counter between the end and the start of the\n stage - it can be negative if a function released more memory than it allocated.\n- `*_peaked_delta` - is any extra memory that was consumed and then freed - relative to the current allocated\n memory counter - it is never negative. When you look at the metrics of any stage you add up `alloc_delta` +\n `peaked_delta` and you know how much memory was needed to complete that stage.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "log_metrics[[transformers.Trainer.log_metrics]]", "char_start": 30252, "char_end": 31145, "token_estimate": 223, "prev_chunk_id": 1022, "next_chunk_id": 1024, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1024, "text": "The reporting happens only for process of rank 0 and gpu 0 (if there is a gpu). Typically this is enough since the\nmain process does the bulk of work, but it could be not quite so if model parallel is used and then other GPUs may\nuse a different amount of gpu memory. This is also not the same under DataParallel where gpu0 may require much more\nmemory than the rest since it stores the gradient and optimizer states for all participating GPUs. Perhaps in the\nfuture these reports will evolve to measure those too.\n\nThe CPU RAM metric measures RSS (Resident Set Size) includes both the memory which is unique to the process and the\nmemory shared with other processes. It is important to note that it does not include swapped out memory, so the\nreports could be imprecise.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "log_metrics[[transformers.Trainer.log_metrics]]", "char_start": 31147, "char_end": 31918, "token_estimate": 192, "prev_chunk_id": 1023, "next_chunk_id": 1025, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1025, "text": "The CPU peak memory is measured using a sampling thread. Due to python's GIL it may miss some of the peak memory if\nthat thread didn't get a chance to run when the highest memory was used. Therefore this report can be less than\nreality. Using `tracemalloc` would have reported the exact peak memory, but it doesn't report memory allocations\noutside of python. So if some C++ CUDA extension allocated its own memory it won't be reported. And therefore it\nwas dropped in favor of the memory sampling approach, which reads the current process memory usage.\n\nThe GPU allocated and peak memory reporting is done with `torch.cuda.memory_allocated()` and\n`torch.cuda.max_memory_allocated()`. This metric reports only \"deltas\" for pytorch-specific allocations, as\n`torch.cuda` memory management system doesn't track any memory allocated outside of pytorch. For example, the very\nfirst cuda call typically loads CUDA kernels, which may take from 0.5 to 2GB of GPU memory.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "log_metrics[[transformers.Trainer.log_metrics]]", "char_start": 31920, "char_end": 32882, "token_estimate": 240, "prev_chunk_id": 1024, "next_chunk_id": 1026, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1026, "text": "Note that this tracker doesn't account for memory allocations outside of [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer)'s `__init__`, `train`,\n`evaluate` and `predict` calls.\n\nBecause `evaluation` calls may happen during `train`, we can't handle nested invocations because\n`torch.cuda.max_memory_allocated` is a single counter, so if it gets reset by a nested eval call, `train`'s tracker\nwill report incorrect info. If this [pytorch issue](https://github.com/pytorch/pytorch/issues/16266) gets resolved\nit will be possible to change this class to be re-entrant. Until then we will only track the outer level of\n`train`, `evaluate` and `predict` methods. Which means that if `eval` is called during `train`, it's the latter\nthat will account for its memory usage and that of the former.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "log_metrics[[transformers.Trainer.log_metrics]]", "char_start": 32884, "char_end": 33705, "token_estimate": 205, "prev_chunk_id": 1025, "next_chunk_id": 1027, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1027, "text": "This also means that if any other tool that is used along the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) calls\n`torch.cuda.reset_peak_memory_stats`, the gpu peak memory stats could be invalid. And the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer) will disrupt\nthe normal behavior of any such tools that rely on calling `torch.cuda.reset_peak_memory_stats` themselves.\n\nFor best performance you may want to consider turning the memory profiling off for production runs.\n\n**Parameters:**\n\nsplit (`str`) : Mode/split name: one of `train`, `eval`, `test`\n\nmetrics (`dict[str, float]`) : The metrics returned from train/evaluate/predictmetrics: metrics dict", "source_file": "transformers/main_classes/trainer.md", "section_heading": "log_metrics[[transformers.Trainer.log_metrics]]", "char_start": 33707, "char_end": 34434, "token_estimate": 181, "prev_chunk_id": 1026, "next_chunk_id": 1028, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1028, "text": "#### metrics_format[[transformers.Trainer.metrics_format]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer_pt_utils.py#L803)\n\nReformat Trainer metrics values to a human-readable format.\n\n**Parameters:**\n\nmetrics (`dict[str, float]`) : The metrics returned from train/evaluate/predict\n\n**Returns:**\n\n`metrics (`dict[str, float]`)`\n\nThe reformatted metrics", "source_file": "transformers/main_classes/trainer.md", "section_heading": "metrics_format[[transformers.Trainer.metrics_format]]", "char_start": 34435, "char_end": 34832, "token_estimate": 99, "prev_chunk_id": 1027, "next_chunk_id": 1029, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1029, "text": "#### num_examples[[transformers.Trainer.num_examples]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L942)\n\nHelper to get number of samples in a `~torch.utils.data.DataLoader` by accessing its dataset. When\ndataloader.dataset does not exist or has no length, estimates as best it can", "source_file": "transformers/main_classes/trainer.md", "section_heading": "num_examples[[transformers.Trainer.num_examples]]", "char_start": 34833, "char_end": 35164, "token_estimate": 82, "prev_chunk_id": 1028, "next_chunk_id": 1030, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1030, "text": "#### pop_callback[[transformers.Trainer.pop_callback]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L4361)\n\nRemove a callback from the current list of [TrainerCallback](/docs/transformers/v5.6.2/en/main_classes/callback#transformers.TrainerCallback) and returns it.\n\nIf the callback is not found, returns `None` (and no error is raised).\n\n**Parameters:**\n\ncallback (`type` or [`~transformers.TrainerCallback]`) : A [TrainerCallback](/docs/transformers/v5.6.2/en/main_classes/callback#transformers.TrainerCallback) class or an instance of a [TrainerCallback](/docs/transformers/v5.6.2/en/main_classes/callback#transformers.TrainerCallback). In the first case, will pop the first member of that class found in the list of callbacks.\n\n**Returns:**\n\n`[TrainerCallback](/docs/transformers/v5.6.2/en/main_classes/callback#transformers.TrainerCallback)`\n\nThe callback removed, if found.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "pop_callback[[transformers.Trainer.pop_callback]]", "char_start": 35165, "char_end": 36093, "token_estimate": 232, "prev_chunk_id": 1029, "next_chunk_id": 1031, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1031, "text": "#### predict[[transformers.Trainer.predict]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L2822)\n\nRun prediction and returns predictions and potential metrics.\n\nDepending on the dataset and your use case, your test dataset may contain labels. In that case, this method\nwill also return metrics, like in `evaluate()`.\n\nIf your predictions or labels have different sequence length (for instance because you're doing dynamic padding\nin a token classification task) the predictions will be padded (on the right) to allow for concatenation into\none array. The padding index is -100.\n\nReturns: *NamedTuple* A namedtuple with the following keys:\n\n- predictions (`np.ndarray`): The predictions on `test_dataset`.\n- label_ids (`np.ndarray`, *optional*): The labels (if the dataset contained some).\n- metrics (`dict[str, float]`, *optional*): The potential dictionary of metrics (if the dataset contained\n labels).\n\n**Parameters:**", "source_file": "transformers/main_classes/trainer.md", "section_heading": "predict[[transformers.Trainer.predict]]", "char_start": 36094, "char_end": 37065, "token_estimate": 242, "prev_chunk_id": 1030, "next_chunk_id": 1032, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1032, "text": "test_dataset (`Dataset`) : Dataset to run the predictions on. If it is an `datasets.Dataset`, columns not accepted by the `model.forward()` method are automatically removed. Has to implement the method `__len__`\n\nignore_keys (`list[str]`, *optional*) : A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions.\n\nmetric_key_prefix (`str`, *optional*, defaults to `\"test\"`) : An optional prefix to be used as the metrics key prefix. For example the metrics \"bleu\" will be named \"test_bleu\" if the prefix is \"test\" (default)", "source_file": "transformers/main_classes/trainer.md", "section_heading": "predict[[transformers.Trainer.predict]]", "char_start": 37067, "char_end": 37648, "token_estimate": 145, "prev_chunk_id": 1031, "next_chunk_id": 1033, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1033, "text": "#### prediction_step[[transformers.Trainer.prediction_step]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L2883)\n\nPerform an evaluation step on `model` using `inputs`.\n\nSubclass and override to inject custom behavior.\n\n**Parameters:**\n\nmodel (`nn.Module`) : The model to evaluate.\n\ninputs (`dict[str, torch.Tensor | Any]`) : The inputs and targets of the model. The dictionary will be unpacked before being fed to the model. Most models expect the targets under the argument `labels`. Check your model's documentation for all accepted arguments.\n\nprediction_loss_only (`bool`) : Whether or not to return the loss only.\n\nignore_keys (`list[str]`, *optional*) : A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions.\n\n**Returns:**\n\n`tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]`\n\nA tuple with the loss,\nlogits and labels (each being optional).", "source_file": "transformers/main_classes/trainer.md", "section_heading": "prediction_step[[transformers.Trainer.prediction_step]]", "char_start": 37649, "char_end": 38636, "token_estimate": 246, "prev_chunk_id": 1032, "next_chunk_id": 1034, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1034, "text": "#### push_to_hub[[transformers.Trainer.push_to_hub]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L3999)\n\nUpload `self.model` and `self.processing_class` to the \ud83e\udd17 model hub on the repo `self.args.hub_model_id`.\n\n**Parameters:**\n\ncommit_message (`str`, *optional*, defaults to `\"End of training\"`) : Message to commit while pushing.\n\nblocking (`bool`, *optional*, defaults to `True`) : Whether the function should return only when the `git push` has finished.\n\ntoken (`str`, *optional*, defaults to `None`) : Token with write permission to overwrite Trainer's original args.\n\nrevision (`str`, *optional*) : The git revision to commit from. Defaults to the head of the \"main\" branch.\n\nkwargs (`dict[str, Any]`, *optional*) : Additional keyword arguments passed along to [create_model_card()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.create_model_card).\n\n**Returns:**", "source_file": "transformers/main_classes/trainer.md", "section_heading": "push_to_hub[[transformers.Trainer.push_to_hub]]", "char_start": 38637, "char_end": 39580, "token_estimate": 235, "prev_chunk_id": 1033, "next_chunk_id": 1035, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1035, "text": "The URL of the repository where the model was pushed if `blocking=False`, or a `Future` object tracking the\nprogress of the commit if `blocking=True`.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "push_to_hub[[transformers.Trainer.push_to_hub]]", "char_start": 39582, "char_end": 39732, "token_estimate": 37, "prev_chunk_id": 1034, "next_chunk_id": 1036, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1036, "text": "#### remove_callback[[transformers.Trainer.remove_callback]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L4377)\n\nRemove a callback from the current list of [TrainerCallback](/docs/transformers/v5.6.2/en/main_classes/callback#transformers.TrainerCallback).\n\n**Parameters:**\n\ncallback (`type` or [`~transformers.TrainerCallback]`) : A [TrainerCallback](/docs/transformers/v5.6.2/en/main_classes/callback#transformers.TrainerCallback) class or an instance of a [TrainerCallback](/docs/transformers/v5.6.2/en/main_classes/callback#transformers.TrainerCallback). In the first case, will remove the first member of that class found in the list of callbacks.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "remove_callback[[transformers.Trainer.remove_callback]]", "char_start": 39733, "char_end": 40434, "token_estimate": 175, "prev_chunk_id": 1035, "next_chunk_id": 1037, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1037, "text": "#### save_metrics[[transformers.Trainer.save_metrics]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer_pt_utils.py#L921)\n\nSave metrics into a json file for that split, e.g. `train_results.json`.\n\nUnder distributed environment this is done only for a process with rank 0.\n\nTo understand the metrics please read the docstring of [log_metrics()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.log_metrics). The only difference is that raw\nunformatted numbers are saved in the current method.\n\n**Parameters:**\n\nsplit (`str`) : Mode/split name: one of `train`, `eval`, `test`, `all`\n\nmetrics (`dict[str, float]`) : The metrics returned from train/evaluate/predict\n\ncombined (`bool`, *optional*, defaults to `True`) : Creates combined metrics by updating `all_results.json` with metrics of this call", "source_file": "transformers/main_classes/trainer.md", "section_heading": "save_metrics[[transformers.Trainer.save_metrics]]", "char_start": 40435, "char_end": 41295, "token_estimate": 215, "prev_chunk_id": 1036, "next_chunk_id": 1038, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1038, "text": "#### save_model[[transformers.Trainer.save_model]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L3752)\n\nWill save the model, so you can reload it using `from_pretrained()`.\n\nWill only save from the main process.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "save_model[[transformers.Trainer.save_model]]", "char_start": 41296, "char_end": 41556, "token_estimate": 65, "prev_chunk_id": 1037, "next_chunk_id": 1039, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1039, "text": "#### save_state[[transformers.Trainer.save_state]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer_pt_utils.py#L960)\n\nSaves the Trainer state, since Trainer.save_model saves only the tokenizer with the model.\n\nUnder distributed environment this is done only for a process with rank 0.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "save_state[[transformers.Trainer.save_state]]", "char_start": 41557, "char_end": 41884, "token_estimate": 81, "prev_chunk_id": 1038, "next_chunk_id": 1040, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1040, "text": "#### set_initial_training_values[[transformers.Trainer.set_initial_training_values]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L2290)\n\nCalculates and returns the following values:\n- `num_train_epochs`\n- `num_update_steps_per_epoch`\n- `num_examples`\n- `num_train_samples`\n- `total_train_batch_size`\n- `steps_in_epoch` (total batches per epoch)\n- `max_steps`", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_initial_training_values[[transformers.Trainer.set_initial_training_values]]", "char_start": 41885, "char_end": 42293, "token_estimate": 102, "prev_chunk_id": 1039, "next_chunk_id": 1041, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1041, "text": "#### store_flos[[transformers.Trainer.store_flos]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L3875)\n\nStore the number of floating-point operations that went into the model.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "store_flos[[transformers.Trainer.store_flos]]", "char_start": 42294, "char_end": 42518, "token_estimate": 56, "prev_chunk_id": 1040, "next_chunk_id": 1042, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1042, "text": "#### train[[transformers.Trainer.train]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L1325)\n\nMain training entry point.\n\n**Parameters:**\n\nresume_from_checkpoint (`str` or `bool`, *optional*) : If a `str`, local path to a saved checkpoint as saved by a previous instance of [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer). If a `bool` and equals `True`, load the last checkpoint in *args.output_dir* as saved by a previous instance of [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer). If present, training will resume from the model/optimizer/scheduler states loaded here.\n\ntrial (`optuna.Trial` or `dict[str, Any]`, *optional*) : The trial run or the hyperparameter dictionary for hyperparameter search.\n\nignore_keys_for_eval (`list[str]`, *optional*) : A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions for evaluation during the training.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "train[[transformers.Trainer.train]]", "char_start": 42519, "char_end": 43542, "token_estimate": 255, "prev_chunk_id": 1041, "next_chunk_id": 1043, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1043, "text": "**Returns:**\n\n``TrainOutput``\n\nObject containing the global step count, training loss, and metrics.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "train[[transformers.Trainer.train]]", "char_start": 43544, "char_end": 43643, "token_estimate": 24, "prev_chunk_id": 1042, "next_chunk_id": 1044, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1044, "text": "#### training_step[[transformers.Trainer.training_step]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer.py#L1870)\n\nPerform a training step on a batch of inputs.\n\nSubclass and override to inject custom behavior.\n\n**Parameters:**\n\nmodel (`nn.Module`) : The model to train.\n\ninputs (`dict[str, torch.Tensor | Any]`) : The inputs and targets of the model. The dictionary will be unpacked before being fed to the model. Most models expect the targets under the argument `labels`. Check your model's documentation for all accepted arguments.\n\n**Returns:**\n\n``torch.Tensor``\n\nThe tensor with training loss on this batch.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "training_step[[transformers.Trainer.training_step]]", "char_start": 43644, "char_end": 44302, "token_estimate": 164, "prev_chunk_id": 1043, "next_chunk_id": 1045, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1045, "text": "## Seq2SeqTrainer[[transformers.Seq2SeqTrainer]]", "source_file": "transformers/main_classes/trainer.md", "section_heading": "Seq2SeqTrainer[[transformers.Seq2SeqTrainer]]", "char_start": 44304, "char_end": 44352, "token_estimate": 12, "prev_chunk_id": 1044, "next_chunk_id": 1046, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1046, "text": "#### transformers.Seq2SeqTrainer[[transformers.Seq2SeqTrainer]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer_seq2seq.py#L55)", "source_file": "transformers/main_classes/trainer.md", "section_heading": "transformers.Seq2SeqTrainer[[transformers.Seq2SeqTrainer]]", "char_start": 44354, "char_end": 44524, "token_estimate": 42, "prev_chunk_id": 1045, "next_chunk_id": 1047, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1047, "text": "evaluatetransformers.Seq2SeqTrainer.evaluatehttps://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer_seq2seq.py#L139[{\"name\": \"eval_dataset\", \"val\": \": torch.utils.data.dataset.Dataset | None = None\"}, {\"name\": \"ignore_keys\", \"val\": \": list[str] | None = None\"}, {\"name\": \"metric_key_prefix\", \"val\": \": str = 'eval'\"}, {\"name\": \"**gen_kwargs\", \"val\": \"\"}]- **eval_dataset** (`Dataset`, *optional*) --\n Pass a dataset if you wish to override `self.eval_dataset`. If it is an [Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset), columns\n not accepted by the `model.forward()` method are automatically removed. It must implement the `__len__`\n method.\n- **ignore_keys** (`list[str]`, *optional*) --\n A list of keys in the output of your model (if it is a dictionary) that should be ignored when\n gathering predictions.\n- **metric_key_prefix** (`str`, *optional*, defaults to `\"eval\"`) --\n An optional prefix to be used as the metrics key prefix. For example the metrics \"bleu\" will be named\n \"eval_bleu\" if the prefix is `\"eval\"` (default)\n- **max_length** (`int`, *optional*) --\n The maximum target length to use when predicting with the generate method.\n- **num_beams** (`int`, *optional*) --\n Number of beams for beam search that will be used when predicting with the generate method. 1 means no\n beam search.\n- **gen_kwargs** --\n Additional `generate` specific kwargs.0A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The\ndictionary also contains the epoch number which comes from the training state.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "transformers.Seq2SeqTrainer[[transformers.Seq2SeqTrainer]]", "char_start": 44526, "char_end": 46168, "token_estimate": 410, "prev_chunk_id": 1046, "next_chunk_id": 1048, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1048, "text": "Run evaluation and returns metrics.\n\nThe calling script will be responsible for providing a method to compute metrics, as they are task-dependent\n(pass it to the init `compute_metrics` argument).\n\nYou can also subclass and override this method to inject custom behavior.\n\n**Parameters:**\n\neval_dataset (`Dataset`, *optional*) : Pass a dataset if you wish to override `self.eval_dataset`. If it is an [Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset), columns not accepted by the `model.forward()` method are automatically removed. It must implement the `__len__` method.\n\nignore_keys (`list[str]`, *optional*) : A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions.\n\nmetric_key_prefix (`str`, *optional*, defaults to `\"eval\"`) : An optional prefix to be used as the metrics key prefix. For example the metrics \"bleu\" will be named \"eval_bleu\" if the prefix is `\"eval\"` (default)", "source_file": "transformers/main_classes/trainer.md", "section_heading": "transformers.Seq2SeqTrainer[[transformers.Seq2SeqTrainer]]", "char_start": 46170, "char_end": 47168, "token_estimate": 249, "prev_chunk_id": 1047, "next_chunk_id": 1049, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1049, "text": "max_length (`int`, *optional*) : The maximum target length to use when predicting with the generate method.\n\nnum_beams (`int`, *optional*) : Number of beams for beam search that will be used when predicting with the generate method. 1 means no beam search.\n\ngen_kwargs : Additional `generate` specific kwargs.\n\n**Returns:**\n\nA dictionary containing the evaluation loss and the potential metrics computed from the predictions. The\ndictionary also contains the epoch number which comes from the training state.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "transformers.Seq2SeqTrainer[[transformers.Seq2SeqTrainer]]", "char_start": 47170, "char_end": 47678, "token_estimate": 127, "prev_chunk_id": 1048, "next_chunk_id": 1050, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1050, "text": "#### predict[[transformers.Seq2SeqTrainer.predict]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/trainer_seq2seq.py#L195)\n\nRun prediction and returns predictions and potential metrics.\n\nDepending on the dataset and your use case, your test dataset may contain labels. In that case, this method\nwill also return metrics, like in `evaluate()`.\n\nIf your predictions or labels have different sequence lengths (for instance because you're doing dynamic\npadding in a token classification task) the predictions will be padded (on the right) to allow for\nconcatenation into one array. The padding index is -100.\n\nReturns: *NamedTuple* A namedtuple with the following keys:\n\n- predictions (`np.ndarray`): The predictions on `test_dataset`.\n- label_ids (`np.ndarray`, *optional*): The labels (if the dataset contained some).\n- metrics (`dict[str, float]`, *optional*): The potential dictionary of metrics (if the dataset contained\n labels).\n\n**Parameters:**", "source_file": "transformers/main_classes/trainer.md", "section_heading": "predict[[transformers.Seq2SeqTrainer.predict]]", "char_start": 47679, "char_end": 48665, "token_estimate": 246, "prev_chunk_id": 1049, "next_chunk_id": 1051, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1051, "text": "test_dataset (`Dataset`) : Dataset to run the predictions on. If it is a [Dataset](https://huggingface.co/docs/datasets/v4.8.4/en/package_reference/main_classes#datasets.Dataset), columns not accepted by the `model.forward()` method are automatically removed. Has to implement the method `__len__`\n\nignore_keys (`list[str]`, *optional*) : A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions.\n\nmetric_key_prefix (`str`, *optional*, defaults to `\"eval\"`) : An optional prefix to be used as the metrics key prefix. For example the metrics \"bleu\" will be named \"eval_bleu\" if the prefix is `\"eval\"` (default)\n\nmax_length (`int`, *optional*) : The maximum target length to use when predicting with the generate method.\n\nnum_beams (`int`, *optional*) : Number of beams for beam search that will be used when predicting with the generate method. 1 means no beam search.\n\ngen_kwargs : Additional `generate` specific kwargs.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "predict[[transformers.Seq2SeqTrainer.predict]]", "char_start": 48667, "char_end": 49647, "token_estimate": 245, "prev_chunk_id": 1050, "next_chunk_id": 1052, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1052, "text": "## TrainingArguments[[transformers.TrainingArguments]]", "source_file": "transformers/main_classes/trainer.md", "section_heading": "TrainingArguments[[transformers.TrainingArguments]]", "char_start": 49649, "char_end": 49703, "token_estimate": 13, "prev_chunk_id": 1051, "next_chunk_id": 1053, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1053, "text": "#### transformers.TrainingArguments[[transformers.TrainingArguments]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/training_args.py#L179)\n\nConfiguration class for controlling all aspects of model training with the Trainer.\nTrainingArguments centralizes all hyperparameters, optimization settings, logging preferences, and infrastructure choices needed for training.\n\n[HfArgumentParser](/docs/transformers/v5.6.2/en/internal/trainer_utils#transformers.HfArgumentParser) can turn this class into\n[argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the\ncommand line.\n\nget_process_log_leveltransformers.TrainingArguments.get_process_log_levelhttps://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/training_args.py#L2018[]\n\nReturns the log level to be used depending on whether this process is the main process of node 0, main process\nof node non-0, or a non-main process.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "transformers.TrainingArguments[[transformers.TrainingArguments]]", "char_start": 49705, "char_end": 50682, "token_estimate": 244, "prev_chunk_id": 1052, "next_chunk_id": 1054, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1054, "text": "For the main process the log level defaults to the logging level set (`logging.WARNING` if you didn't do\nanything) unless overridden by `log_level` argument.\n\nFor the replica processes the log level defaults to `logging.WARNING` unless overridden by `log_level_replica`\nargument.\n\nThe choice between the main and replica process settings is made according to the return value of `should_log`.\n\n**Parameters:**\n\noutput_dir (`str`, *optional*, defaults to `\"trainer_output\"`) : The output directory where the model predictions and checkpoints will be written.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "transformers.TrainingArguments[[transformers.TrainingArguments]]", "char_start": 50684, "char_end": 51241, "token_estimate": 139, "prev_chunk_id": 1053, "next_chunk_id": 1055, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1055, "text": "#### get_warmup_steps[[transformers.TrainingArguments.get_warmup_steps]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/training_args.py#L2107)\n\nGet number of steps used for a linear warmup.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "get_warmup_steps[[transformers.TrainingArguments.get_warmup_steps]]", "char_start": 51242, "char_end": 51468, "token_estimate": 56, "prev_chunk_id": 1054, "next_chunk_id": 1056, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1056, "text": "#### main_process_first[[transformers.TrainingArguments.main_process_first]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/training_args.py#L2056)\n\nA context manager for torch distributed environment where on needs to do something on the main process, while\nblocking replicas, and when it's finished releasing the replicas.\n\nOne such use is for `datasets`'s `map` feature which to be efficient should be run once on the main process,\nwhich upon completion saves a cached version of results and which then automatically gets loaded by the\nreplicas.\n\n**Parameters:**", "source_file": "transformers/main_classes/trainer.md", "section_heading": "main_process_first[[transformers.TrainingArguments.main_process_first]]", "char_start": 51469, "char_end": 52070, "token_estimate": 150, "prev_chunk_id": 1055, "next_chunk_id": 1057, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1057, "text": "local (`bool`, *optional*, defaults to `True`) : if `True` first means process of rank 0 of each node if `False` first means process of rank 0 of node rank 0 In multi-node environment with a shared filesystem you most likely will want to use `local=False` so that only the main process of the first node will do the processing. If however, the filesystem is not shared, then the main process of each node will need to do the processing, which is the default behavior.\n\ndesc (`str`, *optional*, defaults to `\"work\"`) : a work description to be used in debug logs", "source_file": "transformers/main_classes/trainer.md", "section_heading": "main_process_first[[transformers.TrainingArguments.main_process_first]]", "char_start": 52072, "char_end": 52633, "token_estimate": 140, "prev_chunk_id": 1056, "next_chunk_id": 1058, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1058, "text": "#### set_dataloader[[transformers.TrainingArguments.set_dataloader]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/training_args.py#L2641)\n\nA method that regroups all arguments linked to the dataloaders creation.\n\nExample:\n\n```py\n>>> from transformers import TrainingArguments\n\n>>> args = TrainingArguments(\"working_dir\")\n>>> args = args.set_dataloader(train_batch_size=16, eval_batch_size=64)\n>>> args.per_device_train_batch_size\n16\n```\n\n**Parameters:**\n\ndrop_last (`bool`, *optional*, defaults to `False`) : Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size) or not.\n\nnum_workers (`int`, *optional*, defaults to 0) : Number of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded in the main process.\n\npin_memory (`bool`, *optional*, defaults to `True`) : Whether you want to pin memory in data loaders or not. Will default to `True`.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_dataloader[[transformers.TrainingArguments.set_dataloader]]", "char_start": 52634, "char_end": 53601, "token_estimate": 241, "prev_chunk_id": 1057, "next_chunk_id": 1059, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1059, "text": "persistent_workers (`bool`, *optional*, defaults to `False`) : If True, the data loader will not shut down the worker processes after a dataset has been consumed once. This allows to maintain the workers Dataset instances alive. Can potentially speed up training, but will increase RAM usage. Will default to `False`.\n\nprefetch_factor (`int`, *optional*) : Number of batches loaded in advance by each worker. 2 means there will be a total of 2 * num_workers batches prefetched across all workers.\n\nauto_find_batch_size (`bool`, *optional*, defaults to `False`) : Whether to find a batch size that will fit into memory automatically through exponential decay, avoiding CUDA Out-of-Memory errors. Requires accelerate to be installed (`pip install accelerate`)", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_dataloader[[transformers.TrainingArguments.set_dataloader]]", "char_start": 53603, "char_end": 54360, "token_estimate": 189, "prev_chunk_id": 1058, "next_chunk_id": 1060, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1060, "text": "ignore_data_skip (`bool`, *optional*, defaults to `False`) : When resuming training, whether or not to skip the epochs and batches to get the data loading at the same stage as in the previous training. If set to `True`, the training will begin faster (as that skipping step can take a long time) but will not yield the same results as the interrupted training would have.\n\nsampler_seed (`int`, *optional*) : Random seed to be used with data samplers. If not set, random generators for data sampling will use the same seed as `self.seed`. This can be used to ensure reproducibility of data sampling, independent of the model seed.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_dataloader[[transformers.TrainingArguments.set_dataloader]]", "char_start": 54362, "char_end": 54991, "token_estimate": 157, "prev_chunk_id": 1059, "next_chunk_id": 1061, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1061, "text": "#### set_evaluate[[transformers.TrainingArguments.set_evaluate]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/training_args.py#L2253)\n\nA method that regroups all arguments linked to evaluation.\n\nExample:\n\n```py\n>>> from transformers import TrainingArguments\n\n>>> args = TrainingArguments(\"working_dir\")\n>>> args = args.set_evaluate(strategy=\"steps\", steps=100)\n>>> args.eval_steps\n100\n```\n\n**Parameters:**\n\nstrategy (`str` or [IntervalStrategy](/docs/transformers/v5.6.2/en/internal/trainer_utils#transformers.IntervalStrategy), *optional*, defaults to `\"no\"`) : The evaluation strategy to adopt during training. Possible values are: - `\"no\"`: No evaluation is done during training. - `\"steps\"`: Evaluation is done (and logged) every `steps`. - `\"epoch\"`: Evaluation is done at the end of each epoch. Setting a `strategy` different from `\"no\"` will set `self.do_eval` to `True`.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_evaluate[[transformers.TrainingArguments.set_evaluate]]", "char_start": 54992, "char_end": 55910, "token_estimate": 229, "prev_chunk_id": 1060, "next_chunk_id": 1062, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1062, "text": "steps (`int`, *optional*, defaults to 500) : Number of update steps between two evaluations if `strategy=\"steps\"`.\n\nbatch_size (`int` *optional*, defaults to 8) : The batch size per device (GPU/TPU core/CPU...) used for evaluation.\n\naccumulation_steps (`int`, *optional*) : Number of predictions steps to accumulate the output tensors for, before moving the results to the CPU. If left unset, the whole predictions are accumulated on GPU/TPU before being moved to the CPU (faster but requires more memory).\n\ndelay (`float`, *optional*) : Number of epochs or steps to wait for before the first evaluation can be performed, depending on the eval_strategy.\n\nloss_only (`bool`, *optional*, defaults to `False`) : Ignores all outputs except the loss.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_evaluate[[transformers.TrainingArguments.set_evaluate]]", "char_start": 55912, "char_end": 56657, "token_estimate": 186, "prev_chunk_id": 1061, "next_chunk_id": 1063, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1063, "text": "#### set_logging[[transformers.TrainingArguments.set_logging]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/training_args.py#L2395)\n\nA method that regroups all arguments linked to logging.\n\nExample:\n\n```py\n>>> from transformers import TrainingArguments\n\n>>> args = TrainingArguments(\"working_dir\")\n>>> args = args.set_logging(strategy=\"steps\", steps=100)\n>>> args.logging_steps\n100\n```\n\n**Parameters:**\n\nstrategy (`str` or [IntervalStrategy](/docs/transformers/v5.6.2/en/internal/trainer_utils#transformers.IntervalStrategy), *optional*, defaults to `\"steps\"`) : The logging strategy to adopt during training. Possible values are: - `\"no\"`: No logging is done during training. - `\"epoch\"`: Logging is done at the end of each epoch. - `\"steps\"`: Logging is done every `logging_steps`.\n\nsteps (`int`, *optional*, defaults to 500) : Number of update steps between two logs if `strategy=\"steps\"`.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_logging[[transformers.TrainingArguments.set_logging]]", "char_start": 0, "char_end": 931, "token_estimate": 232, "prev_chunk_id": 1062, "next_chunk_id": 1064, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1064, "text": "level (`str`, *optional*, defaults to `\"passive\"`) : Logger log level to use on the main process. Possible choices are the log levels as strings: `\"debug\"`, `\"info\"`, `\"warning\"`, `\"error\"` and `\"critical\"`, plus a `\"passive\"` level which doesn't set anything and lets the application set the level.\n\nreport_to (`str` or `list[str]`, *optional*, defaults to `\"none\"`) : The list of integrations to report the results and logs to. Supported platforms are `\"azure_ml\"`, `\"clearml\"`, `\"codecarbon\"`, `\"comet_ml\"`, `\"dagshub\"`, `\"dvclive\"`, `\"flyte\"`, `\"mlflow\"`, `\"swanlab\"`, `\"tensorboard\"`, `\"trackio\"` and `\"wandb\"`. Use `\"all\"` to report to all integrations installed, `\"none\"` for no integrations.\n\nfirst_step (`bool`, *optional*, defaults to `False`) : Whether to log and evaluate the first `global_step` or not.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_logging[[transformers.TrainingArguments.set_logging]]", "char_start": 57592, "char_end": 58407, "token_estimate": 203, "prev_chunk_id": 1063, "next_chunk_id": 1065, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1065, "text": "nan_inf_filter (`bool`, *optional*, defaults to `True`) : Whether to filter `nan` and `inf` losses for logging. If set to `True` the loss of every step that is `nan` or `inf` is filtered and the average loss of the current logging window is taken instead. `nan_inf_filter` only influences the logging of loss values, it does not change the behavior the gradient is computed or applied to the model. \n\non_each_node (`bool`, *optional*, defaults to `True`) : In multinode distributed training, whether to log using `log_level` once per node, or only on the main node.\n\nreplica_level (`str`, *optional*, defaults to `\"passive\"`) : Logger log level to use on replicas. Same choices as `log_level`", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_logging[[transformers.TrainingArguments.set_logging]]", "char_start": 58409, "char_end": 59106, "token_estimate": 174, "prev_chunk_id": 1064, "next_chunk_id": 1066, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1066, "text": "#### set_lr_scheduler[[transformers.TrainingArguments.set_lr_scheduler]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/training_args.py#L2595)\n\nA method that regroups all arguments linked to the learning rate scheduler and its hyperparameters.\n\nExample:\n\n```py\n>>> from transformers import TrainingArguments\n\n>>> args = TrainingArguments(\"working_dir\")\n>>> args = args.set_lr_scheduler(name=\"cosine\", warmup_steps=0.05)\n>>> args.warmup_steps\n0.05\n```\n\n**Parameters:**\n\nname (`str` or [SchedulerType](/docs/transformers/v5.6.2/en/main_classes/optimizer_schedules#transformers.SchedulerType), *optional*, defaults to `\"linear\"`) : The scheduler type to use. See the documentation of [SchedulerType](/docs/transformers/v5.6.2/en/main_classes/optimizer_schedules#transformers.SchedulerType) for all possible values.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_lr_scheduler[[transformers.TrainingArguments.set_lr_scheduler]]", "char_start": 59107, "char_end": 59955, "token_estimate": 212, "prev_chunk_id": 1065, "next_chunk_id": 1067, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1067, "text": "num_epochs(`float`, *optional*, defaults to 3.0) : Total number of training epochs to perform (if not an integer, will perform the decimal part percents of the last epoch before stopping training).\n\nmax_steps (`int`, *optional*, defaults to -1) : If set to a positive number, the total number of training steps to perform. Overrides `num_train_epochs`. For a finite dataset, training is reiterated through the dataset (if all data is exhausted) until `max_steps` is reached.\n\nwarmup_steps (`float`, *optional*, defaults to 0) : Number of steps used for a linear warmup from 0 to `learning_rate`. Should be an integer or a float in range `[0,1)`. If smaller than 1, will be interpreted as ratio of steps used for a linear warmup from 0 to `learning_rate`.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_lr_scheduler[[transformers.TrainingArguments.set_lr_scheduler]]", "char_start": 59957, "char_end": 60712, "token_estimate": 188, "prev_chunk_id": 1066, "next_chunk_id": 1068, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1068, "text": "#### set_optimizer[[transformers.TrainingArguments.set_optimizer]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/training_args.py#L2544)\n\nA method that regroups all arguments linked to the optimizer and its hyperparameters.\n\nExample:\n\n```py\n>>> from transformers import TrainingArguments\n\n>>> args = TrainingArguments(\"working_dir\")\n>>> args = args.set_optimizer(name=\"adamw_torch\", beta1=0.8)\n>>> args.optim\n'adamw_torch'\n```\n\n**Parameters:**\n\nname (`str` or `training_args.OptimizerNames`, *optional*, defaults to `\"adamw_torch\"`) : The optimizer to use: `\"adamw_torch\"`, `\"adamw_torch_fused\"`, `\"adamw_apex_fused\"`, `\"adamw_anyprecision\"` or `\"adafactor\"`.\n\nlearning_rate (`float`, *optional*, defaults to 5e-5) : The initial learning rate.\n\nweight_decay (`float`, *optional*, defaults to 0) : The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_optimizer[[transformers.TrainingArguments.set_optimizer]]", "char_start": 60713, "char_end": 61639, "token_estimate": 231, "prev_chunk_id": 1067, "next_chunk_id": 1069, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1069, "text": "beta1 (`float`, *optional*, defaults to 0.9) : The beta1 hyperparameter for the adam optimizer or its variants.\n\nbeta2 (`float`, *optional*, defaults to 0.999) : The beta2 hyperparameter for the adam optimizer or its variants.\n\nepsilon (`float`, *optional*, defaults to 1e-8) : The epsilon hyperparameter for the adam optimizer or its variants.\n\nargs (`str`, *optional*) : Optional arguments that are supplied to AnyPrecisionAdamW (only useful when `optim=\"adamw_anyprecision\"`).", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_optimizer[[transformers.TrainingArguments.set_optimizer]]", "char_start": 61641, "char_end": 62120, "token_estimate": 119, "prev_chunk_id": 1068, "next_chunk_id": 1070, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1070, "text": "#### set_push_to_hub[[transformers.TrainingArguments.set_push_to_hub]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/training_args.py#L2470)\n\nA method that regroups all arguments linked to synchronizing checkpoints with the Hub.\n\nCalling this method will set `self.push_to_hub` to `True`, which means the `output_dir` will begin a git\ndirectory synced with the repo (determined by `model_id`) and the content will be pushed each time a save is\ntriggered (depending on your `self.save_strategy`). Calling [save_model()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.save_model) will also trigger a push.\n\nExample:\n\n```py\n>>> from transformers import TrainingArguments\n\n>>> args = TrainingArguments(\"working_dir\")\n>>> args = args.set_push_to_hub(\"me/awesome-model\")\n>>> args.hub_model_id\n'me/awesome-model'\n```\n\n**Parameters:**", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_push_to_hub[[transformers.TrainingArguments.set_push_to_hub]]", "char_start": 62121, "char_end": 63008, "token_estimate": 221, "prev_chunk_id": 1069, "next_chunk_id": 1071, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1071, "text": "model_id (`str`) : The name of the repository to keep in sync with the local *output_dir*. It can be a simple model ID in which case the model will be pushed in your namespace. Otherwise it should be the whole repository name, for instance `\"user_name/model\"`, which allows you to push to an organization you are a member of with `\"organization_name/model\"`.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_push_to_hub[[transformers.TrainingArguments.set_push_to_hub]]", "char_start": 63010, "char_end": 63368, "token_estimate": 89, "prev_chunk_id": 1070, "next_chunk_id": 1072, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1072, "text": "strategy (`str` or `HubStrategy`, *optional*, defaults to `\"every_save\"`) : Defines the scope of what is pushed to the Hub and when. Possible values are: - `\"end\"`: push the model, its configuration, the processing_class e.g. tokenizer (if passed along to the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer)) and a draft of a model card when the [save_model()](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer.save_model) method is called. - `\"every_save\"`: push the model, its configuration, the processing_class e.g. tokenizer (if passed along to the [Trainer](/docs/transformers/v5.6.2/en/main_classes/trainer#transformers.Trainer)) and a draft of a model card each time there is a model save. The pushes are asynchronous to not block training, and in case the save are very frequent, a new push is only attempted if the previous one is finished. A last push is made with the final model at the end of training. - `\"checkpoint\"`: like `\"every_save\"` but the latest checkpoint is also pushed in a subfolder named last-checkpoint, allowing you to resume training easily with `trainer.train(resume_from_checkpoint=\"last-checkpoint\")`. - `\"all_checkpoints\"`: like `\"checkpoint\"` but all checkpoints are pushed like they appear in the output folder (so you will get one checkpoint folder per folder in your final repository)", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_push_to_hub[[transformers.TrainingArguments.set_push_to_hub]]", "char_start": 63370, "char_end": 64749, "token_estimate": 345, "prev_chunk_id": 1071, "next_chunk_id": 1073, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1073, "text": "token (`str`, *optional*) : The token to use to push the model to the Hub. Will default to the token in the cache folder obtained with `hf auth login`.\n\nprivate_repo (`bool`, *optional*, defaults to `False`) : Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.\n\nalways_push (`bool`, *optional*, defaults to `False`) : Unless this is `True`, the `Trainer` will skip pushing a checkpoint when the previous push is not finished.\n\nrevision (`str`, *optional*) : The revision to use when pushing to the Hub. Can be a branch name, a tag, or a commit hash.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_push_to_hub[[transformers.TrainingArguments.set_push_to_hub]]", "char_start": 64752, "char_end": 65425, "token_estimate": 168, "prev_chunk_id": 1072, "next_chunk_id": 1074, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1074, "text": "#### set_save[[transformers.TrainingArguments.set_save]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/training_args.py#L2346)\n\nA method that regroups all arguments linked to checkpoint saving.\n\nExample:\n\n```py\n>>> from transformers import TrainingArguments\n\n>>> args = TrainingArguments(\"working_dir\")\n>>> args = args.set_save(strategy=\"steps\", steps=100)\n>>> args.save_steps\n100\n```\n\n**Parameters:**\n\nstrategy (`str` or [IntervalStrategy](/docs/transformers/v5.6.2/en/internal/trainer_utils#transformers.IntervalStrategy), *optional*, defaults to `\"steps\"`) : The checkpoint save strategy to adopt during training. Possible values are: - `\"no\"`: No save is done during training. - `\"epoch\"`: Save is done at the end of each epoch. - `\"steps\"`: Save is done every `save_steps`.\n\nsteps (`int`, *optional*, defaults to 500) : Number of updates steps before two checkpoint saves if `strategy=\"steps\"`.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_save[[transformers.TrainingArguments.set_save]]", "char_start": 0, "char_end": 937, "token_estimate": 234, "prev_chunk_id": 1073, "next_chunk_id": 1075, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1075, "text": "total_limit (`int`, *optional*) : If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in `output_dir`.\n\non_each_node (`bool`, *optional*, defaults to `False`) : When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on the main one. This should not be activated when the different nodes use the same storage as the files will be saved with the same names for each node.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_save[[transformers.TrainingArguments.set_save]]", "char_start": 66366, "char_end": 66830, "token_estimate": 116, "prev_chunk_id": 1074, "next_chunk_id": 1076, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1076, "text": "#### set_testing[[transformers.TrainingArguments.set_testing]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/training_args.py#L2310)\n\nA method that regroups all basic arguments linked to testing on a held-out dataset.\n\nCalling this method will automatically set `self.do_predict` to `True`.\n\nExample:\n\n```py\n>>> from transformers import TrainingArguments\n\n>>> args = TrainingArguments(\"working_dir\")\n>>> args = args.set_testing(batch_size=32)\n>>> args.per_device_eval_batch_size\n32\n```\n\n**Parameters:**\n\nbatch_size (`int` *optional*, defaults to 8) : The batch size per device (GPU/TPU core/CPU...) used for testing.\n\nloss_only (`bool`, *optional*, defaults to `False`) : Ignores all outputs except the loss.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_testing[[transformers.TrainingArguments.set_testing]]", "char_start": 66831, "char_end": 67576, "token_estimate": 186, "prev_chunk_id": 1075, "next_chunk_id": 1077, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1077, "text": "#### set_training[[transformers.TrainingArguments.set_training]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/training_args.py#L2178)\n\nA method that regroups all basic arguments linked to the training.\n\nCalling this method will automatically set `self.do_train` to `True`.\n\nExample:\n\n```py\n>>> from transformers import TrainingArguments\n\n>>> args = TrainingArguments(\"working_dir\")\n>>> args = args.set_training(learning_rate=1e-4, batch_size=32)\n>>> args.learning_rate\n1e-4\n```\n\n**Parameters:**\n\nlearning_rate (`float`, *optional*, defaults to 5e-5) : The initial learning rate for the optimizer.\n\nbatch_size (`int` *optional*, defaults to 8) : The batch size per device (GPU/TPU core/CPU...) used for training.\n\nweight_decay (`float`, *optional*, defaults to 0) : The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights in the optimizer.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_training[[transformers.TrainingArguments.set_training]]", "char_start": 67577, "char_end": 68489, "token_estimate": 228, "prev_chunk_id": 1076, "next_chunk_id": 1078, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1078, "text": "num_train_epochs(`float`, *optional*, defaults to 3.0) : Total number of training epochs to perform (if not an integer, will perform the decimal part percents of the last epoch before stopping training).\n\nmax_steps (`int`, *optional*, defaults to -1) : If set to a positive number, the total number of training steps to perform. Overrides `num_train_epochs`. For a finite dataset, training is reiterated through the dataset (if all data is exhausted) until `max_steps` is reached.\n\ngradient_accumulation_steps (`int`, *optional*, defaults to 1) : Number of updates steps to accumulate the gradients for, before performing a backward/update pass. When using gradient accumulation, one step is counted as one step with backward pass. Therefore, logging, evaluation, save will be conducted every `gradient_accumulation_steps * xxx_step` training examples.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_training[[transformers.TrainingArguments.set_training]]", "char_start": 68491, "char_end": 69346, "token_estimate": 213, "prev_chunk_id": 1077, "next_chunk_id": 1079, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1079, "text": "seed (`int`, *optional*, defaults to 42) : Random seed that will be set at the beginning of training. To ensure reproducibility across runs, use the `~Trainer.model_init` function to instantiate the model if it has some randomly initialized parameters.\n\ngradient_checkpointing (`bool`, *optional*, defaults to `False`) : If True, use gradient checkpointing to save memory at the expense of slower backward pass.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "set_training[[transformers.TrainingArguments.set_training]]", "char_start": 69351, "char_end": 69762, "token_estimate": 102, "prev_chunk_id": 1078, "next_chunk_id": 1080, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1080, "text": "#### to_dict[[transformers.TrainingArguments.to_dict]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/training_args.py#L2128)\n\nSerializes this instance while replace `Enum` by their values (for JSON serialization support). It obfuscates\nthe token values by removing their value.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "to_dict[[transformers.TrainingArguments.to_dict]]", "char_start": 69763, "char_end": 70077, "token_estimate": 78, "prev_chunk_id": 1079, "next_chunk_id": 1081, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1081, "text": "#### to_json_string[[transformers.TrainingArguments.to_json_string]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/training_args.py#L2158)\n\nSerializes this instance to a JSON string.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "to_json_string[[transformers.TrainingArguments.to_json_string]]", "char_start": 70078, "char_end": 70297, "token_estimate": 54, "prev_chunk_id": 1080, "next_chunk_id": 1082, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1082, "text": "#### to_sanitized_dict[[transformers.TrainingArguments.to_sanitized_dict]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/training_args.py#L2164)\n\nSanitized serialization to use with TensorBoard's hparams", "source_file": "transformers/main_classes/trainer.md", "section_heading": "to_sanitized_dict[[transformers.TrainingArguments.to_sanitized_dict]]", "char_start": 70298, "char_end": 70538, "token_estimate": 60, "prev_chunk_id": 1081, "next_chunk_id": 1083, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1083, "text": "## Seq2SeqTrainingArguments[[transformers.Seq2SeqTrainingArguments]]", "source_file": "transformers/main_classes/trainer.md", "section_heading": "Seq2SeqTrainingArguments[[transformers.Seq2SeqTrainingArguments]]", "char_start": 70540, "char_end": 70608, "token_estimate": 17, "prev_chunk_id": 1082, "next_chunk_id": 1084, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1084, "text": "#### transformers.Seq2SeqTrainingArguments[[transformers.Seq2SeqTrainingArguments]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/training_args_seq2seq.py#L29)\n\nConfiguration class for controlling all aspects of model training with the Trainer.\nTrainingArguments centralizes all hyperparameters, optimization settings, logging preferences, and infrastructure choices needed for training.\n\n[HfArgumentParser](/docs/transformers/v5.6.2/en/internal/trainer_utils#transformers.HfArgumentParser) can turn this class into\n[argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the\ncommand line.\n\nto_dicttransformers.Seq2SeqTrainingArguments.to_dicthttps://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/training_args_seq2seq.py#L84[]\n\nSerializes this instance while replace `Enum` by their values and `GenerationConfig` by dictionaries (for JSON\nserialization support). It obfuscates the token values by removing their value.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "transformers.Seq2SeqTrainingArguments[[transformers.Seq2SeqTrainingArguments]]", "char_start": 70610, "char_end": 71635, "token_estimate": 256, "prev_chunk_id": 1083, "next_chunk_id": 1085, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1085, "text": "**Parameters:**\n\noutput_dir (`str`, *optional*, defaults to `\"trainer_output\"`) : The output directory where the model predictions and checkpoints will be written.", "source_file": "transformers/main_classes/trainer.md", "section_heading": "transformers.Seq2SeqTrainingArguments[[transformers.Seq2SeqTrainingArguments]]", "char_start": 51078, "char_end": 51241, "token_estimate": 40, "prev_chunk_id": 1084, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/main_classes/trainer", "doc_title": "Trainer" }, { "chunk_id": 1086, "text": "# Generation\n\nEach framework has a generate method for text generation implemented in their respective `GenerationMixin` class:\n\n- PyTorch [generate()](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationMixin.generate) is implemented in [GenerationMixin](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationMixin).\n\nYou can parameterize the generate method with a [GenerationConfig](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig) class instance. Please refer to this class for the complete list of generation parameters, which control the behavior of the generation method.\n\nTo learn how to inspect a model's generation configuration, what are the defaults, how to change the parameters ad hoc,\nand how to create and save a customized generation configuration, refer to the\n[text generation strategies guide](../generation_strategies). The guide also explains how to use related features,\nlike token streaming.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "Generation", "char_start": 0, "char_end": 1011, "token_estimate": 252, "prev_chunk_id": null, "next_chunk_id": 1087, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1087, "text": "## GenerationConfig[[transformers.GenerationConfig]]", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "GenerationConfig[[transformers.GenerationConfig]]", "char_start": 1013, "char_end": 1065, "token_estimate": 13, "prev_chunk_id": 1086, "next_chunk_id": 1088, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1088, "text": "#### transformers.GenerationConfig[[transformers.GenerationConfig]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/configuration_utils.py#L83)\n\nClass that holds a configuration for a generation task. A `generate` call supports the following generation methods\nfor text-decoder, text-to-text, speech-to-text, and vision-to-text models:\n\n- *greedy decoding* if `num_beams=1` and `do_sample=False`\n- *multinomial sampling* if `num_beams=1` and `do_sample=True`\n- *beam-search decoding* if `num_beams>1` and `do_sample=False`\n- *beam-search multinomial sampling* if `num_beams>1` and `do_sample=True`\n- *assisted decoding* if `assistant_model` or `prompt_lookup_num_tokens` is passed to `.generate()`\n\nTo learn more about decoding strategies refer to the [text generation strategies guide](../generation_strategies).", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.GenerationConfig[[transformers.GenerationConfig]]", "char_start": 1067, "char_end": 1926, "token_estimate": 214, "prev_chunk_id": 1087, "next_chunk_id": 1089, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1089, "text": "A large number of these flags control the logits or the stopping criteria of the generation. Make sure you check\nthe [generate-related classes](https://huggingface.co/docs/transformers/internal/generation_utils) for a full\ndescription of the possible manipulations, as well as examples of their usage.\n\nNote: the configuration fields that are still `None` will be overridden by `GenerationConfig._get_default_generation_params()`\nduring the generation loop. If you want to use different values for these fields, make sure to explicitly set them in the\ngeneration config.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.GenerationConfig[[transformers.GenerationConfig]]", "char_start": 1928, "char_end": 2498, "token_estimate": 142, "prev_chunk_id": 1088, "next_chunk_id": 1090, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1090, "text": "from_pretrainedtransformers.GenerationConfig.from_pretrainedhttps://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/configuration_utils.py#L827[{\"name\": \"pretrained_model_name\", \"val\": \": str | os.PathLike\"}, {\"name\": \"config_file_name\", \"val\": \": str | os.PathLike | None = None\"}, {\"name\": \"cache_dir\", \"val\": \": str | os.PathLike | None = None\"}, {\"name\": \"force_download\", \"val\": \": bool = False\"}, {\"name\": \"local_files_only\", \"val\": \": bool = False\"}, {\"name\": \"token\", \"val\": \": str | bool | None = None\"}, {\"name\": \"revision\", \"val\": \": str = 'main'\"}, {\"name\": \"**kwargs\", \"val\": \"\"}]- **pretrained_model_name** (`str` or `os.PathLike`) --\n This can be either:", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.GenerationConfig[[transformers.GenerationConfig]]", "char_start": 2500, "char_end": 3198, "token_estimate": 174, "prev_chunk_id": 1089, "next_chunk_id": 1091, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1091, "text": "- a string, the *model id* of a pretrained model configuration hosted inside a model repo on\n huggingface.co.\n - a path to a *directory* containing a configuration file saved using the\n [save_pretrained()](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig.save_pretrained) method, e.g., `./my_model_directory/`.\n- **config_file_name** (`str` or `os.PathLike`, *optional*, defaults to `\"generation_config.json\"`) --\n Name of the generation configuration JSON file to be loaded from `pretrained_model_name`.\n- **cache_dir** (`str` or `os.PathLike`, *optional*) --\n Path to a directory in which a downloaded pretrained model configuration should be cached if the\n standard cache should not be used.\n- **force_download** (`bool`, *optional*, defaults to `False`) --\n Whether or not to force to (re-)download the configuration files and override the cached versions if\n they exist.\n- **proxies** (`dict[str, str]`, *optional*) --\n A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',\n 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.\n- **token** (`str` or `bool`, *optional*) --\n The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use\n the token generated when running `hf auth login` (stored in `~/.huggingface`).\n- **revision** (`str`, *optional*, defaults to `\"main\"`) --\n The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a\n git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any\n identifier allowed by git.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.GenerationConfig[[transformers.GenerationConfig]]", "char_start": 3202, "char_end": 4875, "token_estimate": 418, "prev_chunk_id": 1090, "next_chunk_id": 1092, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1092, "text": "To test a pull request you made on the Hub, you can pass `revision=\"refs/pr/\"`.\n\n- **return_unused_kwargs** (`bool`, *optional*, defaults to `False`) --\n If `False`, then this function returns just the final configuration object.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.GenerationConfig[[transformers.GenerationConfig]]", "char_start": 0, "char_end": 230, "token_estimate": 57, "prev_chunk_id": 1091, "next_chunk_id": 1093, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1093, "text": "If `True`, then this functions returns a `Tuple(config, unused_kwargs)` where *unused_kwargs* is a\n dictionary consisting of the key/value pairs whose keys are not configuration attributes: i.e., the\n part of `kwargs` which has not been used to update `config` and is otherwise ignored.\n- **subfolder** (`str`, *optional*, defaults to `\"\"`) --\n In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can\n specify the folder name here.\n- **kwargs** (`dict[str, Any]`, *optional*) --\n The values in kwargs of any keys which are configuration attributes will be used to override the loaded\n values. Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled\n by the `return_unused_kwargs` keyword parameter.0[GenerationConfig](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig)The configuration object instantiated from this pretrained model.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.GenerationConfig[[transformers.GenerationConfig]]", "char_start": 5121, "char_end": 6086, "token_estimate": 241, "prev_chunk_id": 1092, "next_chunk_id": 1094, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1094, "text": "Instantiate a [GenerationConfig](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig) from a generation configuration file.\n\nExamples:", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.GenerationConfig[[transformers.GenerationConfig]]", "char_start": 6088, "char_end": 6258, "token_estimate": 42, "prev_chunk_id": 1093, "next_chunk_id": 1095, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1095, "text": "```python\n>>> from transformers import GenerationConfig\n\n>>> # Download configuration from huggingface.co and cache.\n>>> generation_config = GenerationConfig.from_pretrained(\"openai-community/gpt2\")\n\n>>> # E.g. config was saved using *save_pretrained('./test/saved_model/')*\n>>> generation_config.save_pretrained(\"./test/saved_model/\")\n>>> generation_config = GenerationConfig.from_pretrained(\"./test/saved_model/\")\n\n>>> # You can also specify configuration names to your generation configuration file\n>>> generation_config.save_pretrained(\"./test/saved_model/\", config_file_name=\"my_configuration.json\")\n>>> generation_config = GenerationConfig.from_pretrained(\"./test/saved_model/\", \"my_configuration.json\")\n\n>>> # If you'd like to try a minor variation to an existing configuration, you can also pass generation\n>>> # arguments to `.from_pretrained()`. Be mindful that typos and unused arguments will be ignored\n>>> generation_config, unused_kwargs = GenerationConfig.from_pretrained(\n... \"openai-community/gpt2\", top_k=1, foo=False, do_sample=True, return_unused_kwargs=True\n... )\n>>> generation_config.top_k\n1\n\n>>> unused_kwargs\n{'foo': False}\n```", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.GenerationConfig[[transformers.GenerationConfig]]", "char_start": 6260, "char_end": 7416, "token_estimate": 289, "prev_chunk_id": 1094, "next_chunk_id": 1096, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1096, "text": "**Returns:**\n\n`[GenerationConfig](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig)`\n\nThe configuration object instantiated from this pretrained model.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.GenerationConfig[[transformers.GenerationConfig]]", "char_start": 7418, "char_end": 7608, "token_estimate": 47, "prev_chunk_id": 1095, "next_chunk_id": 1097, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1097, "text": "#### from_model_config[[transformers.GenerationConfig.from_model_config]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/configuration_utils.py#L1159)\n\nInstantiates a [GenerationConfig](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig) from a [PreTrainedConfig](/docs/transformers/v5.6.2/en/main_classes/configuration#transformers.PreTrainedConfig). This function is useful to convert legacy\n[PreTrainedConfig](/docs/transformers/v5.6.2/en/main_classes/configuration#transformers.PreTrainedConfig) objects, which may contain generation parameters, into a stand-alone [GenerationConfig](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig).\n\n**Parameters:**\n\nmodel_config (`PreTrainedConfig | dict`) : The model config that will be used to instantiate the generation config.\n\n**Returns:**\n\n`[GenerationConfig](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig)`", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "from_model_config[[transformers.GenerationConfig.from_model_config]]", "char_start": 7609, "char_end": 8629, "token_estimate": 255, "prev_chunk_id": 1096, "next_chunk_id": 1098, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1098, "text": "The configuration object instantiated from those parameters.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "from_model_config[[transformers.GenerationConfig.from_model_config]]", "char_start": 8631, "char_end": 8691, "token_estimate": 15, "prev_chunk_id": 1097, "next_chunk_id": 1099, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1099, "text": "#### save_pretrained[[transformers.GenerationConfig.save_pretrained]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/configuration_utils.py#L768)\n\nSave a generation configuration object to the directory `save_directory`, so that it can be re-loaded using the\n[from_pretrained()](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig.from_pretrained) class method.\n\n**Parameters:**\n\nsave_directory (`str` or `os.PathLike`) : Directory where the configuration JSON file will be saved (will be created if it does not exist).\n\nconfig_file_name (`str` or `os.PathLike`, *optional*, defaults to `\"generation_config.json\"`) : Name of the generation configuration JSON file to be saved in `save_directory`.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "save_pretrained[[transformers.GenerationConfig.save_pretrained]]", "char_start": 8692, "char_end": 9471, "token_estimate": 194, "prev_chunk_id": 1098, "next_chunk_id": 1100, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1100, "text": "push_to_hub (`bool`, *optional*, defaults to `False`) : Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the repository you want to push to with `repo_id` (will default to the name of `save_directory` in your namespace).\n\nkwargs (`dict[str, Any]`, *optional*) : Additional key word arguments passed along to the [push_to_hub()](/docs/transformers/v5.6.2/en/main_classes/model#transformers.utils.PushToHubMixin.push_to_hub) method.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "save_pretrained[[transformers.GenerationConfig.save_pretrained]]", "char_start": 9473, "char_end": 9951, "token_estimate": 119, "prev_chunk_id": 1099, "next_chunk_id": 1101, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1101, "text": "#### update[[transformers.GenerationConfig.update]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/configuration_utils.py#L1209)\n\nUpdates attributes of this class instance with attributes from `kwargs` if they match existing attributes,\nreturning all the unused kwargs.\n\n**Parameters:**\n\ndefaults_only (`bool`, *optional*, defaults to `False`) : Whether to update all keys in config with `kwargs` or only those that are set to `None` (i.e. default value).\n\nallow_custom_entries (`bool`, *optional*, defaults to `False`) : Whether to allow updating custom entries into the config with `kwargs` if not present in the current config.\n\nkwargs (`dict[str, Any]`) : Dictionary of attributes to tentatively update this class.\n\n**Returns:**\n\n``dict[str, Any]``\n\nDictionary containing all the key-value pairs that were not used to update the instance.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "update[[transformers.GenerationConfig.update]]", "char_start": 9952, "char_end": 10841, "token_estimate": 222, "prev_chunk_id": 1100, "next_chunk_id": 1102, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1102, "text": "#### validate[[transformers.GenerationConfig.validate]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/configuration_utils.py#L590)\n\nValidates the values of the attributes of the [GenerationConfig](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig) instance. Raises exceptions in the presence\nof parameterization that can be detected as incorrect from the configuration instance alone.\n\nNote that some parameters not validated here are best validated at generate runtime, as they may depend on\nother inputs and/or the model, such as parameters related to the generation length.\n\n**Parameters:**\n\nstrict (bool) : If True, raise an exception for any issues found. If False, only log issues.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "validate[[transformers.GenerationConfig.validate]]", "char_start": 10842, "char_end": 11615, "token_estimate": 193, "prev_chunk_id": 1101, "next_chunk_id": 1103, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1103, "text": "#### get_generation_mode[[transformers.GenerationConfig.get_generation_mode]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/configuration_utils.py#L485)\n\nReturns the generation mode triggered by the [GenerationConfig](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig) instance.\n\n**Parameters:**\n\nassistant_model (`PreTrainedModel`, *optional*) : The assistant model to be used for assisted generation. If set, the generation mode will be assisted generation.\n\n**Returns:**\n\n``GenerationMode``\n\nThe generation mode triggered by the instance.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "get_generation_mode[[transformers.GenerationConfig.get_generation_mode]]", "char_start": 11616, "char_end": 12243, "token_estimate": 156, "prev_chunk_id": 1102, "next_chunk_id": 1104, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1104, "text": "## GenerationMixin[[transformers.GenerationMixin]]", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "GenerationMixin[[transformers.GenerationMixin]]", "char_start": 12245, "char_end": 12295, "token_estimate": 12, "prev_chunk_id": 1103, "next_chunk_id": 1105, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1105, "text": "#### transformers.GenerationMixin[[transformers.GenerationMixin]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/utils.py#L338)\n\nA class containing all functions for auto-regressive text generation, to be used as a mixin in model classes.\nInheriting from this class causes the model to have special generation-related behavior, such as loading a\n`GenerationConfig` at initialization time or ensuring `generate`-related tests are run in `transformers` CI.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.GenerationMixin[[transformers.GenerationMixin]]", "char_start": 12297, "char_end": 12798, "token_estimate": 125, "prev_chunk_id": 1104, "next_chunk_id": 1106, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1106, "text": "A model class should inherit from `GenerationMixin` to enable calling methods like `generate`, or when it\nhas defined a custom `generate` method that relies on `GenerationMixin`, directly or indirectly, which\napproximately shares the same interface to public methods like `generate`. Three examples:\n- `LlamaForCausalLM` should inherit from `GenerationMixin` to enable calling `generate` and other public\n methods in the mixin;\n- `BlipForQuestionAnswering` has a custom `generate` method that approximately shares the same interface as\n `GenerationMixin.generate` (it has a few extra arguments, and the same output). That function also calls\n `GenerationMixin.generate` indirectly, through an inner model. As such, `BlipForQuestionAnswering` should\n inherit from `GenerationMixin` to benefit from all generation-related automation in our codebase;\n- `BarkModel` has a custom `generate` method and one of its inner models calls `GenerationMixin.generate`.\n However, its `generate` does not share the same interface as `GenerationMixin.generate`. In this case,\n `BarkModel` should NOT inherit from `GenerationMixin`, as it breaks the `generate` interface.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.GenerationMixin[[transformers.GenerationMixin]]", "char_start": 12800, "char_end": 13959, "token_estimate": 289, "prev_chunk_id": 1105, "next_chunk_id": 1107, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1107, "text": "The class exposes [generate()](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationMixin.generate), which can be used for:\n- *greedy decoding* if `num_beams=1` and `do_sample=False`\n- *multinomial sampling* if `num_beams=1` and `do_sample=True`\n- *beam-search decoding* if `num_beams>1` and `do_sample=False`\n- *beam-search multinomial sampling* if `num_beams>1` and `do_sample=True`\n- *assisted decoding* if `assistant_model` or `prompt_lookup_num_tokens` is passed to `.generate()`\n\nTo learn more about decoding strategies refer to the [text generation strategies guide](../generation_strategies).", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.GenerationMixin[[transformers.GenerationMixin]]", "char_start": 13961, "char_end": 14589, "token_estimate": 157, "prev_chunk_id": 1106, "next_chunk_id": 1108, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1108, "text": "generatetransformers.GenerationMixin.generatehttps://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/utils.py#L2130[{\"name\": \"inputs\", \"val\": \": torch.Tensor | None = None\"}, {\"name\": \"generation_config\", \"val\": \": transformers.generation.configuration_utils.GenerationConfig | None = None\"}, {\"name\": \"logits_processor\", \"val\": \": transformers.generation.logits_process.LogitsProcessorList | None = None\"}, {\"name\": \"stopping_criteria\", \"val\": \": transformers.generation.stopping_criteria.StoppingCriteriaList | None = None\"}, {\"name\": \"prefix_allowed_tokens_fn\", \"val\": \": collections.abc.Callable[[int, torch.Tensor], list[int]] | None = None\"}, {\"name\": \"synced_gpus\", \"val\": \": bool | None = None\"}, {\"name\": \"assistant_model\", \"val\": \": typing.Optional[ForwardRef('PreTrainedModel')] = None\"}, {\"name\": \"streamer\", \"val\": \": typing.Optional[ForwardRef('BaseStreamer')] = None\"}, {\"name\": \"negative_prompt_ids\", \"val\": \": torch.Tensor | None = None\"}, {\"name\": \"negative_prompt_attention_mask\", \"val\": \": torch.Tensor | None = None\"}, {\"name\": \"custom_generate\", \"val\": \": str | collections.abc.Callable | None = None\"}, {\"name\": \"**kwargs\", \"val\": \"\"}]- **inputs** (`torch.Tensor` of varying shape depending on the modality, *optional*) --\n The sequence used as a prompt for the generation or as model inputs to the encoder. If `None` the\n method initializes it with `bos_token_id` and a batch size of 1. For decoder-only models `inputs`\n should be in the format of `input_ids`. For encoder-decoder models *inputs* can represent any of\n `input_ids`, `input_values`, `input_features`, or `pixel_values`.\n- **generation_config** ([GenerationConfig](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig), *optional*) --\n The generation configuration to be used as base parametrization for the generation call. `**kwargs`\n passed to generate matching the attributes of `generation_config` will override them. If\n `generation_config` is not provided, the default will be used, which has the following loading\n priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model\n configuration. Please note that unspecified parameters will inherit [GenerationConfig](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig)'s\n default values, whose documentation should be checked to parameterize generation.\n- **logits_processor** (`LogitsProcessorList`, *optional*) --\n Custom logits processors that complement the default logits processors built from arguments and\n generation config. If a logit processor is passed that is already created with the arguments or a\n generation config an error is thrown. This feature is intended for advanced users.\n- **stopping_criteria** (`StoppingCriteriaList`, *optional*) --\n Custom stopping criteria that complements the default stopping criteria built from arguments and a\n generation config. If a stopping criteria is passed that is already created with the arguments or a\n generation config an error is thrown. If your stopping criteria depends on the `scores` input, make\n sure you pass `return_dict_in_generate=True, output_scores=True` to `generate`. This feature is\n intended for advanced users.\n- **prefix_allowed_tokens_fn** (`Callable[[int, torch.Tensor], list[int]]`, *optional*) --\n If provided, this function constraints the beam search to allowed tokens only at each step. If not\n provided no constraint is applied. This function takes 2 arguments: the batch ID `batch_id` and\n `input_ids`. It has to return a list with the allowed tokens for the next generation step conditioned\n on the batch ID `batch_id` and the previously generated tokens `inputs_ids`. This argument is useful\n for constrained generation conditioned on the prefix, as described in [Autoregressive Entity\n Retrieval](https://huggingface.co/papers/2010.00904).\n- **synced_gpus** (`bool`, *optional*) --\n Whether to continue running the while loop until max_length. Unless overridden, this flag will be set\n to `True` if using `FullyShardedDataParallel` or DeepSpeed ZeRO Stage 3 with multiple GPUs to avoid\n deadlocking if one GPU finishes generating before other GPUs. Otherwise, defaults to `False`.\n- **assistant_model** (`PreTrainedModel`, *optional*) --\n An assistant model that can be used to accelerate generation. The assistant model must have the exact\n same tokenizer. The acceleration is achieved when forecasting candidate tokens with the assistant model\n is much faster than running generation with the model you're calling generate from. As such, the\n assistant model should be much smaller.\n- **streamer** (`BaseStreamer`, *optional*) --\n Streamer object that will be used to stream the generated sequences. Generated tokens are passed\n through `streamer.put(token_ids)` and the streamer is responsible for any further processing.\n- **negative_prompt_ids** (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) --\n The negative prompt needed for some processors such as CFG. The batch size must match the input batch\n size. This is an experimental feature, subject to breaking API changes in future versions.\n- **negative_prompt_attention_mask** (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) --\n Attention_mask for `negative_prompt_ids`.\n- **custom_generate** (`str` or `Callable`, *optional*) --\n One of the following:\n - `str` (Hugging Face Hub repository name): runs the custom `generate` function defined at\n `custom_generate/generate.py` in that repository instead of the standard `generate` method. The\n repository fully replaces the generation logic, and the return type may differ.\n - `str` (local repository path): same as above but from a local path, `trust_remote_code` not required.\n - `Callable`: `generate` will perform the usual input preparation steps, then call the provided callable to\n run the decoding loop.\n For more information, see [the docs](../../generation_strategies#custom-generation-methods).\n- **kwargs** (`dict[str, Any]`, *optional*) --\n Ad hoc parametrization of `generation_config` and/or additional model-specific kwargs that will be\n forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder\n specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.0[ModelOutput](/docs/transformers/v5.6.2/en/main_classes/output#transformers.utils.ModelOutput) or `torch.LongTensor`A [ModelOutput](/docs/transformers/v5.6.2/en/main_classes/output#transformers.utils.ModelOutput) (if `return_dict_in_generate=True`\nor when `config.return_dict_in_generate=True`) or a `torch.LongTensor`.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.GenerationMixin[[transformers.GenerationMixin]]", "char_start": 14591, "char_end": 21343, "token_estimate": 1688, "prev_chunk_id": 1107, "next_chunk_id": 1109, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1109, "text": "If the model is *not* an encoder-decoder model (`model.config.is_encoder_decoder=False`), the possible\n[ModelOutput](/docs/transformers/v5.6.2/en/main_classes/output#transformers.utils.ModelOutput) types are:\n\n- [GenerateDecoderOnlyOutput](/docs/transformers/v5.6.2/en/internal/generation_utils#transformers.generation.GenerateDecoderOnlyOutput),\n- [GenerateBeamDecoderOnlyOutput](/docs/transformers/v5.6.2/en/internal/generation_utils#transformers.generation.GenerateBeamDecoderOnlyOutput)\n\nIf the model is an encoder-decoder model (`model.config.is_encoder_decoder=True`), the possible\n[ModelOutput](/docs/transformers/v5.6.2/en/main_classes/output#transformers.utils.ModelOutput) types are:\n\n- [GenerateEncoderDecoderOutput](/docs/transformers/v5.6.2/en/internal/generation_utils#transformers.generation.GenerateEncoderDecoderOutput),\n- [GenerateBeamEncoderDecoderOutput](/docs/transformers/v5.6.2/en/internal/generation_utils#transformers.generation.GenerateBeamEncoderDecoderOutput)", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.GenerationMixin[[transformers.GenerationMixin]]", "char_start": 21345, "char_end": 22332, "token_estimate": 246, "prev_chunk_id": 1108, "next_chunk_id": 1110, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1110, "text": "Generates sequences of token ids for models with a language modeling head.\n\nMost generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the\nmodel's default generation configuration. You can override any `generation_config` by passing the corresponding\nparameters to generate(), e.g. `.generate(inputs, num_beams=4, do_sample=True)`.\n\nFor an overview of generation strategies and code examples, check out the [following\nguide](../generation_strategies).\n\n**Parameters:**\n\ninputs (`torch.Tensor` of varying shape depending on the modality, *optional*) : The sequence used as a prompt for the generation or as model inputs to the encoder. If `None` the method initializes it with `bos_token_id` and a batch size of 1. For decoder-only models `inputs` should be in the format of `input_ids`. For encoder-decoder models *inputs* can represent any of `input_ids`, `input_values`, `input_features`, or `pixel_values`.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.GenerationMixin[[transformers.GenerationMixin]]", "char_start": 22334, "char_end": 23291, "token_estimate": 239, "prev_chunk_id": 1109, "next_chunk_id": 1111, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1111, "text": "generation_config ([GenerationConfig](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig), *optional*) : The generation configuration to be used as base parametrization for the generation call. `**kwargs` passed to generate matching the attributes of `generation_config` will override them. If `generation_config` is not provided, the default will be used, which has the following loading priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model configuration. Please note that unspecified parameters will inherit [GenerationConfig](/docs/transformers/v5.6.2/en/main_classes/text_generation#transformers.GenerationConfig)'s default values, whose documentation should be checked to parameterize generation.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.GenerationMixin[[transformers.GenerationMixin]]", "char_start": 23293, "char_end": 24069, "token_estimate": 194, "prev_chunk_id": 1110, "next_chunk_id": 1112, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1112, "text": "logits_processor (`LogitsProcessorList`, *optional*) : Custom logits processors that complement the default logits processors built from arguments and generation config. If a logit processor is passed that is already created with the arguments or a generation config an error is thrown. This feature is intended for advanced users.\n\nstopping_criteria (`StoppingCriteriaList`, *optional*) : Custom stopping criteria that complements the default stopping criteria built from arguments and a generation config. If a stopping criteria is passed that is already created with the arguments or a generation config an error is thrown. If your stopping criteria depends on the `scores` input, make sure you pass `return_dict_in_generate=True, output_scores=True` to `generate`. This feature is intended for advanced users.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.GenerationMixin[[transformers.GenerationMixin]]", "char_start": 24071, "char_end": 24884, "token_estimate": 203, "prev_chunk_id": 1111, "next_chunk_id": 1113, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1113, "text": "prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], list[int]]`, *optional*) : If provided, this function constraints the beam search to allowed tokens only at each step. If not provided no constraint is applied. This function takes 2 arguments: the batch ID `batch_id` and `input_ids`. It has to return a list with the allowed tokens for the next generation step conditioned on the batch ID `batch_id` and the previously generated tokens `inputs_ids`. This argument is useful for constrained generation conditioned on the prefix, as described in [Autoregressive Entity Retrieval](https://huggingface.co/papers/2010.00904).\n\nsynced_gpus (`bool`, *optional*) : Whether to continue running the while loop until max_length. Unless overridden, this flag will be set to `True` if using `FullyShardedDataParallel` or DeepSpeed ZeRO Stage 3 with multiple GPUs to avoid deadlocking if one GPU finishes generating before other GPUs. Otherwise, defaults to `False`.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.GenerationMixin[[transformers.GenerationMixin]]", "char_start": 24886, "char_end": 25846, "token_estimate": 240, "prev_chunk_id": 1112, "next_chunk_id": 1114, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1114, "text": "assistant_model (`PreTrainedModel`, *optional*) : An assistant model that can be used to accelerate generation. The assistant model must have the exact same tokenizer. The acceleration is achieved when forecasting candidate tokens with the assistant model is much faster than running generation with the model you're calling generate from. As such, the assistant model should be much smaller.\n\nstreamer (`BaseStreamer`, *optional*) : Streamer object that will be used to stream the generated sequences. Generated tokens are passed through `streamer.put(token_ids)` and the streamer is responsible for any further processing.\n\nnegative_prompt_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) : The negative prompt needed for some processors such as CFG. The batch size must match the input batch size. This is an experimental feature, subject to breaking API changes in future versions.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.GenerationMixin[[transformers.GenerationMixin]]", "char_start": 25848, "char_end": 26762, "token_estimate": 228, "prev_chunk_id": 1113, "next_chunk_id": 1115, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1115, "text": "negative_prompt_attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) : Attention_mask for `negative_prompt_ids`.\n\ncustom_generate (`str` or `Callable`, *optional*) : One of the following: - `str` (Hugging Face Hub repository name): runs the custom `generate` function defined at `custom_generate/generate.py` in that repository instead of the standard `generate` method. The repository fully replaces the generation logic, and the return type may differ. - `str` (local repository path): same as above but from a local path, `trust_remote_code` not required. - `Callable`: `generate` will perform the usual input preparation steps, then call the provided callable to run the decoding loop. For more information, see [the docs](../../generation_strategies#custom-generation-methods).", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.GenerationMixin[[transformers.GenerationMixin]]", "char_start": 26764, "char_end": 27582, "token_estimate": 204, "prev_chunk_id": 1114, "next_chunk_id": 1116, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1116, "text": "kwargs (`dict[str, Any]`, *optional*) : Ad hoc parametrization of `generation_config` and/or additional model-specific kwargs that will be forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.\n\n**Returns:**\n\n`[ModelOutput](/docs/transformers/v5.6.2/en/main_classes/output#transformers.utils.ModelOutput) or `torch.LongTensor``\n\nA [ModelOutput](/docs/transformers/v5.6.2/en/main_classes/output#transformers.utils.ModelOutput) (if `return_dict_in_generate=True`\nor when `config.return_dict_in_generate=True`) or a `torch.LongTensor`.\n\nIf the model is *not* an encoder-decoder model (`model.config.is_encoder_decoder=False`), the possible\n[ModelOutput](/docs/transformers/v5.6.2/en/main_classes/output#transformers.utils.ModelOutput) types are:", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.GenerationMixin[[transformers.GenerationMixin]]", "char_start": 27584, "char_end": 28474, "token_estimate": 222, "prev_chunk_id": 1115, "next_chunk_id": 1117, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1117, "text": "- [GenerateDecoderOnlyOutput](/docs/transformers/v5.6.2/en/internal/generation_utils#transformers.generation.GenerateDecoderOnlyOutput),\n- [GenerateBeamDecoderOnlyOutput](/docs/transformers/v5.6.2/en/internal/generation_utils#transformers.generation.GenerateBeamDecoderOnlyOutput)\n\nIf the model is an encoder-decoder model (`model.config.is_encoder_decoder=True`), the possible\n[ModelOutput](/docs/transformers/v5.6.2/en/main_classes/output#transformers.utils.ModelOutput) types are:\n\n- [GenerateEncoderDecoderOutput](/docs/transformers/v5.6.2/en/internal/generation_utils#transformers.generation.GenerateEncoderDecoderOutput),\n- [GenerateBeamEncoderDecoderOutput](/docs/transformers/v5.6.2/en/internal/generation_utils#transformers.generation.GenerateBeamEncoderDecoderOutput)", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.GenerationMixin[[transformers.GenerationMixin]]", "char_start": 21555, "char_end": 22332, "token_estimate": 194, "prev_chunk_id": 1116, "next_chunk_id": 1118, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1118, "text": "#### compute_transition_scores[[transformers.GenerationMixin.compute_transition_scores]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/utils.py#L1335)\n\nComputes the transition scores of sequences given the generation scores (and beam indices, if beam search was\nused). This is a convenient method to quickly obtain the scores of the selected tokens at generation time.\n\nExamples:", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "compute_transition_scores[[transformers.GenerationMixin.compute_transition_scores]]", "char_start": 29254, "char_end": 29681, "token_estimate": 106, "prev_chunk_id": 1117, "next_chunk_id": 1119, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1119, "text": "```python\n>>> from transformers import GPT2Tokenizer, AutoModelForCausalLM\n>>> import numpy as np\n\n>>> tokenizer = GPT2Tokenizer.from_pretrained(\"gpt2\")\n>>> model = AutoModelForCausalLM.from_pretrained(\"openai-community/gpt2\")\n>>> tokenizer.pad_token_id = tokenizer.eos_token_id\n>>> inputs = tokenizer([\"Today is\"], return_tensors=\"pt\")\n\n>>> # Example 1: Print the scores for each token generated with Greedy Search\n>>> outputs = model.generate(**inputs, max_new_tokens=5, return_dict_in_generate=True, output_scores=True)\n>>> transition_scores = model.compute_transition_scores(\n... outputs.sequences, outputs.scores, normalize_logits=True\n... )\n>>> # input_length is the length of the input prompt for decoder-only models, like the GPT family, and 1 for\n>>> # encoder-decoder models, like BART or T5.\n>>> input_length = 1 if model.config.is_encoder_decoder else inputs.input_ids.shape[1]\n>>> generated_tokens = outputs.sequences[:, input_length:]\n>>> for tok, score in zip(generated_tokens[0], transition_scores[0]):\n... # | token | token string | log probability | probability\n... print(f\"| {tok:5d} | {tokenizer.decode(tok):8s} | {score.numpy():.3f} | {np.exp(score.numpy()):.2%}\")\n| 262 | the | -1.414 | 24.33%\n| 1110 | day | -2.609 | 7.36%\n| 618 | when | -2.010 | 13.40%\n| 356 | we | -1.859 | 15.58%\n| 460 | can | -2.508 | 8.14%\n\n>>> # Example 2: Reconstruct the sequence scores from Beam Search\n>>> outputs = model.generate(\n... **inputs,\n... max_new_tokens=5,\n... num_beams=4,\n... num_return_sequences=4,\n... return_dict_in_generate=True,\n... output_scores=True,\n... )\n>>> transition_scores = model.compute_transition_scores(\n... outputs.sequences, outputs.scores, outputs.beam_indices, normalize_logits=False\n... )\n>>> # If you sum the generated tokens' scores and apply the length penalty, you'll get the sequence scores.\n>>> # Tip 1: recomputing the scores is only guaranteed to match with `normalize_logits=False`. Depending on the\n>>> # use case, you might want to recompute it with `normalize_logits=True`.\n>>> # Tip 2: the output length does NOT include the input length\n>>> output_length = np.sum(transition_scores.numpy() >> length_penalty = model.generation_config.length_penalty\n>>> reconstructed_scores = transition_scores.sum(axis=1) / (output_length**length_penalty)\n>>> print(np.allclose(outputs.sequences_scores, reconstructed_scores))\nTrue\n```", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "compute_transition_scores[[transformers.GenerationMixin.compute_transition_scores]]", "char_start": 29683, "char_end": 32125, "token_estimate": 610, "prev_chunk_id": 1118, "next_chunk_id": 1120, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1120, "text": "**Parameters:**\n\nsequences (`torch.LongTensor`) : The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter if all batches finished early due to the `eos_token_id`.\n\nscores (`tuple(torch.FloatTensor)`) : Transition scores for each vocabulary token at each generation step. Beam transition scores consisting of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token), with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.\n\nbeam_indices (`torch.LongTensor`, *optional*) : Beam indices of generated token id at each generation step. `torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`. Only required if a `num_beams>1` at generate-time.\n\nnormalize_logits (`bool`, *optional*, defaults to `False`) : Whether to normalize the logits (which, for legacy reasons, may be unnormalized).", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "compute_transition_scores[[transformers.GenerationMixin.compute_transition_scores]]", "char_start": 32127, "char_end": 33148, "token_estimate": 255, "prev_chunk_id": 1119, "next_chunk_id": 1121, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1121, "text": "**Returns:**\n\n``torch.Tensor``\n\nA `torch.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)` containing\nthe transition scores (logits)", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "compute_transition_scores[[transformers.GenerationMixin.compute_transition_scores]]", "char_start": 33150, "char_end": 33302, "token_estimate": 38, "prev_chunk_id": 1120, "next_chunk_id": 1122, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1122, "text": "## ContinuousMixin[[transformers.ContinuousMixin]]", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "ContinuousMixin[[transformers.ContinuousMixin]]", "char_start": 33304, "char_end": 33354, "token_estimate": 12, "prev_chunk_id": 1121, "next_chunk_id": 1123, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1123, "text": "#### transformers.ContinuousMixin[[transformers.ContinuousMixin]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/continuous_api.py#L1147)\n\nMixin class for models to add continuous batching capabilities. Continuous batching has three entry points:\n- `init_continuous_batching`, which is the actual entry point for continuous batching\n- `continuous_batching_context_manager`, which itself is a wrapper around `init_continuous_batching`\n- `generate_batch`, which is really a wrapper around `continuous_batching_context_manager`\n\nThey are defined in this order. Any change made to any of those three entry points should be reflected in the other\ntwo.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.ContinuousMixin[[transformers.ContinuousMixin]]", "char_start": 33356, "char_end": 34069, "token_estimate": 178, "prev_chunk_id": 1122, "next_chunk_id": 1124, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1124, "text": "continuous_batching_context_managertransformers.ContinuousMixin.continuous_batching_context_managerhttps://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/continuous_api.py#L1219[{\"name\": \"generation_config\", \"val\": \": transformers.generation.configuration_utils.GenerationConfig | None = None\"}, {\"name\": \"block\", \"val\": \": bool = True\"}, {\"name\": \"timeout\", \"val\": \": float | None = None\"}, {\"name\": \"continuous_batching_config\", \"val\": \": transformers.generation.configuration_utils.ContinuousBatchingConfig | None = None\"}, {\"name\": \"persistent_manager\", \"val\": \": bool = False\"}, {\"name\": \"warmup_requests\", \"val\": \": int | None = 0\"}, {\"name\": \"**deprecated_kwargs\", \"val\": \"\"}]\nA context manager to safely use the continuous batching manager. Arguments are similar to the ones of\n`init_continuous_batching`, except for:\n- block: whether to block the thread when stopping the manager. Default is True.\n- timeout: maximum time to wait for the thread to stop. Default is None (no timeout).\n- warmup_query_tokens: the number of expected requests for which to warmup. 0 is auto, None is no warmup.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.ContinuousMixin[[transformers.ContinuousMixin]]", "char_start": 34071, "char_end": 35218, "token_estimate": 286, "prev_chunk_id": 1123, "next_chunk_id": 1125, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1125, "text": "#### destroy_cached_continuous_batching_manager[[transformers.ContinuousMixin.destroy_cached_continuous_batching_manager]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/continuous_api.py#L1212)\n\nDestroy the cached continuous batching manager and free GPU resources.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "destroy_cached_continuous_batching_manager[[transformers.ContinuousMixin.destroy_cached_continuous_batching_manager]]", "char_start": 35219, "char_end": 35552, "token_estimate": 83, "prev_chunk_id": 1124, "next_chunk_id": 1126, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1126, "text": "#### generate_batch[[transformers.ContinuousMixin.generate_batch]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/continuous_api.py#L1257)\n\nGenerate sequences for a batch of prompts using continuous batching.\n\n**Parameters:**\n\ninputs : List of input token sequences (prompts)\n\ngeneration_config : Optional generation configuration\n\ncontinuous_batching_config : Optional continuous batching configuration\n\nrecord_timestamps : If set to true, the requests will have a timestamp for each token generated\n\nprogress_bar : If set to true, a progress bar will be displayed\n\npersistent_manager : whether to persist the manager after the generation is finished. Default is False.\n\nwarmup : whether to pre-capture CUDA graphs before processing requests. Default is True.\n\n- ****kwargs** : Additional generation parameters. Only max_new_tokens is used, but other deprecated arguments are extracted and passed to the continuous_batching_config object.\n\n**Returns:**", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "generate_batch[[transformers.ContinuousMixin.generate_batch]]", "char_start": 35553, "char_end": 36573, "token_estimate": 255, "prev_chunk_id": 1125, "next_chunk_id": 1127, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1127, "text": "``dict[str, GenerationOutput]``\n\na dictionary of request ids to GenerationOutput objects", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "generate_batch[[transformers.ContinuousMixin.generate_batch]]", "char_start": 36575, "char_end": 36663, "token_estimate": 22, "prev_chunk_id": 1126, "next_chunk_id": 1128, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1128, "text": "#### init_continuous_batching[[transformers.ContinuousMixin.init_continuous_batching]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/continuous_api.py#L1159)\n\nInitialize a manager for continuous batching inference.\n\n**Parameters:**\n\ngeneration_config : An optional generation configuration, which may contain a CompileConfig object\n\ncontinuous_batching_config : An optional continuous batching configuration\n\n- ****deprecated_kwargs** : Deprecated arguments that are now passed in the continuous_batching_config. Those are: max_queue_size, q_padding_interval_size, kv_padding_interval_size, allow_block_sharing, use_async_batching, max_cached_graphs\n\n**Returns:**\n\n``ContinuousBatchingManager``\n\nThe manager instance to add requests and retrieve results.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "init_continuous_batching[[transformers.ContinuousMixin.init_continuous_batching]]", "char_start": 36664, "char_end": 37486, "token_estimate": 205, "prev_chunk_id": 1127, "next_chunk_id": 1129, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1129, "text": "## ContinuousBatchingManager[[transformers.ContinuousBatchingManager]]", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "ContinuousBatchingManager[[transformers.ContinuousBatchingManager]]", "char_start": 37488, "char_end": 37558, "token_estimate": 17, "prev_chunk_id": 1128, "next_chunk_id": 1130, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1130, "text": "#### transformers.ContinuousBatchingManager[[transformers.ContinuousBatchingManager]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/continuous_api.py#L731)\n\nManager for handling continuous batching of generation requests. It provides a user interface for submitting\ngeneration requests, retrieving results, and managing the background generation thread. This class should not be\ncreated directly, but through one of the following entry points (all methods of the `ContinuousMixin` mixin):\n- `init_continuous_batching`\n- `continuous_batching_context_manager`\n- `generate_batch`", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.ContinuousBatchingManager[[transformers.ContinuousBatchingManager]]", "char_start": 37560, "char_end": 38204, "token_estimate": 161, "prev_chunk_id": 1129, "next_chunk_id": 1131, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1131, "text": "add_requesttransformers.ContinuousBatchingManager.add_requesthttps://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/continuous_api.py#L878[{\"name\": \"input_ids\", \"val\": \": list\"}, {\"name\": \"request_id\", \"val\": \": str | None = None\"}, {\"name\": \"max_new_tokens\", \"val\": \": int | None = None\"}, {\"name\": \"streaming\", \"val\": \": bool = False\"}, {\"name\": \"record_timestamps\", \"val\": \": bool = False\"}, {\"name\": \"eos_token_id\", \"val\": \": int | list[int] | None = None\"}, {\"name\": \"**logit_processor_kwargs\", \"val\": \": typing.Any\"}]- **input_ids** -- Input token IDs to use as prompt\n- **request_id** -- Optional custom request ID (auto-generated if None)\n- **max_new_tokens** -- Maximum number of new tokens to generate\n- **streaming** -- Whether to stream tokens as they're generated\n- **record_timestamps** -- Whether to record timestamps for each generated token\n- **eos_token_id** -- End-of-sequence token ID(s)\n- **logit_processor_kwargs** -- Keyword arguments for the logits processor.0strThe request ID\nAdd a new generation request to the queue.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.ContinuousBatchingManager[[transformers.ContinuousBatchingManager]]", "char_start": 38206, "char_end": 39299, "token_estimate": 273, "prev_chunk_id": 1130, "next_chunk_id": 1132, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1132, "text": "**Parameters:**\n\ninput_ids : Input token IDs to use as prompt\n\nrequest_id : Optional custom request ID (auto-generated if None)\n\nmax_new_tokens : Maximum number of new tokens to generate\n\nstreaming : Whether to stream tokens as they're generated\n\nrecord_timestamps : Whether to record timestamps for each generated token\n\neos_token_id : End-of-sequence token ID(s)\n\nlogit_processor_kwargs : Keyword arguments for the logits processor.\n\n**Returns:**\n\n`str`\n\nThe request ID", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.ContinuousBatchingManager[[transformers.ContinuousBatchingManager]]", "char_start": 39301, "char_end": 39772, "token_estimate": 117, "prev_chunk_id": 1131, "next_chunk_id": 1133, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1133, "text": "#### cancel_request[[transformers.ContinuousBatchingManager.cancel_request]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/continuous_api.py#L960)\n\nCancel a request by its ID.\n\n**Parameters:**\n\nrequest_id : The ID of the request to cancel", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "cancel_request[[transformers.ContinuousBatchingManager.cancel_request]]", "char_start": 39773, "char_end": 40079, "token_estimate": 76, "prev_chunk_id": 1132, "next_chunk_id": 1134, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1134, "text": "#### get_result[[transformers.ContinuousBatchingManager.get_result]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/continuous_api.py#L970)\n\nRetrieve one result from the output queue.\n\n**Parameters:**\n\nrequest_id : If set, only return results matching this ID (others are requeued).\n\ntimeout : Maximum time to wait for a result.\n\n**Returns:**\n\n`Optional[GenerationOutput]`\n\nThe result data or None if timeout.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "get_result[[transformers.ContinuousBatchingManager.get_result]]", "char_start": 40080, "char_end": 40556, "token_estimate": 119, "prev_chunk_id": 1133, "next_chunk_id": 1135, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1135, "text": "#### is_running[[transformers.ContinuousBatchingManager.is_running]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/continuous_api.py#L810)\n\nCheck if the background generation thread is running.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "is_running[[transformers.ContinuousBatchingManager.is_running]]", "char_start": 40557, "char_end": 40818, "token_estimate": 65, "prev_chunk_id": 1134, "next_chunk_id": 1136, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1136, "text": "#### join[[transformers.ContinuousBatchingManager.join]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/continuous_api.py#L863)\n\nWait for the background thread to finish.\n\n**Parameters:**\n\ntimeout : Maximum time to wait for the thread to stop", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "join[[transformers.ContinuousBatchingManager.join]]", "char_start": 40819, "char_end": 41128, "token_estimate": 77, "prev_chunk_id": 1135, "next_chunk_id": 1137, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1137, "text": "#### register_result_handler[[transformers.ContinuousBatchingManager.register_result_handler]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/continuous_api.py#L1011)\n\nRegister a callback for result delivery (streaming or non-streaming).\n\nThe callback is invoked on the event loop via `call_soon_threadsafe`\neach time a result is produced for this request. For streaming requests,\nthis happens on every token; for non-streaming, only on completion.\n\nThe handler is automatically cleaned up when the request finishes.\n\n**Parameters:**\n\nrequest_id (*str*) : The request ID to receive outputs for.\n\ncallback (*callable*) : Called with a `GenerationOutput` for each result.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "register_result_handler[[transformers.ContinuousBatchingManager.register_result_handler]]", "char_start": 41129, "char_end": 41865, "token_estimate": 184, "prev_chunk_id": 1136, "next_chunk_id": 1138, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1138, "text": "#### request_id_iter[[transformers.ContinuousBatchingManager.request_id_iter]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/continuous_api.py#L998)\n\nIterate over results matching a specific request id (blocking).\n\nUses the shared output queue with requeue. For high-concurrency serving,\nuse `register_result_handler` instead.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "request_id_iter[[transformers.ContinuousBatchingManager.request_id_iter]]", "char_start": 41866, "char_end": 42260, "token_estimate": 98, "prev_chunk_id": 1137, "next_chunk_id": 1139, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1139, "text": "#### start[[transformers.ContinuousBatchingManager.start]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/continuous_api.py#L800)\n\nStart the background generation thread.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "start[[transformers.ContinuousBatchingManager.start]]", "char_start": 42261, "char_end": 42498, "token_estimate": 59, "prev_chunk_id": 1138, "next_chunk_id": 1140, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1140, "text": "#### stop[[transformers.ContinuousBatchingManager.stop]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/continuous_api.py#L823)\n\nSignal the background thread to stop.\n\n**Parameters:**\n\nblock : Whether to wait for the thread to stop\n\ntimeout : Maximum time to wait for the thread to stop\n\nkeep_for_next_session : Whether to cache this on the model for future use", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "stop[[transformers.ContinuousBatchingManager.stop]]", "char_start": 42499, "char_end": 42927, "token_estimate": 107, "prev_chunk_id": 1139, "next_chunk_id": 1141, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1141, "text": "#### warmup[[transformers.ContinuousBatchingManager.warmup]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/continuous_api.py#L814)\n\nPre-capture CUDA graphs for varlen and decode paths by running dummy batches. Initializes the batch\nprocessor if not already done.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "warmup[[transformers.ContinuousBatchingManager.warmup]]", "char_start": 42928, "char_end": 43258, "token_estimate": 82, "prev_chunk_id": 1140, "next_chunk_id": 1142, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1142, "text": "## Scheduler[[transformers.generation.Scheduler]]", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "Scheduler[[transformers.generation.Scheduler]]", "char_start": 43260, "char_end": 43309, "token_estimate": 12, "prev_chunk_id": 1141, "next_chunk_id": 1143, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1143, "text": "#### transformers.generation.Scheduler[[transformers.generation.Scheduler]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/scheduler.py#L23)\n\nAbstract base class for scheduling requests in the continuous batch processor. Schedulers manage the lifecycle of\nrequests from when they are added to the waiting queue to when they are scheduled for processing. Different\nschedulers implement different strategies for prioritizing and batching requests.\n\nadd_waiting_requesttransformers.generation.Scheduler.add_waiting_requesthttps://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/scheduler.py#L48[{\"name\": \"state\", \"val\": \": RequestState\"}]\nAdds a request to the waiting list.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.generation.Scheduler[[transformers.generation.Scheduler]]", "char_start": 43311, "char_end": 44097, "token_estimate": 196, "prev_chunk_id": 1142, "next_chunk_id": 1144, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1144, "text": "#### clear_cancelled_requests[[transformers.generation.Scheduler.clear_cancelled_requests]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/scheduler.py#L91)\n\nRemove all cancelled requests from active and waiting queues.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "clear_cancelled_requests[[transformers.generation.Scheduler.clear_cancelled_requests]]", "char_start": 44098, "char_end": 44384, "token_estimate": 71, "prev_chunk_id": 1143, "next_chunk_id": 1145, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1145, "text": "#### finish_request[[transformers.generation.Scheduler.finish_request]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/scheduler.py#L70)\n\nCompletes processing of a request and frees its allocated cache blocks. This method is called\nwhen a request has finished generation or encountered an error.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "finish_request[[transformers.generation.Scheduler.finish_request]]", "char_start": 44385, "char_end": 44747, "token_estimate": 90, "prev_chunk_id": 1144, "next_chunk_id": 1146, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1146, "text": "#### get_active_request_static_outputs[[transformers.generation.Scheduler.get_active_request_static_outputs]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/scheduler.py#L78)\n\nGets generated tokens for an active request.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "get_active_request_static_outputs[[transformers.generation.Scheduler.get_active_request_static_outputs]]", "char_start": 44748, "char_end": 45035, "token_estimate": 71, "prev_chunk_id": 1145, "next_chunk_id": 1147, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1147, "text": "#### has_pending_requests[[transformers.generation.Scheduler.has_pending_requests]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/scheduler.py#L65)\n\nChecks if there are requests ready to be processed.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "has_pending_requests[[transformers.generation.Scheduler.has_pending_requests]]", "char_start": 45036, "char_end": 45304, "token_estimate": 67, "prev_chunk_id": 1146, "next_chunk_id": 1148, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1148, "text": "#### request_is_cancelled[[transformers.generation.Scheduler.request_is_cancelled]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/scheduler.py#L103)\n\nChecks if a request has been cancelled or removed.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "request_is_cancelled[[transformers.generation.Scheduler.request_is_cancelled]]", "char_start": 45305, "char_end": 45573, "token_estimate": 67, "prev_chunk_id": 1147, "next_chunk_id": 1149, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1149, "text": "#### reset[[transformers.generation.Scheduler.reset]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/scheduler.py#L39)\n\nReset scheduler state for a new generation loop.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "reset[[transformers.generation.Scheduler.reset]]", "char_start": 45574, "char_end": 45809, "token_estimate": 58, "prev_chunk_id": 1148, "next_chunk_id": 1150, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1150, "text": "#### schedule_batch[[transformers.generation.Scheduler.schedule_batch]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/scheduler.py#L54)\n\nSchedules requests for the next batch based on available token and cache budgets. This method selects which\nrequests should be processed in the current batch, considering the budgets and the scheduler's prioritization\nrules. The token_budget is the maximum number of tokens that can be processed in a batch, and the cache_budget\nis the maximum number of KV cache entries that can be read in a batch.\nReturns the list of scheduled requests in their \"FutureRequestState\" form, a boolean indicating if the decode\nfast path can be used, the total number of query tokens and the maximum number of kv tokens read.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "schedule_batch[[transformers.generation.Scheduler.schedule_batch]]", "char_start": 45810, "char_end": 46622, "token_estimate": 203, "prev_chunk_id": 1149, "next_chunk_id": 1151, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1151, "text": "#### set_request_cancellation[[transformers.generation.Scheduler.set_request_cancellation]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/scheduler.py#L85)\n\nMarks a request for cancellation.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "set_request_cancellation[[transformers.generation.Scheduler.set_request_cancellation]]", "char_start": 46623, "char_end": 46881, "token_estimate": 64, "prev_chunk_id": 1150, "next_chunk_id": 1152, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1152, "text": "## FIFOScheduler[[transformers.generation.FIFOScheduler]]", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "FIFOScheduler[[transformers.generation.FIFOScheduler]]", "char_start": 46883, "char_end": 46940, "token_estimate": 14, "prev_chunk_id": 1151, "next_chunk_id": 1153, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1153, "text": "#### transformers.generation.FIFOScheduler[[transformers.generation.FIFOScheduler]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/scheduler.py#L292)\n\nThis scheduler processes requests in the order they arrive, meaning decoding requests has priority over\nprefilling requests. Additionally, it includes a safety margin mechanism to prevent cache exhaustion. By default,\nwhen 80% of the cache is full, new requests will not be scheduled to prioritize decoding active requests.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.generation.FIFOScheduler[[transformers.generation.FIFOScheduler]]", "char_start": 46942, "char_end": 47483, "token_estimate": 135, "prev_chunk_id": 1152, "next_chunk_id": 1154, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1154, "text": "## PrefillFirstScheduler[[transformers.generation.PrefillFirstScheduler]]", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "PrefillFirstScheduler[[transformers.generation.PrefillFirstScheduler]]", "char_start": 47485, "char_end": 47558, "token_estimate": 18, "prev_chunk_id": 1153, "next_chunk_id": 1155, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1155, "text": "#### transformers.generation.PrefillFirstScheduler[[transformers.generation.PrefillFirstScheduler]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/generation/continuous_batching/scheduler.py#L348)\n\nScheduler that prioritizes split prefill requests over decoding requests. This scheduler ensures that split\nprefill requests (which are continuations of partially processed prompts) are completed before processing new\ndecoding requests.", "source_file": "transformers/main_classes/text_generation.md", "section_heading": "transformers.generation.PrefillFirstScheduler[[transformers.generation.PrefillFirstScheduler]]", "char_start": 47560, "char_end": 48030, "token_estimate": 117, "prev_chunk_id": 1154, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/main_classes/text_generation", "doc_title": "Generation" }, { "chunk_id": 1156, "text": "# Model outputs\n\nAll models have outputs that are instances of subclasses of [ModelOutput](/docs/transformers/v5.6.2/en/main_classes/output#transformers.utils.ModelOutput). Those are\ndata structures containing all the information returned by the model, but that can also be used as tuples or\ndictionaries.\n\nLet's see how this looks in an example:\n\n```python\nfrom transformers import BertTokenizer, BertForSequenceClassification\nimport torch\n\ntokenizer = BertTokenizer.from_pretrained(\"google-bert/bert-base-uncased\")\nmodel = BertForSequenceClassification.from_pretrained(\"google-bert/bert-base-uncased\")\n\ninputs = tokenizer(\"Hello, my dog is cute\", return_tensors=\"pt\")\nlabels = torch.tensor([1]).unsqueeze(0) # Batch size 1\noutputs = model(**inputs, labels=labels)\n```", "source_file": "transformers/main_classes/output.md", "section_heading": "Model outputs", "char_start": 0, "char_end": 770, "token_estimate": 192, "prev_chunk_id": null, "next_chunk_id": 1157, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1157, "text": "The `outputs` object is a [SequenceClassifierOutput](/docs/transformers/v5.6.2/en/main_classes/output#transformers.modeling_outputs.SequenceClassifierOutput), as we can see in the\ndocumentation of that class below, it means it has an optional `loss`, a `logits`, an optional `hidden_states` and\nan optional `attentions` attribute. Here we have the `loss` since we passed along `labels`, but we don't have\n`hidden_states` and `attentions` because we didn't pass `output_hidden_states=True` or\n`output_attentions=True`.\n\nWhen passing `output_hidden_states=True` you may expect the `outputs.hidden_states[-1]` to match `outputs.last_hidden_state` exactly.\nHowever, this is not always the case. Some models apply normalization or subsequent process to the last hidden state when it's returned.", "source_file": "transformers/main_classes/output.md", "section_heading": "Model outputs", "char_start": 772, "char_end": 1561, "token_estimate": 197, "prev_chunk_id": 1156, "next_chunk_id": 1158, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1158, "text": "You can access each attribute as you would usually do, and if that attribute has not been returned by the model, you\nwill get `None`. Here for instance `outputs.loss` is the loss computed by the model, and `outputs.attentions` is\n`None`.\n\nWhen considering our `outputs` object as tuple, it only considers the attributes that don't have `None` values.\nHere for instance, it has two elements, `loss` then `logits`, so\n\n```python\noutputs[:2]\n```\n\nwill return the tuple `(outputs.loss, outputs.logits)` for instance.\n\nWhen considering our `outputs` object as dictionary, it only considers the attributes that don't have `None`\nvalues. Here for instance, it has two keys that are `loss` and `logits`.\n\nWe document here the generic model outputs that are used by more than one model type. Specific output types are\ndocumented on their corresponding model page.", "source_file": "transformers/main_classes/output.md", "section_heading": "Model outputs", "char_start": 1563, "char_end": 2417, "token_estimate": 213, "prev_chunk_id": 1157, "next_chunk_id": 1159, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1159, "text": "## ModelOutput[[transformers.utils.ModelOutput]]", "source_file": "transformers/main_classes/output.md", "section_heading": "ModelOutput[[transformers.utils.ModelOutput]]", "char_start": 2419, "char_end": 2467, "token_estimate": 12, "prev_chunk_id": 1158, "next_chunk_id": 1160, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1160, "text": "#### transformers.utils.ModelOutput[[transformers.utils.ModelOutput]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/utils/generic.py#L366)\n\nBase class for all model outputs as dataclass. Has a `__getitem__` that allows indexing by integer or slice (like a\ntuple) or strings (like a dictionary) that will ignore the `None` attributes. Otherwise behaves like a regular\npython dictionary.\n\nYou can't unpack a `ModelOutput` directly. Use the [to_tuple()](/docs/transformers/v5.6.2/en/main_classes/output#transformers.utils.ModelOutput.to_tuple) method to convert it to a tuple\nbefore.\n\nto_tupletransformers.utils.ModelOutput.to_tuplehttps://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/utils/generic.py#L499[]\n\nConvert self to a tuple containing all the attributes/keys that are not `None`.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.utils.ModelOutput[[transformers.utils.ModelOutput]]", "char_start": 2469, "char_end": 3312, "token_estimate": 210, "prev_chunk_id": 1159, "next_chunk_id": 1161, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1161, "text": "## BaseModelOutput[[transformers.modeling_outputs.BaseModelOutput]]", "source_file": "transformers/main_classes/output.md", "section_heading": "BaseModelOutput[[transformers.modeling_outputs.BaseModelOutput]]", "char_start": 3314, "char_end": 3381, "token_estimate": 16, "prev_chunk_id": 1160, "next_chunk_id": 1162, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1162, "text": "#### transformers.modeling_outputs.BaseModelOutput[[transformers.modeling_outputs.BaseModelOutput]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L24)\n\nBase class for model's outputs, with potential hidden states and attentions.\n\n**Parameters:**\n\nlast_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`) : Sequence of hidden-states at the output of the last layer of the model.\n\nhidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.BaseModelOutput[[transformers.modeling_outputs.BaseModelOutput]]", "char_start": 3383, "char_end": 4305, "token_estimate": 230, "prev_chunk_id": 1161, "next_chunk_id": 1163, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1163, "text": "attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.BaseModelOutput[[transformers.modeling_outputs.BaseModelOutput]]", "char_start": 4307, "char_end": 4685, "token_estimate": 94, "prev_chunk_id": 1162, "next_chunk_id": 1164, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1164, "text": "## BaseModelOutputWithPooling[[transformers.modeling_outputs.BaseModelOutputWithPooling]]", "source_file": "transformers/main_classes/output.md", "section_heading": "BaseModelOutputWithPooling[[transformers.modeling_outputs.BaseModelOutputWithPooling]]", "char_start": 4687, "char_end": 4776, "token_estimate": 22, "prev_chunk_id": 1163, "next_chunk_id": 1165, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1165, "text": "#### transformers.modeling_outputs.BaseModelOutputWithPooling[[transformers.modeling_outputs.BaseModelOutputWithPooling]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L69)\n\nBase class for model's outputs that also contains a pooling of the last hidden states.\n\n**Parameters:**\n\nlast_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`) : Sequence of hidden-states at the output of the last layer of the model.\n\npooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`) : Last layer hidden-state of the first token of the sequence (classification token) after further processing through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns the classification token after processing through a linear layer and a tanh activation function. The linear layer weights are trained from the next sentence prediction (classification) objective during pretraining.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.BaseModelOutputWithPooling[[transformers.modeling_outputs.BaseModelOutputWithPooling]]", "char_start": 4778, "char_end": 5784, "token_estimate": 251, "prev_chunk_id": 1164, "next_chunk_id": 1166, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1166, "text": "hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.\n\nattentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.BaseModelOutputWithPooling[[transformers.modeling_outputs.BaseModelOutputWithPooling]]", "char_start": 3856, "char_end": 4685, "token_estimate": 207, "prev_chunk_id": 1165, "next_chunk_id": 1167, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1167, "text": "## BaseModelOutputWithCrossAttentions[[transformers.modeling_outputs.BaseModelOutputWithCrossAttentions]]", "source_file": "transformers/main_classes/output.md", "section_heading": "BaseModelOutputWithCrossAttentions[[transformers.modeling_outputs.BaseModelOutputWithCrossAttentions]]", "char_start": 6617, "char_end": 6722, "token_estimate": 26, "prev_chunk_id": 1166, "next_chunk_id": 1168, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1168, "text": "#### transformers.modeling_outputs.BaseModelOutputWithCrossAttentions[[transformers.modeling_outputs.BaseModelOutputWithCrossAttentions]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L159)\n\nBase class for model's outputs, with potential hidden states and attentions.\n\n**Parameters:**\n\nlast_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`) : Sequence of hidden-states at the output of the last layer of the model.\n\nhidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.BaseModelOutputWithCrossAttentions[[transformers.modeling_outputs.BaseModelOutputWithCrossAttentions]]", "char_start": 6724, "char_end": 7685, "token_estimate": 240, "prev_chunk_id": 1167, "next_chunk_id": 1169, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1169, "text": "attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\ncross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.BaseModelOutputWithCrossAttentions[[transformers.modeling_outputs.BaseModelOutputWithCrossAttentions]]", "char_start": 7687, "char_end": 8530, "token_estimate": 210, "prev_chunk_id": 1168, "next_chunk_id": 1170, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1170, "text": "## BaseModelOutputWithPoolingAndCrossAttentions[[transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions]]", "source_file": "transformers/main_classes/output.md", "section_heading": "BaseModelOutputWithPoolingAndCrossAttentions[[transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions]]", "char_start": 8532, "char_end": 8657, "token_estimate": 31, "prev_chunk_id": 1169, "next_chunk_id": 1171, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1171, "text": "#### transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions[[transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L192)\n\nBase class for model's outputs that also contains a pooling of the last hidden states.\n\n**Parameters:**\n\nlast_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`) : Sequence of hidden-states at the output of the last layer of the model.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions[[transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions]]", "char_start": 8659, "char_end": 9199, "token_estimate": 135, "prev_chunk_id": 1170, "next_chunk_id": 1172, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1172, "text": "pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`) : Last layer hidden-state of the first token of the sequence (classification token) after further processing through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns the classification token after processing through a linear layer and a tanh activation function. The linear layer weights are trained from the next sentence prediction (classification) objective during pretraining.\n\nhidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions[[transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions]]", "char_start": 5283, "char_end": 6235, "token_estimate": 238, "prev_chunk_id": 1171, "next_chunk_id": 1173, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1173, "text": "attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\ncross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions[[transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions]]", "char_start": 7687, "char_end": 8530, "token_estimate": 210, "prev_chunk_id": 1172, "next_chunk_id": 1174, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1174, "text": "past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) : It is a [Cache](/docs/transformers/v5.6.2/en/internal/generation_utils#transformers.Cache) instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions[[transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions]]", "char_start": 11000, "char_end": 11556, "token_estimate": 139, "prev_chunk_id": 1173, "next_chunk_id": 1175, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1175, "text": "## BaseModelOutputWithPast[[transformers.modeling_outputs.BaseModelOutputWithPast]]", "source_file": "transformers/main_classes/output.md", "section_heading": "BaseModelOutputWithPast[[transformers.modeling_outputs.BaseModelOutputWithPast]]", "char_start": 11558, "char_end": 11641, "token_estimate": 20, "prev_chunk_id": 1174, "next_chunk_id": 1176, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1176, "text": "#### transformers.modeling_outputs.BaseModelOutputWithPast[[transformers.modeling_outputs.BaseModelOutputWithPast]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L123)\n\nBase class for model's outputs that may also contain a past key/values (to speed up sequential decoding).\n\n**Parameters:**\n\nlast_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`) : Sequence of hidden-states at the output of the last layer of the model. If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1, hidden_size)` is output.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.BaseModelOutputWithPast[[transformers.modeling_outputs.BaseModelOutputWithPast]]", "char_start": 11643, "char_end": 12285, "token_estimate": 160, "prev_chunk_id": 1175, "next_chunk_id": 1177, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1177, "text": "past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) : It is a [Cache](/docs/transformers/v5.6.2/en/internal/generation_utils#transformers.Cache) instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.\n\nhidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.BaseModelOutputWithPast[[transformers.modeling_outputs.BaseModelOutputWithPast]]", "char_start": 12287, "char_end": 13294, "token_estimate": 251, "prev_chunk_id": 1176, "next_chunk_id": 1178, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1178, "text": "attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.BaseModelOutputWithPast[[transformers.modeling_outputs.BaseModelOutputWithPast]]", "char_start": 4307, "char_end": 4685, "token_estimate": 94, "prev_chunk_id": 1177, "next_chunk_id": 1179, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1179, "text": "## BaseModelOutputWithPastAndCrossAttentions[[transformers.modeling_outputs.BaseModelOutputWithPastAndCrossAttentions]]", "source_file": "transformers/main_classes/output.md", "section_heading": "BaseModelOutputWithPastAndCrossAttentions[[transformers.modeling_outputs.BaseModelOutputWithPastAndCrossAttentions]]", "char_start": 13676, "char_end": 13795, "token_estimate": 29, "prev_chunk_id": 1178, "next_chunk_id": 1180, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1180, "text": "#### transformers.modeling_outputs.BaseModelOutputWithPastAndCrossAttentions[[transformers.modeling_outputs.BaseModelOutputWithPastAndCrossAttentions]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L238)\n\nBase class for model's outputs that may also contain a past key/values (to speed up sequential decoding).\n\n**Parameters:**\n\nlast_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`) : Sequence of hidden-states at the output of the last layer of the model. If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1, hidden_size)` is output.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.BaseModelOutputWithPastAndCrossAttentions[[transformers.modeling_outputs.BaseModelOutputWithPastAndCrossAttentions]]", "char_start": 13797, "char_end": 14475, "token_estimate": 169, "prev_chunk_id": 1179, "next_chunk_id": 1181, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1181, "text": "past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) : It is a [Cache](/docs/transformers/v5.6.2/en/internal/generation_utils#transformers.Cache) instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.\n\nhidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.BaseModelOutputWithPastAndCrossAttentions[[transformers.modeling_outputs.BaseModelOutputWithPastAndCrossAttentions]]", "char_start": 12287, "char_end": 13294, "token_estimate": 251, "prev_chunk_id": 1180, "next_chunk_id": 1182, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1182, "text": "attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\ncross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.BaseModelOutputWithPastAndCrossAttentions[[transformers.modeling_outputs.BaseModelOutputWithPastAndCrossAttentions]]", "char_start": 7687, "char_end": 8530, "token_estimate": 210, "prev_chunk_id": 1181, "next_chunk_id": 1183, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1183, "text": "## Seq2SeqModelOutput[[transformers.modeling_outputs.Seq2SeqModelOutput]]", "source_file": "transformers/main_classes/output.md", "section_heading": "Seq2SeqModelOutput[[transformers.modeling_outputs.Seq2SeqModelOutput]]", "char_start": 16331, "char_end": 16404, "token_estimate": 18, "prev_chunk_id": 1182, "next_chunk_id": 1184, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1184, "text": "#### transformers.modeling_outputs.Seq2SeqModelOutput[[transformers.modeling_outputs.Seq2SeqModelOutput]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L500)\n\nBase class for model encoder's outputs that also contains : pre-computed hidden states that can speed up sequential\ndecoding.\n\n**Parameters:**\n\nlast_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`) : Sequence of hidden-states at the output of the last layer of the decoder of the model. If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1, hidden_size)` is output.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqModelOutput[[transformers.modeling_outputs.Seq2SeqModelOutput]]", "char_start": 16406, "char_end": 17073, "token_estimate": 166, "prev_chunk_id": 1183, "next_chunk_id": 1185, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1185, "text": "past_key_values (`EncoderDecoderCache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) : It is a [EncoderDecoderCache](/docs/transformers/v5.6.2/en/internal/generation_utils#transformers.EncoderDecoderCache) instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.\n\ndecoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the decoder at the output of each layer plus the optional initial embedding outputs.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqModelOutput[[transformers.modeling_outputs.Seq2SeqModelOutput]]", "char_start": 17075, "char_end": 18087, "token_estimate": 253, "prev_chunk_id": 1184, "next_chunk_id": 1186, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1186, "text": "decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.\n\ncross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqModelOutput[[transformers.modeling_outputs.Seq2SeqModelOutput]]", "char_start": 18089, "char_end": 18918, "token_estimate": 207, "prev_chunk_id": 1185, "next_chunk_id": 1187, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1187, "text": "encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) : Sequence of hidden-states at the output of the last layer of the encoder of the model.\n\nencoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the encoder at the output of each layer plus the optional initial embedding outputs.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqModelOutput[[transformers.modeling_outputs.Seq2SeqModelOutput]]", "char_start": 18920, "char_end": 19583, "token_estimate": 165, "prev_chunk_id": 1186, "next_chunk_id": 1188, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1188, "text": "encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqModelOutput[[transformers.modeling_outputs.Seq2SeqModelOutput]]", "char_start": 19585, "char_end": 19987, "token_estimate": 100, "prev_chunk_id": 1187, "next_chunk_id": 1189, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1189, "text": "## CausalLMOutput[[transformers.modeling_outputs.CausalLMOutput]]", "source_file": "transformers/main_classes/output.md", "section_heading": "CausalLMOutput[[transformers.modeling_outputs.CausalLMOutput]]", "char_start": 19989, "char_end": 20054, "token_estimate": 16, "prev_chunk_id": 1188, "next_chunk_id": 1190, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1190, "text": "#### transformers.modeling_outputs.CausalLMOutput[[transformers.modeling_outputs.CausalLMOutput]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L629)\n\nBase class for causal language model (or autoregressive) outputs.\n\n**Parameters:**\n\nloss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) : Language modeling loss (for next-token prediction).\n\nlogits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`) : Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.CausalLMOutput[[transformers.modeling_outputs.CausalLMOutput]]", "char_start": 20056, "char_end": 20683, "token_estimate": 156, "prev_chunk_id": 1189, "next_chunk_id": 1191, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1191, "text": "hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.\n\nattentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.CausalLMOutput[[transformers.modeling_outputs.CausalLMOutput]]", "char_start": 3856, "char_end": 4685, "token_estimate": 207, "prev_chunk_id": 1190, "next_chunk_id": 1192, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1192, "text": "## CausalLMOutputWithCrossAttentions[[transformers.modeling_outputs.CausalLMOutputWithCrossAttentions]]", "source_file": "transformers/main_classes/output.md", "section_heading": "CausalLMOutputWithCrossAttentions[[transformers.modeling_outputs.CausalLMOutputWithCrossAttentions]]", "char_start": 21516, "char_end": 21619, "token_estimate": 25, "prev_chunk_id": 1191, "next_chunk_id": 1193, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1193, "text": "#### transformers.modeling_outputs.CausalLMOutputWithCrossAttentions[[transformers.modeling_outputs.CausalLMOutputWithCrossAttentions]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L693)\n\nBase class for causal language model (or autoregressive) outputs.\n\n**Parameters:**\n\nloss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) : Language modeling loss (for next-token prediction).\n\nlogits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`) : Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.CausalLMOutputWithCrossAttentions[[transformers.modeling_outputs.CausalLMOutputWithCrossAttentions]]", "char_start": 21621, "char_end": 22286, "token_estimate": 166, "prev_chunk_id": 1192, "next_chunk_id": 1194, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1194, "text": "hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.\n\nattentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.CausalLMOutputWithCrossAttentions[[transformers.modeling_outputs.CausalLMOutputWithCrossAttentions]]", "char_start": 3856, "char_end": 4685, "token_estimate": 207, "prev_chunk_id": 1193, "next_chunk_id": 1195, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1195, "text": "cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Cross attentions weights after the attention softmax, used to compute the weighted average in the cross-attention heads.\n\npast_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) : It is a [Cache](/docs/transformers/v5.6.2/en/internal/generation_utils#transformers.Cache) instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.CausalLMOutputWithCrossAttentions[[transformers.modeling_outputs.CausalLMOutputWithCrossAttentions]]", "char_start": 23119, "char_end": 23982, "token_estimate": 215, "prev_chunk_id": 1194, "next_chunk_id": 1196, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1196, "text": "## CausalLMOutputWithPast[[transformers.modeling_outputs.CausalLMOutputWithPast]]", "source_file": "transformers/main_classes/output.md", "section_heading": "CausalLMOutputWithPast[[transformers.modeling_outputs.CausalLMOutputWithPast]]", "char_start": 23984, "char_end": 24065, "token_estimate": 20, "prev_chunk_id": 1195, "next_chunk_id": 1197, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1197, "text": "#### transformers.modeling_outputs.CausalLMOutputWithPast[[transformers.modeling_outputs.CausalLMOutputWithPast]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L658)\n\nBase class for causal language model (or autoregressive) outputs.\n\n**Parameters:**\n\nloss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) : Language modeling loss (for next-token prediction).\n\nlogits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`) : Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.CausalLMOutputWithPast[[transformers.modeling_outputs.CausalLMOutputWithPast]]", "char_start": 24067, "char_end": 24710, "token_estimate": 160, "prev_chunk_id": 1196, "next_chunk_id": 1198, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1198, "text": "past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) : It is a [Cache](/docs/transformers/v5.6.2/en/internal/generation_utils#transformers.Cache) instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.\n\nhidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.CausalLMOutputWithPast[[transformers.modeling_outputs.CausalLMOutputWithPast]]", "char_start": 24712, "char_end": 25638, "token_estimate": 231, "prev_chunk_id": 1197, "next_chunk_id": 1199, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1199, "text": "attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.CausalLMOutputWithPast[[transformers.modeling_outputs.CausalLMOutputWithPast]]", "char_start": 4307, "char_end": 4685, "token_estimate": 94, "prev_chunk_id": 1198, "next_chunk_id": 1200, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1200, "text": "## MaskedLMOutput[[transformers.modeling_outputs.MaskedLMOutput]]", "source_file": "transformers/main_classes/output.md", "section_heading": "MaskedLMOutput[[transformers.modeling_outputs.MaskedLMOutput]]", "char_start": 26020, "char_end": 26085, "token_estimate": 16, "prev_chunk_id": 1199, "next_chunk_id": 1201, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1201, "text": "#### transformers.modeling_outputs.MaskedLMOutput[[transformers.modeling_outputs.MaskedLMOutput]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L770)\n\nBase class for masked language models outputs.\n\n**Parameters:**\n\nloss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) : Masked language modeling (MLM) loss.\n\nlogits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`) : Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.MaskedLMOutput[[transformers.modeling_outputs.MaskedLMOutput]]", "char_start": 26087, "char_end": 26680, "token_estimate": 148, "prev_chunk_id": 1200, "next_chunk_id": 1202, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1202, "text": "hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.\n\nattentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.MaskedLMOutput[[transformers.modeling_outputs.MaskedLMOutput]]", "char_start": 3856, "char_end": 4685, "token_estimate": 207, "prev_chunk_id": 1201, "next_chunk_id": 1203, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1203, "text": "## Seq2SeqLMOutput[[transformers.modeling_outputs.Seq2SeqLMOutput]]", "source_file": "transformers/main_classes/output.md", "section_heading": "Seq2SeqLMOutput[[transformers.modeling_outputs.Seq2SeqLMOutput]]", "char_start": 27513, "char_end": 27580, "token_estimate": 16, "prev_chunk_id": 1202, "next_chunk_id": 1204, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1204, "text": "#### transformers.modeling_outputs.Seq2SeqLMOutput[[transformers.modeling_outputs.Seq2SeqLMOutput]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L799)\n\nBase class for sequence-to-sequence language models outputs.\n\n**Parameters:**\n\nloss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) : Language modeling loss.\n\nlogits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`) : Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqLMOutput[[transformers.modeling_outputs.Seq2SeqLMOutput]]", "char_start": 27582, "char_end": 28178, "token_estimate": 149, "prev_chunk_id": 1203, "next_chunk_id": 1205, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1205, "text": "past_key_values (`EncoderDecoderCache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) : It is a [EncoderDecoderCache](/docs/transformers/v5.6.2/en/internal/generation_utils#transformers.EncoderDecoderCache) instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.\n\ndecoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqLMOutput[[transformers.modeling_outputs.Seq2SeqLMOutput]]", "char_start": 28180, "char_end": 29183, "token_estimate": 250, "prev_chunk_id": 1204, "next_chunk_id": 1206, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1206, "text": "decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.\n\ncross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqLMOutput[[transformers.modeling_outputs.Seq2SeqLMOutput]]", "char_start": 18089, "char_end": 18918, "token_estimate": 207, "prev_chunk_id": 1205, "next_chunk_id": 1207, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1207, "text": "encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) : Sequence of hidden-states at the output of the last layer of the encoder of the model.\n\nencoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqLMOutput[[transformers.modeling_outputs.Seq2SeqLMOutput]]", "char_start": 30016, "char_end": 30670, "token_estimate": 163, "prev_chunk_id": 1206, "next_chunk_id": 1208, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1208, "text": "encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqLMOutput[[transformers.modeling_outputs.Seq2SeqLMOutput]]", "char_start": 19585, "char_end": 19987, "token_estimate": 100, "prev_chunk_id": 1207, "next_chunk_id": 1209, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1209, "text": "## NextSentencePredictorOutput[[transformers.modeling_outputs.NextSentencePredictorOutput]]", "source_file": "transformers/main_classes/output.md", "section_heading": "NextSentencePredictorOutput[[transformers.modeling_outputs.NextSentencePredictorOutput]]", "char_start": 31076, "char_end": 31167, "token_estimate": 22, "prev_chunk_id": 1208, "next_chunk_id": 1210, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1210, "text": "#### transformers.modeling_outputs.NextSentencePredictorOutput[[transformers.modeling_outputs.NextSentencePredictorOutput]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L930)\n\nBase class for outputs of models predicting if two sentences are consecutive or not.\n\n**Parameters:**\n\nloss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `next_sentence_label` is provided) : Next sequence prediction (classification) loss.\n\nlogits (`torch.FloatTensor` of shape `(batch_size, 2)`) : Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation before SoftMax).", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.NextSentencePredictorOutput[[transformers.modeling_outputs.NextSentencePredictorOutput]]", "char_start": 31169, "char_end": 31842, "token_estimate": 168, "prev_chunk_id": 1209, "next_chunk_id": 1211, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1211, "text": "hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.\n\nattentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.NextSentencePredictorOutput[[transformers.modeling_outputs.NextSentencePredictorOutput]]", "char_start": 3856, "char_end": 4685, "token_estimate": 207, "prev_chunk_id": 1210, "next_chunk_id": 1212, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1212, "text": "## SequenceClassifierOutput[[transformers.modeling_outputs.SequenceClassifierOutput]]", "source_file": "transformers/main_classes/output.md", "section_heading": "SequenceClassifierOutput[[transformers.modeling_outputs.SequenceClassifierOutput]]", "char_start": 32675, "char_end": 32760, "token_estimate": 21, "prev_chunk_id": 1211, "next_chunk_id": 1213, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1213, "text": "#### transformers.modeling_outputs.SequenceClassifierOutput[[transformers.modeling_outputs.SequenceClassifierOutput]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L960)\n\nBase class for outputs of sentence classification models.\n\n**Parameters:**\n\nloss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) : Classification (or regression if config.num_labels==1) loss.\n\nlogits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`) : Classification (or regression if config.num_labels==1) scores (before SoftMax).", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.SequenceClassifierOutput[[transformers.modeling_outputs.SequenceClassifierOutput]]", "char_start": 32762, "char_end": 33374, "token_estimate": 153, "prev_chunk_id": 1212, "next_chunk_id": 1214, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1214, "text": "hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.\n\nattentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.SequenceClassifierOutput[[transformers.modeling_outputs.SequenceClassifierOutput]]", "char_start": 3856, "char_end": 4685, "token_estimate": 207, "prev_chunk_id": 1213, "next_chunk_id": 1215, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1215, "text": "## Seq2SeqSequenceClassifierOutput[[transformers.modeling_outputs.Seq2SeqSequenceClassifierOutput]]", "source_file": "transformers/main_classes/output.md", "section_heading": "Seq2SeqSequenceClassifierOutput[[transformers.modeling_outputs.Seq2SeqSequenceClassifierOutput]]", "char_start": 34207, "char_end": 34306, "token_estimate": 24, "prev_chunk_id": 1214, "next_chunk_id": 1216, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1216, "text": "#### transformers.modeling_outputs.Seq2SeqSequenceClassifierOutput[[transformers.modeling_outputs.Seq2SeqSequenceClassifierOutput]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L989)\n\nBase class for outputs of sequence-to-sequence sentence classification models.\n\n**Parameters:**\n\nloss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `label` is provided) : Classification (or regression if config.num_labels==1) loss.\n\nlogits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`) : Classification (or regression if config.num_labels==1) scores (before SoftMax).", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqSequenceClassifierOutput[[transformers.modeling_outputs.Seq2SeqSequenceClassifierOutput]]", "char_start": 34308, "char_end": 34954, "token_estimate": 161, "prev_chunk_id": 1215, "next_chunk_id": 1217, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1217, "text": "past_key_values (`EncoderDecoderCache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) : It is a [EncoderDecoderCache](/docs/transformers/v5.6.2/en/internal/generation_utils#transformers.EncoderDecoderCache) instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.\n\ndecoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqSequenceClassifierOutput[[transformers.modeling_outputs.Seq2SeqSequenceClassifierOutput]]", "char_start": 28180, "char_end": 29183, "token_estimate": 250, "prev_chunk_id": 1216, "next_chunk_id": 1218, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1218, "text": "decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.\n\ncross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqSequenceClassifierOutput[[transformers.modeling_outputs.Seq2SeqSequenceClassifierOutput]]", "char_start": 18089, "char_end": 18918, "token_estimate": 207, "prev_chunk_id": 1217, "next_chunk_id": 1219, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1219, "text": "encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) : Sequence of hidden-states at the output of the last layer of the encoder of the model.\n\nencoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqSequenceClassifierOutput[[transformers.modeling_outputs.Seq2SeqSequenceClassifierOutput]]", "char_start": 30016, "char_end": 30670, "token_estimate": 163, "prev_chunk_id": 1218, "next_chunk_id": 1220, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1220, "text": "encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqSequenceClassifierOutput[[transformers.modeling_outputs.Seq2SeqSequenceClassifierOutput]]", "char_start": 19585, "char_end": 19987, "token_estimate": 100, "prev_chunk_id": 1219, "next_chunk_id": 1221, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1221, "text": "## MultipleChoiceModelOutput[[transformers.modeling_outputs.MultipleChoiceModelOutput]]", "source_file": "transformers/main_classes/output.md", "section_heading": "MultipleChoiceModelOutput[[transformers.modeling_outputs.MultipleChoiceModelOutput]]", "char_start": 37852, "char_end": 37939, "token_estimate": 21, "prev_chunk_id": 1220, "next_chunk_id": 1222, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1222, "text": "#### transformers.modeling_outputs.MultipleChoiceModelOutput[[transformers.modeling_outputs.MultipleChoiceModelOutput]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L1047)\n\nBase class for outputs of multiple choice models.\n\n**Parameters:**\n\nloss (`torch.FloatTensor` of shape *(1,)*, *optional*, returned when `labels` is provided) : Classification loss.\n\nlogits (`torch.FloatTensor` of shape `(batch_size, num_choices)`) : *num_choices* is the second dimension of the input tensors. (see *input_ids* above). Classification scores (before SoftMax).", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.MultipleChoiceModelOutput[[transformers.modeling_outputs.MultipleChoiceModelOutput]]", "char_start": 37941, "char_end": 38548, "token_estimate": 151, "prev_chunk_id": 1221, "next_chunk_id": 1223, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1223, "text": "hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.\n\nattentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.MultipleChoiceModelOutput[[transformers.modeling_outputs.MultipleChoiceModelOutput]]", "char_start": 3856, "char_end": 4685, "token_estimate": 207, "prev_chunk_id": 1222, "next_chunk_id": 1224, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1224, "text": "## TokenClassifierOutput[[transformers.modeling_outputs.TokenClassifierOutput]]", "source_file": "transformers/main_classes/output.md", "section_heading": "TokenClassifierOutput[[transformers.modeling_outputs.TokenClassifierOutput]]", "char_start": 39381, "char_end": 39460, "token_estimate": 19, "prev_chunk_id": 1223, "next_chunk_id": 1225, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1225, "text": "#### transformers.modeling_outputs.TokenClassifierOutput[[transformers.modeling_outputs.TokenClassifierOutput]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L1078)\n\nBase class for outputs of token classification models.\n\n**Parameters:**\n\nloss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) : Classification loss.\n\nlogits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`) : Classification scores (before SoftMax).\n\nhidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.TokenClassifierOutput[[transformers.modeling_outputs.TokenClassifierOutput]]", "char_start": 39462, "char_end": 40454, "token_estimate": 248, "prev_chunk_id": 1224, "next_chunk_id": 1226, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1226, "text": "attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.TokenClassifierOutput[[transformers.modeling_outputs.TokenClassifierOutput]]", "char_start": 4307, "char_end": 4685, "token_estimate": 94, "prev_chunk_id": 1225, "next_chunk_id": 1227, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1227, "text": "## QuestionAnsweringModelOutput[[transformers.modeling_outputs.QuestionAnsweringModelOutput]]", "source_file": "transformers/main_classes/output.md", "section_heading": "QuestionAnsweringModelOutput[[transformers.modeling_outputs.QuestionAnsweringModelOutput]]", "char_start": 40836, "char_end": 40929, "token_estimate": 23, "prev_chunk_id": 1226, "next_chunk_id": 1228, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1228, "text": "#### transformers.modeling_outputs.QuestionAnsweringModelOutput[[transformers.modeling_outputs.QuestionAnsweringModelOutput]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L1107)\n\nBase class for outputs of question answering models.\n\n**Parameters:**\n\nloss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) : Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.\n\nstart_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length)`) : Span-start scores (before SoftMax).\n\nend_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length)`) : Span-end scores (before SoftMax).", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.QuestionAnsweringModelOutput[[transformers.modeling_outputs.QuestionAnsweringModelOutput]]", "char_start": 40931, "char_end": 41647, "token_estimate": 179, "prev_chunk_id": 1227, "next_chunk_id": 1229, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1229, "text": "hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.\n\nattentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.QuestionAnsweringModelOutput[[transformers.modeling_outputs.QuestionAnsweringModelOutput]]", "char_start": 3856, "char_end": 4685, "token_estimate": 207, "prev_chunk_id": 1228, "next_chunk_id": 1230, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1230, "text": "## Seq2SeqQuestionAnsweringModelOutput[[transformers.modeling_outputs.Seq2SeqQuestionAnsweringModelOutput]]", "source_file": "transformers/main_classes/output.md", "section_heading": "Seq2SeqQuestionAnsweringModelOutput[[transformers.modeling_outputs.Seq2SeqQuestionAnsweringModelOutput]]", "char_start": 42480, "char_end": 42587, "token_estimate": 26, "prev_chunk_id": 1229, "next_chunk_id": 1231, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1231, "text": "#### transformers.modeling_outputs.Seq2SeqQuestionAnsweringModelOutput[[transformers.modeling_outputs.Seq2SeqQuestionAnsweringModelOutput]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L1139)\n\nBase class for outputs of sequence-to-sequence question answering models.\n\n**Parameters:**\n\nloss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) : Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.\n\nstart_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length)`) : Span-start scores (before SoftMax).\n\nend_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length)`) : Span-end scores (before SoftMax).", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqQuestionAnsweringModelOutput[[transformers.modeling_outputs.Seq2SeqQuestionAnsweringModelOutput]]", "char_start": 42589, "char_end": 43340, "token_estimate": 187, "prev_chunk_id": 1230, "next_chunk_id": 1232, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1232, "text": "past_key_values (`EncoderDecoderCache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) : It is a [EncoderDecoderCache](/docs/transformers/v5.6.2/en/internal/generation_utils#transformers.EncoderDecoderCache) instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.\n\ndecoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqQuestionAnsweringModelOutput[[transformers.modeling_outputs.Seq2SeqQuestionAnsweringModelOutput]]", "char_start": 28180, "char_end": 29183, "token_estimate": 250, "prev_chunk_id": 1231, "next_chunk_id": 1233, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1233, "text": "decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.\n\ncross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqQuestionAnsweringModelOutput[[transformers.modeling_outputs.Seq2SeqQuestionAnsweringModelOutput]]", "char_start": 18089, "char_end": 18918, "token_estimate": 207, "prev_chunk_id": 1232, "next_chunk_id": 1234, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1234, "text": "encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) : Sequence of hidden-states at the output of the last layer of the encoder of the model.\n\nencoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqQuestionAnsweringModelOutput[[transformers.modeling_outputs.Seq2SeqQuestionAnsweringModelOutput]]", "char_start": 30016, "char_end": 30670, "token_estimate": 163, "prev_chunk_id": 1233, "next_chunk_id": 1235, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1235, "text": "encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqQuestionAnsweringModelOutput[[transformers.modeling_outputs.Seq2SeqQuestionAnsweringModelOutput]]", "char_start": 19585, "char_end": 19987, "token_estimate": 100, "prev_chunk_id": 1234, "next_chunk_id": 1236, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1236, "text": "## Seq2SeqSpectrogramOutput[[transformers.modeling_outputs.Seq2SeqSpectrogramOutput]]", "source_file": "transformers/main_classes/output.md", "section_heading": "Seq2SeqSpectrogramOutput[[transformers.modeling_outputs.Seq2SeqSpectrogramOutput]]", "char_start": 46238, "char_end": 46323, "token_estimate": 21, "prev_chunk_id": 1235, "next_chunk_id": 1237, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1237, "text": "#### transformers.modeling_outputs.Seq2SeqSpectrogramOutput[[transformers.modeling_outputs.Seq2SeqSpectrogramOutput]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L1470)\n\nBase class for sequence-to-sequence spectrogram outputs.\n\n**Parameters:**\n\nloss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) : Spectrogram generation loss.\n\nspectrogram (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_bins)`) : The predicted spectrogram.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqSpectrogramOutput[[transformers.modeling_outputs.Seq2SeqSpectrogramOutput]]", "char_start": 46325, "char_end": 46865, "token_estimate": 135, "prev_chunk_id": 1236, "next_chunk_id": 1238, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1238, "text": "past_key_values (`EncoderDecoderCache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) : It is a [EncoderDecoderCache](/docs/transformers/v5.6.2/en/internal/generation_utils#transformers.EncoderDecoderCache) instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.\n\ndecoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqSpectrogramOutput[[transformers.modeling_outputs.Seq2SeqSpectrogramOutput]]", "char_start": 28180, "char_end": 29183, "token_estimate": 250, "prev_chunk_id": 1237, "next_chunk_id": 1239, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1239, "text": "decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.\n\ncross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqSpectrogramOutput[[transformers.modeling_outputs.Seq2SeqSpectrogramOutput]]", "char_start": 18089, "char_end": 18918, "token_estimate": 207, "prev_chunk_id": 1238, "next_chunk_id": 1240, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1240, "text": "encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) : Sequence of hidden-states at the output of the last layer of the encoder of the model.\n\nencoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqSpectrogramOutput[[transformers.modeling_outputs.Seq2SeqSpectrogramOutput]]", "char_start": 30016, "char_end": 30670, "token_estimate": 163, "prev_chunk_id": 1239, "next_chunk_id": 1241, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1241, "text": "encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqSpectrogramOutput[[transformers.modeling_outputs.Seq2SeqSpectrogramOutput]]", "char_start": 19585, "char_end": 19987, "token_estimate": 100, "prev_chunk_id": 1240, "next_chunk_id": 1242, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1242, "text": "## SemanticSegmenterOutput[[transformers.modeling_outputs.SemanticSegmenterOutput]]", "source_file": "transformers/main_classes/output.md", "section_heading": "SemanticSegmenterOutput[[transformers.modeling_outputs.SemanticSegmenterOutput]]", "char_start": 49763, "char_end": 49846, "token_estimate": 20, "prev_chunk_id": 1241, "next_chunk_id": 1243, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1243, "text": "#### transformers.modeling_outputs.SemanticSegmenterOutput[[transformers.modeling_outputs.SemanticSegmenterOutput]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L1200)\n\nBase class for outputs of semantic segmentation models.\n\n**Parameters:**\n\nloss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) : Classification (or regression if config.num_labels==1) loss.\n\nlogits (`torch.FloatTensor` of shape `(batch_size, config.num_labels, logits_height, logits_width)`) : Classification scores for each pixel. The logits returned do not necessarily have the same size as the `pixel_values` passed as inputs. This is to avoid doing two interpolations and lose some quality when a user needs to resize the logits to the original image size as post-processing. You should always check your logits shape and resize as needed.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.SemanticSegmenterOutput[[transformers.modeling_outputs.SemanticSegmenterOutput]]", "char_start": 49848, "char_end": 50759, "token_estimate": 227, "prev_chunk_id": 1242, "next_chunk_id": 1244, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1244, "text": "hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, patch_size, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.\n\nattentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, patch_size, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.SemanticSegmenterOutput[[transformers.modeling_outputs.SemanticSegmenterOutput]]", "char_start": 50764, "char_end": 51583, "token_estimate": 204, "prev_chunk_id": 1243, "next_chunk_id": 1245, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1245, "text": "## ImageClassifierOutput[[transformers.modeling_outputs.ImageClassifierOutput]]", "source_file": "transformers/main_classes/output.md", "section_heading": "ImageClassifierOutput[[transformers.modeling_outputs.ImageClassifierOutput]]", "char_start": 51585, "char_end": 51664, "token_estimate": 19, "prev_chunk_id": 1244, "next_chunk_id": 1246, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1246, "text": "#### transformers.modeling_outputs.ImageClassifierOutput[[transformers.modeling_outputs.ImageClassifierOutput]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L1238)\n\nBase class for outputs of image classification models.\n\n**Parameters:**\n\nloss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) : Classification (or regression if config.num_labels==1) loss.\n\nlogits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`) : Classification (or regression if config.num_labels==1) scores (before SoftMax).", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.ImageClassifierOutput[[transformers.modeling_outputs.ImageClassifierOutput]]", "char_start": 51666, "char_end": 52270, "token_estimate": 151, "prev_chunk_id": 1245, "next_chunk_id": 1247, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1247, "text": "hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each stage) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states (also called feature maps) of the model at the output of each stage.\n\nattentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, patch_size, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.ImageClassifierOutput[[transformers.modeling_outputs.ImageClassifierOutput]]", "char_start": 52272, "char_end": 53078, "token_estimate": 201, "prev_chunk_id": 1246, "next_chunk_id": 1248, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1248, "text": "## ImageClassifierOutputWithNoAttention[[transformers.modeling_outputs.ImageClassifierOutputWithNoAttention]]", "source_file": "transformers/main_classes/output.md", "section_heading": "ImageClassifierOutputWithNoAttention[[transformers.modeling_outputs.ImageClassifierOutputWithNoAttention]]", "char_start": 53080, "char_end": 53189, "token_estimate": 27, "prev_chunk_id": 1247, "next_chunk_id": 1249, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1249, "text": "#### transformers.modeling_outputs.ImageClassifierOutputWithNoAttention[[transformers.modeling_outputs.ImageClassifierOutputWithNoAttention]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L1266)\n\nBase class for outputs of image classification models.\n\n**Parameters:**\n\nloss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) : Classification (or regression if config.num_labels==1) loss.\n\nlogits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`) : Classification (or regression if config.num_labels==1) scores (before SoftMax).", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.ImageClassifierOutputWithNoAttention[[transformers.modeling_outputs.ImageClassifierOutputWithNoAttention]]", "char_start": 53191, "char_end": 53825, "token_estimate": 158, "prev_chunk_id": 1248, "next_chunk_id": 1250, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1250, "text": "hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each stage) of shape `(batch_size, num_channels, height, width)`. Hidden-states (also called feature maps) of the model at the output of each stage.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.ImageClassifierOutputWithNoAttention[[transformers.modeling_outputs.ImageClassifierOutputWithNoAttention]]", "char_start": 53827, "char_end": 54257, "token_estimate": 107, "prev_chunk_id": 1249, "next_chunk_id": 1251, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1251, "text": "## DepthEstimatorOutput[[transformers.modeling_outputs.DepthEstimatorOutput]]", "source_file": "transformers/main_classes/output.md", "section_heading": "DepthEstimatorOutput[[transformers.modeling_outputs.DepthEstimatorOutput]]", "char_start": 54259, "char_end": 54336, "token_estimate": 19, "prev_chunk_id": 1250, "next_chunk_id": 1252, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1252, "text": "#### transformers.modeling_outputs.DepthEstimatorOutput[[transformers.modeling_outputs.DepthEstimatorOutput]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L1287)\n\nBase class for outputs of depth estimation models.\n\n**Parameters:**\n\nloss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) : Classification (or regression if config.num_labels==1) loss.\n\npredicted_depth (`torch.FloatTensor` of shape `(batch_size, height, width)`) : Predicted depth for each pixel.\n\nhidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, num_channels, height, width)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.DepthEstimatorOutput[[transformers.modeling_outputs.DepthEstimatorOutput]]", "char_start": 0, "char_end": 1005, "token_estimate": 251, "prev_chunk_id": 1251, "next_chunk_id": 1253, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1253, "text": "attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, patch_size, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.DepthEstimatorOutput[[transformers.modeling_outputs.DepthEstimatorOutput]]", "char_start": 51210, "char_end": 51583, "token_estimate": 93, "prev_chunk_id": 1252, "next_chunk_id": 1254, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1254, "text": "## Wav2Vec2BaseModelOutput[[transformers.modeling_outputs.Wav2Vec2BaseModelOutput]]", "source_file": "transformers/main_classes/output.md", "section_heading": "Wav2Vec2BaseModelOutput[[transformers.modeling_outputs.Wav2Vec2BaseModelOutput]]", "char_start": 55721, "char_end": 55804, "token_estimate": 20, "prev_chunk_id": 1253, "next_chunk_id": 1255, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1255, "text": "#### transformers.modeling_outputs.Wav2Vec2BaseModelOutput[[transformers.modeling_outputs.Wav2Vec2BaseModelOutput]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L1345)\n\nBase class for models that have been trained with the Wav2Vec2 loss objective.\n\n**Parameters:**\n\nlast_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`) : Sequence of hidden-states at the output of the last layer of the model.\n\nextract_features (`torch.FloatTensor` of shape `(batch_size, sequence_length, conv_dim[-1])`) : Sequence of extracted feature vectors of the last convolutional layer of the model.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Wav2Vec2BaseModelOutput[[transformers.modeling_outputs.Wav2Vec2BaseModelOutput]]", "char_start": 55806, "char_end": 56478, "token_estimate": 168, "prev_chunk_id": 1254, "next_chunk_id": 1256, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1256, "text": "hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n\nattentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Wav2Vec2BaseModelOutput[[transformers.modeling_outputs.Wav2Vec2BaseModelOutput]]", "char_start": 56480, "char_end": 57262, "token_estimate": 195, "prev_chunk_id": 1255, "next_chunk_id": 1257, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1257, "text": "## XVectorOutput[[transformers.modeling_outputs.XVectorOutput]]", "source_file": "transformers/main_classes/output.md", "section_heading": "XVectorOutput[[transformers.modeling_outputs.XVectorOutput]]", "char_start": 57264, "char_end": 57327, "token_estimate": 15, "prev_chunk_id": 1256, "next_chunk_id": 1258, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1258, "text": "#### transformers.modeling_outputs.XVectorOutput[[transformers.modeling_outputs.XVectorOutput]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L1374)\n\nOutput type of [Wav2Vec2ForXVector](/docs/transformers/v5.6.2/en/model_doc/wav2vec2#transformers.Wav2Vec2ForXVector).\n\n**Parameters:**\n\nloss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) : Classification loss.\n\nlogits (`torch.FloatTensor` of shape `(batch_size, config.xvector_output_dim)`) : Classification hidden states before AMSoftmax.\n\nembeddings (`torch.FloatTensor` of shape `(batch_size, config.xvector_output_dim)`) : Utterance embeddings used for vector similarity-based retrieval.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.XVectorOutput[[transformers.modeling_outputs.XVectorOutput]]", "char_start": 57329, "char_end": 58067, "token_estimate": 184, "prev_chunk_id": 1257, "next_chunk_id": 1259, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1259, "text": "hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n\nattentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.XVectorOutput[[transformers.modeling_outputs.XVectorOutput]]", "char_start": 56480, "char_end": 57262, "token_estimate": 195, "prev_chunk_id": 1258, "next_chunk_id": 1260, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1260, "text": "## Seq2SeqTSModelOutput[[transformers.modeling_outputs.Seq2SeqTSModelOutput]]", "source_file": "transformers/main_classes/output.md", "section_heading": "Seq2SeqTSModelOutput[[transformers.modeling_outputs.Seq2SeqTSModelOutput]]", "char_start": 58853, "char_end": 58930, "token_estimate": 19, "prev_chunk_id": 1259, "next_chunk_id": 1261, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1261, "text": "#### transformers.modeling_outputs.Seq2SeqTSModelOutput[[transformers.modeling_outputs.Seq2SeqTSModelOutput]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L1528)\n\nBase class for time series model's encoder outputs that also contains pre-computed hidden states that can speed up\nsequential decoding.\n\n**Parameters:**\n\nlast_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`) : Sequence of hidden-states at the output of the last layer of the decoder of the model. If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1, hidden_size)` is output.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqTSModelOutput[[transformers.modeling_outputs.Seq2SeqTSModelOutput]]", "char_start": 58932, "char_end": 59614, "token_estimate": 170, "prev_chunk_id": 1260, "next_chunk_id": 1262, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1262, "text": "past_key_values (`EncoderDecoderCache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) : It is a [EncoderDecoderCache](/docs/transformers/v5.6.2/en/internal/generation_utils#transformers.EncoderDecoderCache) instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.\n\ndecoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the decoder at the output of each layer plus the optional initial embedding outputs.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqTSModelOutput[[transformers.modeling_outputs.Seq2SeqTSModelOutput]]", "char_start": 17075, "char_end": 18087, "token_estimate": 253, "prev_chunk_id": 1261, "next_chunk_id": 1263, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1263, "text": "decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.\n\ncross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqTSModelOutput[[transformers.modeling_outputs.Seq2SeqTSModelOutput]]", "char_start": 18089, "char_end": 18918, "token_estimate": 207, "prev_chunk_id": 1262, "next_chunk_id": 1264, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1264, "text": "encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) : Sequence of hidden-states at the output of the last layer of the encoder of the model.\n\nencoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the encoder at the output of each layer plus the optional initial embedding outputs.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqTSModelOutput[[transformers.modeling_outputs.Seq2SeqTSModelOutput]]", "char_start": 18920, "char_end": 19583, "token_estimate": 165, "prev_chunk_id": 1263, "next_chunk_id": 1265, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1265, "text": "encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.\n\nloc (`torch.FloatTensor` of shape `(batch_size,)` or `(batch_size, input_size)`, *optional*) : Shift values of each time series' context window which is used to give the model inputs of the same magnitude and then used to shift back to the original magnitude.\n\nscale (`torch.FloatTensor` of shape `(batch_size,)` or `(batch_size, input_size)`, *optional*) : Scaling values of each time series' context window which is used to give the model inputs of the same magnitude and then used to rescale back to the original magnitude.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqTSModelOutput[[transformers.modeling_outputs.Seq2SeqTSModelOutput]]", "char_start": 62126, "char_end": 63056, "token_estimate": 232, "prev_chunk_id": 1264, "next_chunk_id": 1266, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1266, "text": "static_features (`torch.FloatTensor` of shape `(batch_size, feature size)`, *optional*) : Static features of each time series' in a batch which are copied to the covariates at inference time.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqTSModelOutput[[transformers.modeling_outputs.Seq2SeqTSModelOutput]]", "char_start": 63058, "char_end": 63249, "token_estimate": 47, "prev_chunk_id": 1265, "next_chunk_id": 1267, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1267, "text": "## Seq2SeqTSPredictionOutput[[transformers.modeling_outputs.Seq2SeqTSPredictionOutput]]", "source_file": "transformers/main_classes/output.md", "section_heading": "Seq2SeqTSPredictionOutput[[transformers.modeling_outputs.Seq2SeqTSPredictionOutput]]", "char_start": 63251, "char_end": 63338, "token_estimate": 21, "prev_chunk_id": 1266, "next_chunk_id": 1268, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1268, "text": "#### transformers.modeling_outputs.Seq2SeqTSPredictionOutput[[transformers.modeling_outputs.Seq2SeqTSPredictionOutput]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L1598)\n\nBase class for time series model's decoder outputs that also contain the loss as well as the parameters of the\nchosen distribution.\n\n**Parameters:**\n\nloss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when a `future_values` is provided) : Distributional loss.\n\nparams (`torch.FloatTensor` of shape `(batch_size, num_samples, num_params)`) : Parameters of the chosen distribution.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqTSPredictionOutput[[transformers.modeling_outputs.Seq2SeqTSPredictionOutput]]", "char_start": 63340, "char_end": 63963, "token_estimate": 155, "prev_chunk_id": 1267, "next_chunk_id": 1269, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1269, "text": "past_key_values (`EncoderDecoderCache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) : It is a [EncoderDecoderCache](/docs/transformers/v5.6.2/en/internal/generation_utils#transformers.EncoderDecoderCache) instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.\n\ndecoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqTSPredictionOutput[[transformers.modeling_outputs.Seq2SeqTSPredictionOutput]]", "char_start": 28180, "char_end": 29183, "token_estimate": 250, "prev_chunk_id": 1268, "next_chunk_id": 1270, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1270, "text": "decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.\n\ncross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqTSPredictionOutput[[transformers.modeling_outputs.Seq2SeqTSPredictionOutput]]", "char_start": 18089, "char_end": 18918, "token_estimate": 207, "prev_chunk_id": 1269, "next_chunk_id": 1271, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1271, "text": "encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) : Sequence of hidden-states at the output of the last layer of the encoder of the model.\n\nencoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) : Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqTSPredictionOutput[[transformers.modeling_outputs.Seq2SeqTSPredictionOutput]]", "char_start": 30016, "char_end": 30670, "token_estimate": 163, "prev_chunk_id": 1270, "next_chunk_id": 1272, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1272, "text": "encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) : Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.\n\nloc (`torch.FloatTensor` of shape `(batch_size,)` or `(batch_size, input_size)`, *optional*) : Shift values of each time series' context window which is used to give the model inputs of the same magnitude and then used to shift back to the original magnitude.\n\nscale (`torch.FloatTensor` of shape `(batch_size,)` or `(batch_size, input_size)`, *optional*) : Scaling values of each time series' context window which is used to give the model inputs of the same magnitude and then used to rescale back to the original magnitude.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqTSPredictionOutput[[transformers.modeling_outputs.Seq2SeqTSPredictionOutput]]", "char_start": 62126, "char_end": 63056, "token_estimate": 232, "prev_chunk_id": 1271, "next_chunk_id": 1273, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1273, "text": "static_features (`torch.FloatTensor` of shape `(batch_size, feature size)`, *optional*) : Static features of each time series' in a batch which are copied to the covariates at inference time.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.Seq2SeqTSPredictionOutput[[transformers.modeling_outputs.Seq2SeqTSPredictionOutput]]", "char_start": 63058, "char_end": 63249, "token_estimate": 47, "prev_chunk_id": 1272, "next_chunk_id": 1274, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1274, "text": "## SampleTSPredictionOutput[[transformers.modeling_outputs.SampleTSPredictionOutput]]", "source_file": "transformers/main_classes/output.md", "section_heading": "SampleTSPredictionOutput[[transformers.modeling_outputs.SampleTSPredictionOutput]]", "char_start": 67582, "char_end": 67667, "token_estimate": 21, "prev_chunk_id": 1273, "next_chunk_id": 1275, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1275, "text": "#### transformers.modeling_outputs.SampleTSPredictionOutput[[transformers.modeling_outputs.SampleTSPredictionOutput]]\n\n[Source](https://github.com/huggingface/transformers/blob/v5.6.2/src/transformers/modeling_outputs.py#L1668)\n\nBase class for time series model's predictions outputs that contains the sampled values from the chosen\ndistribution.\n\n**Parameters:**\n\nsequences (`torch.FloatTensor` of shape `(batch_size, num_samples, prediction_length)` or `(batch_size, num_samples, prediction_length, input_size)`) : Sampled values from the chosen distribution.", "source_file": "transformers/main_classes/output.md", "section_heading": "transformers.modeling_outputs.SampleTSPredictionOutput[[transformers.modeling_outputs.SampleTSPredictionOutput]]", "char_start": 67669, "char_end": 68230, "token_estimate": 140, "prev_chunk_id": 1274, "next_chunk_id": null, "url": "https://huggingface.co/docs/transformers/main_classes/output", "doc_title": "Model outputs" }, { "chunk_id": 1276, "text": "# Hugging Face Hub documentation\n\nThe Hugging Face Hub is a platform with over 2M models, 500k datasets, and 1M demo apps (Spaces), all open source and publicly available, in an online platform where people can easily collaborate and build ML together. The Hub works as a central place where anyone can explore, experiment, collaborate, and build technology with Machine Learning. Are you ready to join the path towards open source Machine Learning? \ud83e\udd17\n\n Subscriptions & Plans\nPRO subscription\nTeam & Enterprise Plans\nSingle Sign-On (SSO)\nAudit Logs\nStorage Regions\nData Studio for Private datasets\nResource Groups\nAdvanced Security\nTokens Management\nNetwork Security\nRate Limits\n\n Repositories\nGetting Started\nRepository Settings\nStorage Limits\nStorage Backend (Xet)\nLocal Cache\nPull requests and Discussions\nNotifications\nCollections\nWebhooks\nNext Steps\nLicenses\n\n Models\nThe Model Hub\nModel Cards\nEval Results\nGated Models\nUploading Models\nDownloading Models\nLibraries\nTasks\nWidgets\nInference Providers\nDownload Stats", "source_file": "hub/index.md", "section_heading": "Hugging Face Hub documentation", "char_start": 0, "char_end": 1024, "token_estimate": 256, "prev_chunk_id": null, "next_chunk_id": 1277, "url": "https://huggingface.co/docs/hub/index", "doc_title": "Hugging Face Hub documentation" }, { "chunk_id": 1277, "text": "Datasets\nIntroduction\nDatasets Overview\nDataset Cards\nGated Datasets\nUploading Datasets\nIngesting Datasets\nDownloading Datasets\nStreaming Datasets\nEditing Datasets\nLibraries\nData Studio\nDownload Stats\nData files Configuration\n\n Spaces\nIntroduction\nSpaces Overview\nGradio Spaces\nStatic HTML Spaces\nDocker Spaces\nZeroGPU Spaces\nEmbed your Space\nRun with Docker\nReference\nAdvanced Topics\nSign in with HF\n\n Storage Buckets new\nIntroduction\nBuckets vs Git Repositories\nCreating a Bucket\nManaging Files\nUse Cases\nSecurity & Compliance\n\n Jobs\nIntroduction\nJobs Overview\nQuickstart\nPricing\nManage Jobs\nJobs Configuration\nPopular images\nSchedule Jobs\nWebhooks Automation\nReference\n\n Agents\nIntroduction\nAgents Overview\nHugging Face CLI for AI Agents\nHugging Face MCP Server\nHugging Face Agent Skills\nBuilding agents with the HF SDK\nLocal Agents\nAgent Libraries", "source_file": "hub/index.md", "section_heading": "Hugging Face Hub documentation", "char_start": 1027, "char_end": 1878, "token_estimate": 212, "prev_chunk_id": 1276, "next_chunk_id": 1278, "url": "https://huggingface.co/docs/hub/index", "doc_title": "Hugging Face Hub documentation" }, { "chunk_id": 1278, "text": "Other\nOrganizations\nBilling\nSecurity\nModeration\nPaper Pages\nSearch\nDigital Object Identifier (DOI)\nHub API Endpoints\nSign in with HF\nContributor Code of Conduct\nContent Guidelines", "source_file": "hub/index.md", "section_heading": "Hugging Face Hub documentation", "char_start": 1881, "char_end": 2060, "token_estimate": 45, "prev_chunk_id": 1277, "next_chunk_id": 1279, "url": "https://huggingface.co/docs/hub/index", "doc_title": "Hugging Face Hub documentation" }, { "chunk_id": 1279, "text": "## What's the Hugging Face Hub?\n\nWe are helping the community work together towards the goal of advancing Machine Learning \ud83d\udd25.\n\nThe Hugging Face Hub is a platform with over 2M models, 500k datasets, and 1M demos in which people can easily collaborate in their ML workflows. The Hub works as a central place where anyone can share, explore, discover, and experiment with open-source Machine Learning.\n\nNo single company, including the Tech Titans, will be able to \u201csolve AI\u201d by themselves \u2013 the only way we'll achieve this is by sharing knowledge and resources in a community-centric approach. We are building the largest open-source collection of models, datasets, and demos on the Hugging Face Hub to democratize and advance ML for everyone \ud83d\ude80.\n\nWe encourage you to read the [Code of Conduct](https://huggingface.co/code-of-conduct) and the [Content Guidelines](https://huggingface.co/content-guidelines) to familiarize yourself with the values that we expect our community members to uphold \ud83e\udd17.", "source_file": "hub/index.md", "section_heading": "What's the Hugging Face Hub?", "char_start": 2062, "char_end": 3055, "token_estimate": 248, "prev_chunk_id": 1278, "next_chunk_id": 1280, "url": "https://huggingface.co/docs/hub/index", "doc_title": "Hugging Face Hub documentation" }, { "chunk_id": 1280, "text": "## What can you find on the Hub?\n\nThe Hugging Face Hub hosts Git-based repositories, which are version-controlled folders that can contain all your files. For non-versioned, mutable object storage, the Hub also offers [Storage Buckets](./storage-buckets).\n\nOn it, you'll be able to upload and discover...\n\n- Models: _hosting the latest state-of-the-art models for LLM, text, vision, and audio tasks_\n- Datasets: _featuring a wide variety of data for different domains and modalities_\n- Spaces: _interactive apps for demonstrating ML models directly in your browser_\n\nThe Hub offers **versioning, commit history, diffs, branches, and over a dozen library integrations**! \nAll repositories build on [Xet](./xet/index), a new technology to efficiently store Large Files inside Git, intelligently splitting files into unique chunks and accelerating uploads and downloads.\n\nYou can learn more about the features that all repositories share in the [**Repositories documentation**](./repositories).", "source_file": "hub/index.md", "section_heading": "What can you find on the Hub?", "char_start": 3057, "char_end": 4048, "token_estimate": 247, "prev_chunk_id": 1279, "next_chunk_id": 1281, "url": "https://huggingface.co/docs/hub/index", "doc_title": "Hugging Face Hub documentation" }, { "chunk_id": 1281, "text": "## Models\n\nYou can discover and use dozens of thousands of open-source ML models shared by the community. To promote responsible model usage and development, model repos are equipped with [Model Cards](./model-cards) to inform users of each model's limitations and biases. Additional [metadata](./model-cards#model-card-metadata) about info such as their tasks, languages, and evaluation results can be included, with training metrics charts even added if the repository contains [TensorBoard traces](./tensorboard). It's also easy to add an [**inference widget**](./models-widgets) to your model, allowing anyone to play with the model directly in the browser! For programmatic access, a serverless API is provided by [**Inference Providers**](./models-inference).", "source_file": "hub/index.md", "section_heading": "Models", "char_start": 4050, "char_end": 4815, "token_estimate": 191, "prev_chunk_id": 1280, "next_chunk_id": 1282, "url": "https://huggingface.co/docs/hub/index", "doc_title": "Hugging Face Hub documentation" }, { "chunk_id": 1282, "text": "To upload models to the Hub, or download models and integrate them into your work, explore the [**Models documentation**](./models). You can also choose from [**over a dozen libraries**](./models-libraries) such as \ud83e\udd17 Transformers, Asteroid, and ESPnet that support the Hub.", "source_file": "hub/index.md", "section_heading": "Models", "char_start": 4817, "char_end": 5090, "token_estimate": 68, "prev_chunk_id": 1281, "next_chunk_id": 1283, "url": "https://huggingface.co/docs/hub/index", "doc_title": "Hugging Face Hub documentation" }, { "chunk_id": 1283, "text": "## Datasets\n\nThe Hub is home to over 500k public datasets in more than 8k languages that can be used for a broad range of tasks across NLP, Computer Vision, and Audio. The Hub makes it simple to find, download, and upload datasets. Datasets are accompanied by extensive documentation in the form of [**Dataset Cards**](./datasets-cards) and [**Data Studio**](./datasets-viewer) to let you explore the data directly in your browser. While many datasets are public, [**organizations**](./organizations) and individuals can create private datasets to comply with licensing or privacy issues. You can learn more about [**Datasets here on the Hugging Face Hub documentation**](./datasets-overview).", "source_file": "hub/index.md", "section_heading": "Datasets", "char_start": 5092, "char_end": 5785, "token_estimate": 173, "prev_chunk_id": 1282, "next_chunk_id": 1284, "url": "https://huggingface.co/docs/hub/index", "doc_title": "Hugging Face Hub documentation" }, { "chunk_id": 1284, "text": "The [\ud83e\udd17 `datasets`](https://huggingface.co/docs/datasets/index) library allows you to programmatically interact with the datasets, so you can easily use datasets from the Hub in your projects. With a single line of code, you can access the datasets; even if they are so large they don't fit in your computer, you can use streaming to efficiently access the data.", "source_file": "hub/index.md", "section_heading": "Datasets", "char_start": 5787, "char_end": 6148, "token_estimate": 90, "prev_chunk_id": 1283, "next_chunk_id": 1285, "url": "https://huggingface.co/docs/hub/index", "doc_title": "Hugging Face Hub documentation" }, { "chunk_id": 1285, "text": "## Spaces\n\n[Spaces](https://huggingface.co/spaces) is a simple way to host ML demo apps on the Hub. They allow you to build your ML portfolio, showcase your projects at conferences or to stakeholders, and work collaboratively with other people in the ML ecosystem.\n\nWe currently support two awesome Python SDKs (**[Gradio](https://gradio.app/)** and **[Streamlit](./spaces-sdks-streamlit)**) that let you build cool apps in a matter of minutes. Users can also create static Spaces, which are simple HTML/CSS/JavaScript pages, or deploy any Docker-based application.\n\nIf you need GPU power for your demos, try [**ZeroGPU**](./spaces-zerogpu): it dynamically provides NVIDIA H200 GPUs, in real-time, only when needed.", "source_file": "hub/index.md", "section_heading": "Spaces", "char_start": 6150, "char_end": 6865, "token_estimate": 178, "prev_chunk_id": 1284, "next_chunk_id": 1286, "url": "https://huggingface.co/docs/hub/index", "doc_title": "Hugging Face Hub documentation" }, { "chunk_id": 1286, "text": "After you've explored a few Spaces (take a look at our [Space of the Week!](https://huggingface.co/spaces)), dive into the [**Spaces documentation**](./spaces-overview) to learn all about how you can create your own Space. You'll also be able to upgrade your Space to run on a GPU or other accelerated hardware. \u26a1\ufe0f", "source_file": "hub/index.md", "section_heading": "Spaces", "char_start": 6867, "char_end": 7181, "token_estimate": 78, "prev_chunk_id": 1285, "next_chunk_id": 1287, "url": "https://huggingface.co/docs/hub/index", "doc_title": "Hugging Face Hub documentation" }, { "chunk_id": 1287, "text": "## Storage Buckets\n\n[Storage Buckets](./storage-buckets) provide S3-like object storage on Hugging Face, powered by the Xet storage backend. Unlike repositories (which are git-based and track file history), buckets are remote object storage containers designed for large-scale files with content-addressable deduplication. They are designed for use cases where you need simple, fast, mutable storage such as storing training checkpoints, logs, intermediate artifacts, or any large collection of files that doesn\u2019t need version control.", "source_file": "hub/index.md", "section_heading": "Storage Buckets", "char_start": 7183, "char_end": 7718, "token_estimate": 133, "prev_chunk_id": 1286, "next_chunk_id": 1288, "url": "https://huggingface.co/docs/hub/index", "doc_title": "Hugging Face Hub documentation" }, { "chunk_id": 1288, "text": "## Organizations\n\nCompanies, universities and non-profits are an essential part of the Hugging Face community! The Hub offers [**Organizations**](./organizations), which can be used to group accounts and manage datasets, models, and Spaces. Educators can also create collaborative organizations for students using [Hugging Face for Classrooms](https://huggingface.co/classrooms). An organization's repositories will be featured on the organization\u2019s page and every member of the organization will have the ability to contribute to the repository. In addition to conveniently grouping all of an organization's work, the Hub allows admins to set roles to [**control access to repositories**](./organizations-security), and manage their organization's [payment method and billing info](https://huggingface.co/pricing). Machine Learning is more fun when collaborating! \ud83d\udd25", "source_file": "hub/index.md", "section_heading": "Organizations", "char_start": 7720, "char_end": 8586, "token_estimate": 216, "prev_chunk_id": 1287, "next_chunk_id": 1289, "url": "https://huggingface.co/docs/hub/index", "doc_title": "Hugging Face Hub documentation" }, { "chunk_id": 1289, "text": "[Explore existing organizations](https://huggingface.co/organizations), create a new organization [here](https://huggingface.co/organizations/new), and then visit the [**Organizations documentation**](./organizations) to learn more.", "source_file": "hub/index.md", "section_heading": "Organizations", "char_start": 8588, "char_end": 8820, "token_estimate": 58, "prev_chunk_id": 1288, "next_chunk_id": 1290, "url": "https://huggingface.co/docs/hub/index", "doc_title": "Hugging Face Hub documentation" }, { "chunk_id": 1290, "text": "## Security\n\nThe Hugging Face Hub supports security and access control features to give you the peace of mind that your code, models, and data are safe. Visit the [**Security**](./security) section in these docs to learn about:\n\n- User Access Tokens\n- Access Control for Organizations\n- Signing commits with GPG\n- Malware scanning", "source_file": "hub/index.md", "section_heading": "Security", "char_start": 8822, "char_end": 9152, "token_estimate": 82, "prev_chunk_id": 1289, "next_chunk_id": null, "url": "https://huggingface.co/docs/hub/index", "doc_title": "Hugging Face Hub documentation" }, { "chunk_id": 1291, "text": "# Repositories\n\nModels, Spaces, and Datasets are hosted on the Hugging Face Hub as [Git repositories](https://git-scm.com/about), which means that version control and collaboration are core elements of the Hub. In a nutshell, a repository (also known as a **repo**) is a place where code and assets can be stored to back up your work, share it with the community, and work in a team.\n\n> [!TIP]\n> Looking for non-versioned, mutable storage? Check out [Storage Buckets](./storage-buckets), which provide S3-like object storage without Git history.\n\nUnlike other collaboration platforms, our Git repositories are optimized for Machine Learning and AI files \u2013 large binary files, usually in specific file formats like Parquet and Safetensors, and up to [Terabyte-scale sizes](https://huggingface.co/blog/from-files-to-chunks)!\nTo achieve this, we built [Xet](./xet/index), a modern custom storage system built specifically for AI/ML development, enabling chunk-level deduplication, smaller uploads, and faster downloads.", "source_file": "hub/repositories.md", "section_heading": "Repositories", "char_start": 0, "char_end": 1016, "token_estimate": 254, "prev_chunk_id": null, "next_chunk_id": 1292, "url": "https://huggingface.co/docs/hub/repositories", "doc_title": "Repositories" }, { "chunk_id": 1292, "text": "In these pages, you will go over the basics of getting started with Git and Xet and interacting with repositories on the Hub. Once you get the hang of it, you can explore the best practices and next steps that we've compiled for effective repository usage.", "source_file": "hub/repositories.md", "section_heading": "Repositories", "char_start": 1018, "char_end": 1274, "token_estimate": 64, "prev_chunk_id": 1291, "next_chunk_id": 1293, "url": "https://huggingface.co/docs/hub/repositories", "doc_title": "Repositories" }, { "chunk_id": 1293, "text": "## Contents\n\n- [Getting Started with Repositories](./repositories-getting-started)\n- [Settings](./repositories-settings)\n- [Storage Limits](./storage-limits)\n- [Storage Backend (Xet)](./xet/index)\n- [Local Cache](./local-cache)\n- [Pull Requests & Discussions](./repositories-pull-requests-discussions)\n - [Pull Requests advanced usage](./repositories-pull-requests-discussions#pull-requests-advanced-usage)\n- [Collections](./collections)\n- [Notifications](./notifications)\n- [Webhooks](./webhooks)\n- [Next Steps](./repositories-next-steps)\n- [Licenses](./repositories-licenses)", "source_file": "hub/repositories.md", "section_heading": "Contents", "char_start": 1276, "char_end": 1854, "token_estimate": 144, "prev_chunk_id": 1292, "next_chunk_id": null, "url": "https://huggingface.co/docs/hub/repositories", "doc_title": "Repositories" }, { "chunk_id": 1294, "text": "# Getting Started with Repositories\n\nThis beginner-friendly guide will help you get the basic skills you need to create and manage your repository on the Hub. Each section builds on the previous one, so feel free to choose where to start!", "source_file": "hub/repositories-getting-started.md", "section_heading": "Getting Started with Repositories", "char_start": 0, "char_end": 238, "token_estimate": 59, "prev_chunk_id": null, "next_chunk_id": 1295, "url": "https://huggingface.co/docs/hub/repositories-getting-started", "doc_title": "Getting Started with Repositories" }, { "chunk_id": 1295, "text": "## Requirements\n\nThis document shows how to handle repositories through the web interface as well as through the terminal. There are no requirements if working with the UI. If you want to work with the terminal, please follow these installation instructions.\n\nIf you do not have `git` available as a CLI command yet, you will need to [install Git](https://git-scm.com/downloads) for your platform. You will also need to [install Git-Xet](./xet/using-xet-storage#git-xet), which will be used to handle large files such as images and model weights.\n\n> [!TIP]\n> To be able to download and upload large files from Git, you need to install the [Git Xet](./xet/using-xet-storage#git) extension.\n\nTo be able to push your code to the Hub, you'll need to authenticate somehow. The easiest way to do this is by installing the [`hf` CLI](https://huggingface.co/docs/huggingface_hub/guides/cli) and running the login command:\n\n```bash", "source_file": "hub/repositories-getting-started.md", "section_heading": "Requirements", "char_start": 240, "char_end": 1162, "token_estimate": 230, "prev_chunk_id": 1294, "next_chunk_id": 1296, "url": "https://huggingface.co/docs/hub/repositories-getting-started", "doc_title": "Getting Started with Repositories" }, { "chunk_id": 1296, "text": "# Install hf:", "source_file": "hub/repositories-getting-started.md", "section_heading": "Install hf:", "char_start": 1163, "char_end": 1176, "token_estimate": 3, "prev_chunk_id": 1295, "next_chunk_id": 1297, "url": "https://huggingface.co/docs/hub/repositories-getting-started", "doc_title": "Getting Started with Repositories" }, { "chunk_id": 1297, "text": "# brew install hf", "source_file": "hub/repositories-getting-started.md", "section_heading": "brew install hf", "char_start": 1177, "char_end": 1196, "token_estimate": 4, "prev_chunk_id": 1296, "next_chunk_id": 1298, "url": "https://huggingface.co/docs/hub/repositories-getting-started", "doc_title": "Getting Started with Repositories" }, { "chunk_id": 1298, "text": "# or", "source_file": "hub/repositories-getting-started.md", "section_heading": "or", "char_start": 1197, "char_end": 1203, "token_estimate": 1, "prev_chunk_id": 1297, "next_chunk_id": 1299, "url": "https://huggingface.co/docs/hub/repositories-getting-started", "doc_title": "Getting Started with Repositories" }, { "chunk_id": 1299, "text": "# pip install hf\nhf auth login\n```\n\n**The content in the Getting Started section of this document is also available as a video!**", "source_file": "hub/repositories-getting-started.md", "section_heading": "pip install hf", "char_start": 1204, "char_end": 1335, "token_estimate": 32, "prev_chunk_id": 1298, "next_chunk_id": 1300, "url": "https://huggingface.co/docs/hub/repositories-getting-started", "doc_title": "Getting Started with Repositories" }, { "chunk_id": 1300, "text": "## Creating a repository\n\nUsing the Hub's web interface you can easily create repositories, add files (even large ones!), explore models, visualize diffs, and much more. There are three kinds of repositories on the Hub, and in this guide you'll be creating a **model repository** for demonstration purposes. For information on creating and managing models, datasets, and Spaces, refer to their respective documentation.\n\n1. To create a new repository, visit [huggingface.co/new](http://huggingface.co/new):\n\n2. Specify the owner of the repository: this can be either you or any of the organizations you\u2019re affiliated with.\n\n3. Enter your model\u2019s name. This will also be the name of the repository.\n\n4. Specify whether you want your model to be public or private.\n\n5. Specify the license. You can leave the *License* field blank for now. To learn about licenses, visit the [**Licenses**](repositories-licenses) documentation.\n\nAfter creating your model repository, you should see a page like this:", "source_file": "hub/repositories-getting-started.md", "section_heading": "Creating a repository", "char_start": 0, "char_end": 996, "token_estimate": 249, "prev_chunk_id": 1299, "next_chunk_id": 1301, "url": "https://huggingface.co/docs/hub/repositories-getting-started", "doc_title": "Getting Started with Repositories" }, { "chunk_id": 1301, "text": "Note that the Hub prompts you to create a *Model Card*, which you can learn about in the [**Model Cards documentation**](./model-cards). Including a Model Card in your model repo is best practice, but since we're only making a test repo at the moment we can skip this.", "source_file": "hub/repositories-getting-started.md", "section_heading": "Creating a repository", "char_start": 2337, "char_end": 2605, "token_estimate": 67, "prev_chunk_id": 1300, "next_chunk_id": 1302, "url": "https://huggingface.co/docs/hub/repositories-getting-started", "doc_title": "Getting Started with Repositories" }, { "chunk_id": 1302, "text": "## Adding files to a repository (Web UI)\n\nTo add files to your repository via the web UI, start by selecting the **Files** tab, navigating to the desired directory, and then clicking **Add file**. You'll be given the option to create a new file or upload a file directly from your computer.", "source_file": "hub/repositories-getting-started.md", "section_heading": "Adding files to a repository (Web UI)", "char_start": 2607, "char_end": 2897, "token_estimate": 72, "prev_chunk_id": 1301, "next_chunk_id": 1303, "url": "https://huggingface.co/docs/hub/repositories-getting-started", "doc_title": "Getting Started with Repositories" }, { "chunk_id": 1303, "text": "### Creating a new file\n\nChoosing to create a new file will take you to the following editor screen, where you can choose a name for your file, add content, and save your file with a message that summarizes your changes. Instead of directly committing the new file to your repo's `main` branch, you can select `Open as a pull request` to create a [Pull Request](./repositories-pull-requests-discussions).", "source_file": "hub/repositories-getting-started.md", "section_heading": "Creating a new file", "char_start": 2900, "char_end": 3304, "token_estimate": 101, "prev_chunk_id": 1302, "next_chunk_id": 1304, "url": "https://huggingface.co/docs/hub/repositories-getting-started", "doc_title": "Getting Started with Repositories" }, { "chunk_id": 1304, "text": "### Uploading a file\n\nIf you choose _Upload file_ you'll be able to choose a local file to upload, along with a message summarizing your changes to the repo.\n\nAs with creating new files, you can select `Open as a pull request` to create a [Pull Request](./repositories-pull-requests-discussions) instead of adding your changes directly to the `main` branch of your repo.", "source_file": "hub/repositories-getting-started.md", "section_heading": "Uploading a file", "char_start": 3306, "char_end": 3676, "token_estimate": 92, "prev_chunk_id": 1303, "next_chunk_id": 1305, "url": "https://huggingface.co/docs/hub/repositories-getting-started", "doc_title": "Getting Started with Repositories" }, { "chunk_id": 1305, "text": "## Adding files to a repository (CLI)[[cli]]\n\nYou can upload files to your repository directly from the terminal using the [`hf` CLI](https://huggingface.co/docs/huggingface_hub/guides/cli). Use the `hf upload` command to push local files or entire folders:\n\n```bash", "source_file": "hub/repositories-getting-started.md", "section_heading": "Adding files to a repository (CLI)[[cli]]", "char_start": 3678, "char_end": 3944, "token_estimate": 66, "prev_chunk_id": 1304, "next_chunk_id": 1306, "url": "https://huggingface.co/docs/hub/repositories-getting-started", "doc_title": "Getting Started with Repositories" }, { "chunk_id": 1306, "text": "# Upload a single file to your model repo\nhf upload your-username/your-model-name model.safetensors", "source_file": "hub/repositories-getting-started.md", "section_heading": "Upload a single file to your model repo", "char_start": 3945, "char_end": 4044, "token_estimate": 24, "prev_chunk_id": 1305, "next_chunk_id": 1307, "url": "https://huggingface.co/docs/hub/repositories-getting-started", "doc_title": "Getting Started with Repositories" }, { "chunk_id": 1307, "text": "# Upload an entire directory\nhf upload your-username/your-model-name ./my-model-directory", "source_file": "hub/repositories-getting-started.md", "section_heading": "Upload an entire directory", "char_start": 4046, "char_end": 4135, "token_estimate": 22, "prev_chunk_id": 1306, "next_chunk_id": 1308, "url": "https://huggingface.co/docs/hub/repositories-getting-started", "doc_title": "Getting Started with Repositories" }, { "chunk_id": 1308, "text": "# Upload to a dataset repo\nhf upload your-username/your-dataset-name ./data --repo-type dataset\n```\n\nThe `hf` CLI handles large files automatically \u2014 no extra setup is required.", "source_file": "hub/repositories-getting-started.md", "section_heading": "Upload to a dataset repo", "char_start": 4137, "char_end": 4314, "token_estimate": 44, "prev_chunk_id": 1307, "next_chunk_id": 1309, "url": "https://huggingface.co/docs/hub/repositories-getting-started", "doc_title": "Getting Started with Repositories" }, { "chunk_id": 1309, "text": "## Adding files to a repository (git)[[terminal]]", "source_file": "hub/repositories-getting-started.md", "section_heading": "Adding files to a repository (git)[[terminal]]", "char_start": 4316, "char_end": 4365, "token_estimate": 12, "prev_chunk_id": 1308, "next_chunk_id": 1310, "url": "https://huggingface.co/docs/hub/repositories-getting-started", "doc_title": "Getting Started with Repositories" }, { "chunk_id": 1310, "text": "### Cloning repositories\n\nDownloading repositories to your local machine is called *cloning*. You can use the following commands to load your repo and navigate to it:\n\n```bash\ngit clone https://huggingface.co//\ncd \n```\n\nOr for a dataset repo:\n\n```bash\ngit clone https://huggingface.co/datasets//\ncd \n```\n\nYou can clone over SSH with the following command:\n```bash\ngit clone git@hf.co:/\ncd \n```\n\nYou'll need to add your SSH public key to [your user settings](https://huggingface.co/settings/keys) to push changes or access private repositories.", "source_file": "hub/repositories-getting-started.md", "section_heading": "Cloning repositories", "char_start": 4367, "char_end": 4910, "token_estimate": 135, "prev_chunk_id": 1309, "next_chunk_id": 1311, "url": "https://huggingface.co/docs/hub/repositories-getting-started", "doc_title": "Getting Started with Repositories" }, { "chunk_id": 1311, "text": "### Set up\n\nNow's the time, you can add any files you want to the repository! \ud83d\udd25\n\nDo you have files larger than 10MB? Those files should be tracked with [`git-xet`](./xet/using-xet-storage#git-xet), which you can initialize with:\n\n```bash\ngit xet install\n```\n\nWhen you use Hugging Face to create a repository, Hugging Face automatically provides a list of common file extensions for common Machine Learning large files in the `.gitattributes` file, which `git-xet` uses to efficiently track changes to your large files. However, you might need to add new extensions if your file types are not already handled. You can do so with `git xet track \"*.your_extension\"`.", "source_file": "hub/repositories-getting-started.md", "section_heading": "Set up", "char_start": 4912, "char_end": 5575, "token_estimate": 165, "prev_chunk_id": 1310, "next_chunk_id": 1312, "url": "https://huggingface.co/docs/hub/repositories-getting-started", "doc_title": "Getting Started with Repositories" }, { "chunk_id": 1312, "text": "### Pushing files\n\nYou can use Git to save new files and any changes to already existing files as a bundle of changes called a *commit*, which can be thought of as a \"revision\" to your project. To create a commit, you have to `add` the files to let Git know that we're planning on saving the changes and then `commit` those changes. In order to sync the new commit with the Hugging Face Hub, you then `push` the commit to the Hub.\n\n```bash", "source_file": "hub/repositories-getting-started.md", "section_heading": "Pushing files", "char_start": 5577, "char_end": 6016, "token_estimate": 109, "prev_chunk_id": 1311, "next_chunk_id": 1313, "url": "https://huggingface.co/docs/hub/repositories-getting-started", "doc_title": "Getting Started with Repositories" }, { "chunk_id": 1313, "text": "# Create any files you like! Then...\ngit add .\ngit commit -m \"First model version\" # You can choose any descriptive message\ngit push\n```\n\nAnd you're done! You can check your repository on Hugging Face with all the recently added files. For example, in the screenshot below the user added a number of files. Note that some files in this example have a size of `1.04 GB`, so the repo uses Xet to track it.\n\n> [!TIP]\n> If you cloned the repository with HTTP, you might be asked to fill your username and password on every push operation. The simplest way to avoid repetition is to [switch to SSH](#cloning-repositories), instead of HTTP. Alternatively, if you have to use HTTP, you might find it helpful to setup a [git credential helper](https://git-scm.com/docs/gitcredentials#_avoiding_repetition) to autofill your username and password.", "source_file": "hub/repositories-getting-started.md", "section_heading": "Create any files you like! Then...", "char_start": 6017, "char_end": 6855, "token_estimate": 209, "prev_chunk_id": 1312, "next_chunk_id": 1314, "url": "https://huggingface.co/docs/hub/repositories-getting-started", "doc_title": "Getting Started with Repositories" }, { "chunk_id": 1314, "text": "## Viewing a repo's history\n\nEvery time you go through the `add`-`commit`-`push` cycle, the repo will keep track of every change you've made to your files. The UI allows you to explore the model files and commits and to see the difference (also known as *diff*) introduced by each commit. To see the history, you can click on the **History: X commits** link.\n\nYou can click on an individual commit to see what changes that commit introduced:", "source_file": "hub/repositories-getting-started.md", "section_heading": "Viewing a repo's history", "char_start": 6857, "char_end": 7298, "token_estimate": 110, "prev_chunk_id": 1313, "next_chunk_id": null, "url": "https://huggingface.co/docs/hub/repositories-getting-started", "doc_title": "Getting Started with Repositories" }, { "chunk_id": 1315, "text": "# Models\n\nThe Hugging Face Hub hosts many models for a [variety of machine learning tasks](https://huggingface.co/tasks). Models are stored in repositories, so they benefit from [all the features](./repositories) possessed by every repo on the Hugging Face Hub. Additionally, model repos have attributes that make exploring and using models as easy as possible. These docs will take you through everything you'll need to know to find models on the Hub, upload your models, and make the most of everything the Model Hub offers!", "source_file": "hub/models.md", "section_heading": "Models", "char_start": 0, "char_end": 526, "token_estimate": 131, "prev_chunk_id": null, "next_chunk_id": 1316, "url": "https://huggingface.co/docs/hub/models", "doc_title": "Models" }, { "chunk_id": 1316, "text": "## Contents\n\n- [The Model Hub](./models-the-hub)\n- [Model Cards](./model-cards)\n - [CO2 emissions](./model-cards-co2)\n- [Eval Results](./eval-results)\n- [Gated models](./models-gated)\n- [Uploading Models](./models-uploading)\n- [Downloading Models](./models-downloading)\n- [Libraries](./models-libraries)\n- [Widgets](./models-widgets)\n - [Widget Examples](./models-widgets-examples)\n- [Model Inference](./models-inference)\n- [Local Apps](./local-apps)\n- [Frequently Asked Questions](./models-faq)\n- [Advanced Topics](./models-advanced)\n - [Integrating libraries with the Hub](./models-adding-libraries)\n - [Tasks](./models-tasks)", "source_file": "hub/models.md", "section_heading": "Contents", "char_start": 528, "char_end": 1160, "token_estimate": 158, "prev_chunk_id": 1315, "next_chunk_id": null, "url": "https://huggingface.co/docs/hub/models", "doc_title": "Models" }, { "chunk_id": 1317, "text": "# Datasets\n\nThe Hugging Face Hub is home to a growing collection of datasets that span a variety of domains and tasks. These docs will guide you through interacting with the datasets on the Hub, uploading new datasets, exploring the datasets contents, and using datasets in your projects.\n\nThis documentation focuses on the datasets functionality in the Hugging Face Hub and how to use the datasets with supported libraries. For detailed information about the \ud83e\udd17 Datasets python package, visit the [\ud83e\udd17 Datasets documentation](/docs/datasets/index).", "source_file": "hub/datasets.md", "section_heading": "Datasets", "char_start": 0, "char_end": 546, "token_estimate": 136, "prev_chunk_id": null, "next_chunk_id": 1318, "url": "https://huggingface.co/docs/hub/datasets", "doc_title": "Datasets" }, { "chunk_id": 1318, "text": "## Contents\n\n- [Datasets Overview](./datasets-overview)\n- [Dataset Cards](./datasets-cards)\n- [Gated Datasets](./datasets-gated)\n- [Uploading Datasets](./datasets-adding)\n- [Downloading Datasets](./datasets-downloading)\n- [Libraries](./datasets-libraries)\n- [Dataset Viewer](./datasets-viewer)\n- [Data files Configuration](./datasets-data-files-configuration)", "source_file": "hub/datasets.md", "section_heading": "Contents", "char_start": 548, "char_end": 907, "token_estimate": 89, "prev_chunk_id": 1317, "next_chunk_id": null, "url": "https://huggingface.co/docs/hub/datasets", "doc_title": "Datasets" }, { "chunk_id": 1319, "text": "# Spaces\n\n[Hugging Face Spaces](https://huggingface.co/spaces) offer a simple way to host ML demo apps directly on your profile or your organization's profile. This allows you to create your ML portfolio, showcase your projects at conferences or to stakeholders, and work collaboratively with other people in the ML ecosystem.\n\nWe have built-in support for an awesome SDK that let you build cool apps in Python in a matter of minutes: **[Gradio](https://gradio.app/)**, but you can also unlock the whole power of Docker and host an arbitrary Dockerfile. Finally, you can create static Spaces using JavaScript and HTML.\n\nYou'll also be able to upgrade your Space to run [on a GPU or other accelerated hardware](./spaces-gpus). \u26a1\ufe0f", "source_file": "hub/spaces.md", "section_heading": "Spaces", "char_start": 0, "char_end": 729, "token_estimate": 182, "prev_chunk_id": null, "next_chunk_id": 1320, "url": "https://huggingface.co/docs/hub/spaces", "doc_title": "Spaces" }, { "chunk_id": 1320, "text": "## Contents\n\n- [Spaces Overview](./spaces-overview)\n - [Handling Spaces Dependencies](./spaces-dependencies)\n - [Spaces Settings](./spaces-settings)\n - [Using OpenCV in Spaces](./spaces-using-opencv)\n - [Using Spaces for Organization Cards](./spaces-organization-cards)\n - [More ways to create Spaces](./spaces-more-ways-to-create)\n - [Managing Spaces with Github Actions](./spaces-github-actions)\n - [How to Add a Space to ArXiv](./spaces-add-to-arxiv)\n- [Spaces Dev Mode](./spaces-dev-mode)\n- [Spaces GPU Upgrades](./spaces-gpus)\n- [Spaces Disk Usage & Storage](./spaces-storage)\n- [Gradio Spaces](./spaces-sdks-gradio)\n- [Docker Spaces](./spaces-sdks-docker)\n- [Static HTML Spaces](./spaces-sdks-static)\n- [Custom Python Spaces](./spaces-sdks-python)\n- [Embed your Space](./spaces-embed)\n- [Run your Space with Docker](./spaces-run-with-docker)\n- [Reference](./spaces-config-reference)\n- [Changelog](./spaces-changelog)", "source_file": "hub/spaces.md", "section_heading": "Contents", "char_start": 731, "char_end": 1660, "token_estimate": 232, "prev_chunk_id": 1319, "next_chunk_id": 1321, "url": "https://huggingface.co/docs/hub/spaces", "doc_title": "Spaces" }, { "chunk_id": 1321, "text": "## Contact\n\nFeel free to ask questions on the [forum](https://discuss.huggingface.co/c/spaces/24) if you need help with making a Space, or if you run into any other issues on the Hub.\n\nIf you're interested in infra challenges, custom demos, advanced GPUs, or something else, please reach out to us by sending an email to **website at huggingface.co**.\n\nYou can also tag us [on Twitter](https://twitter.com/huggingface)! \ud83e\udd17", "source_file": "hub/spaces.md", "section_heading": "Contact", "char_start": 1662, "char_end": 2083, "token_estimate": 105, "prev_chunk_id": 1320, "next_chunk_id": null, "url": "https://huggingface.co/docs/hub/spaces", "doc_title": "Spaces" }, { "chunk_id": 1322, "text": "# Uploading models\n\nTo upload models to the Hub, you'll need to create an account at [Hugging Face](https://huggingface.co/join). Models on the Hub are [Git-based repositories](./repositories), which give you versioning, branches, discoverability and sharing features, integration with dozens of libraries, and more! You have control over what you want to upload to your repository, which could include checkpoints, configs, and any other files.", "source_file": "hub/models-uploading.md", "section_heading": "Uploading models", "char_start": 0, "char_end": 445, "token_estimate": 111, "prev_chunk_id": null, "next_chunk_id": 1323, "url": "https://huggingface.co/docs/hub/models-uploading", "doc_title": "Uploading models" }, { "chunk_id": 1323, "text": "You can link repositories with an individual user, such as [osanseviero/fashion_brands_patterns](https://huggingface.co/osanseviero/fashion_brands_patterns), or with an organization, such as [facebook/bart-large-xsum](https://huggingface.co/facebook/bart-large-xsum). Organizations can collect models related to a company, community, or library! If you choose an organization, the model will be featured on the organization\u2019s page, and every member of the organization will have the ability to contribute to the repository. You can create a new organization [here](https://huggingface.co/organizations/new).\n\n> **_NOTE:_** Models do NOT need to be compatible with the Transformers/Diffusers libraries to get download metrics. Any custom model is supported. Read more below!\n\nThere are several ways to upload models for them to be nicely integrated into the Hub and get [download metrics](models-download-stats), described below.", "source_file": "hub/models-uploading.md", "section_heading": "Uploading models", "char_start": 447, "char_end": 1375, "token_estimate": 232, "prev_chunk_id": 1322, "next_chunk_id": 1324, "url": "https://huggingface.co/docs/hub/models-uploading", "doc_title": "Uploading models" }, { "chunk_id": 1324, "text": "- In case your model is designed for a library that has [built-in support](#upload-from-a-library-with-built-in-support), you can use the methods provided by the library. Custom models that use `trust_remote_code=True` can also leverage these methods.\n- In case your model is a custom PyTorch model, one can leverage the [`PyTorchModelHubMixin` class](#upload-a-pytorch-model-using-huggingfacehub) as it allows to add `from_pretrained`, `push_to_hub` to any `nn.Module` class, just like models in the Transformers, Diffusers and Timm libraries.\n- In addition to programmatic uploads, you can always use the [web interface](#using-the-web-interface) or [the git command line](#using-git).\n\nOnce your model is uploaded, we suggest adding a [Model Card](./model-cards) to your repo to document your model and make it more discoverable.", "source_file": "hub/models-uploading.md", "section_heading": "Uploading models", "char_start": 1377, "char_end": 2209, "token_estimate": 208, "prev_chunk_id": 1323, "next_chunk_id": 1325, "url": "https://huggingface.co/docs/hub/models-uploading", "doc_title": "Uploading models" }, { "chunk_id": 1325, "text": "Example [repository](https://huggingface.co/LiheYoung/depth_anything_vitl14) that leverages [PyTorchModelHubMixin](#upload-a-pytorch-model-using-huggingfacehub). Downloads are shown on the right.", "source_file": "hub/models-uploading.md", "section_heading": "Uploading models", "char_start": 2212, "char_end": 2407, "token_estimate": 49, "prev_chunk_id": 1324, "next_chunk_id": 1326, "url": "https://huggingface.co/docs/hub/models-uploading", "doc_title": "Uploading models" }, { "chunk_id": 1326, "text": "## Using the web interface\n\nTo create a brand new model repository, visit [huggingface.co/new](http://huggingface.co/new). Then follow these steps:\n\n1. In the \"Files and versions\" tab, select \"Add File\" and specify \"Upload File\":\n\n2. From there, select a file from your computer to upload and leave a helpful commit message to know what you are uploading:\n\n3. Afterwards, click **Commit changes** to upload your model to the Hub!\n\n4. Inspect files and history\n\nYou can check your repository with all the recently added files!\n\nThe UI allows you to explore the model files and commits and to see the diff introduced by each commit:\n\n5. Add metadata\n\nYou can add metadata to your model card. You can specify:\n* the type of task this model is for, enabling widgets and Inference Providers.\n* the used library (`transformers`, `spaCy`, etc.)\n* the language\n* the dataset\n* metrics\n* license\n* a lot more!\n\nRead more about model tags [here](./model-cards#model-card-metadata).\n\n6. Add TensorBoard traces", "source_file": "hub/models-uploading.md", "section_heading": "Using the web interface", "char_start": 2409, "char_end": 3407, "token_estimate": 249, "prev_chunk_id": 1325, "next_chunk_id": 1327, "url": "https://huggingface.co/docs/hub/models-uploading", "doc_title": "Uploading models" }, { "chunk_id": 1327, "text": "Any repository that contains TensorBoard traces (filenames that contain `tfevents`) is categorized with the [`TensorBoard` tag](https://huggingface.co/models?filter=tensorboard). As a convention, we suggest that you save traces under the `runs/` subfolder. The \"Training metrics\" tab then makes it easy to review charts of the logged variables, like the loss or the accuracy.\n\nModels trained with \ud83e\udd17 Transformers will generate [TensorBoard traces](https://huggingface.co/docs/transformers/main_classes/callback#transformers.integrations.TensorBoardCallback) by default if [`tensorboard`](https://pypi.org/project/tensorboard/) is installed.", "source_file": "hub/models-uploading.md", "section_heading": "Using the web interface", "char_start": 3409, "char_end": 4048, "token_estimate": 159, "prev_chunk_id": 1326, "next_chunk_id": 1328, "url": "https://huggingface.co/docs/hub/models-uploading", "doc_title": "Uploading models" }, { "chunk_id": 1328, "text": "## Upload from a library with built-in support\n\nFirst check if your model is from a library that has built-in support to push to/load from the Hub, like Transformers, Diffusers, Timm, Asteroid, etc.: https://huggingface.co/docs/hub/models-libraries. Below we'll show how easy this is for a library like Transformers:\n\n```python\nfrom transformers import BertConfig, BertModel\n\nconfig = BertConfig()\nmodel = BertModel(config)\n\nmodel.push_to_hub(\"nielsr/my-awesome-bert-model\")", "source_file": "hub/models-uploading.md", "section_heading": "Upload from a library with built-in support", "char_start": 4050, "char_end": 4524, "token_estimate": 118, "prev_chunk_id": 1327, "next_chunk_id": 1329, "url": "https://huggingface.co/docs/hub/models-uploading", "doc_title": "Uploading models" }, { "chunk_id": 1329, "text": "# reload\nmodel = BertModel.from_pretrained(\"nielsr/my-awesome-bert-model\")\n```\n\nSome libraries, like Transformers, support loading [code from the Hub](https://huggingface.co/docs/transformers/custom_models). This is a way to make your model work with Transformers using the `trust_remote_code=True` flag. You may want to consider this option instead of a full-fledged library integration.", "source_file": "hub/models-uploading.md", "section_heading": "reload", "char_start": 4526, "char_end": 4914, "token_estimate": 97, "prev_chunk_id": 1328, "next_chunk_id": 1330, "url": "https://huggingface.co/docs/hub/models-uploading", "doc_title": "Uploading models" }, { "chunk_id": 1330, "text": "## Upload a PyTorch model using huggingface_hub\n\nIn case your model is a (custom) PyTorch model, you can leverage the `PyTorchModelHubMixin` [class](https://huggingface.co/docs/huggingface_hub/package_reference/mixins#huggingface_hub.PyTorchModelHubMixin) available in the [huggingface_hub](https://github.com/huggingface/huggingface_hub) Python library. It is a minimal class which adds `from_pretrained` and `push_to_hub` capabilities to any `nn.Module`, along with download metrics.\n\nHere is how to use it (assuming you have run `pip install huggingface_hub`):\n\n```python\nimport torch\nimport torch.nn as nn\nfrom huggingface_hub import PyTorchModelHubMixin", "source_file": "hub/models-uploading.md", "section_heading": "Upload a PyTorch model using huggingface_hub", "char_start": 4916, "char_end": 5574, "token_estimate": 164, "prev_chunk_id": 1329, "next_chunk_id": 1331, "url": "https://huggingface.co/docs/hub/models-uploading", "doc_title": "Uploading models" }, { "chunk_id": 1331, "text": "class MyModel(\n nn.Module,\n PyTorchModelHubMixin, \n # optionally, you can add metadata which gets pushed to the model card\n repo_url=\"your-repo-url\",\n pipeline_tag=\"text-to-image\",\n license=\"mit\",\n):\n def __init__(self, num_channels: int, hidden_size: int, num_classes: int):\n super().__init__()\n self.param = nn.Parameter(torch.rand(num_channels, hidden_size))\n self.linear = nn.Linear(hidden_size, num_classes)\n\n def forward(self, x):\n return self.linear(x + self.param)", "source_file": "hub/models-uploading.md", "section_heading": "Upload a PyTorch model using huggingface_hub", "char_start": 5576, "char_end": 6100, "token_estimate": 131, "prev_chunk_id": 1330, "next_chunk_id": 1332, "url": "https://huggingface.co/docs/hub/models-uploading", "doc_title": "Uploading models" }, { "chunk_id": 1332, "text": "# create model\nconfig = {\"num_channels\": 3, \"hidden_size\": 32, \"num_classes\": 10}\nmodel = MyModel(**config)", "source_file": "hub/models-uploading.md", "section_heading": "create model", "char_start": 6102, "char_end": 6209, "token_estimate": 26, "prev_chunk_id": 1331, "next_chunk_id": 1333, "url": "https://huggingface.co/docs/hub/models-uploading", "doc_title": "Uploading models" }, { "chunk_id": 1333, "text": "# save locally\nmodel.save_pretrained(\"my-awesome-model\")", "source_file": "hub/models-uploading.md", "section_heading": "save locally", "char_start": 6211, "char_end": 6267, "token_estimate": 14, "prev_chunk_id": 1332, "next_chunk_id": 1334, "url": "https://huggingface.co/docs/hub/models-uploading", "doc_title": "Uploading models" }, { "chunk_id": 1334, "text": "# push to the hub\nmodel.push_to_hub(\"your-hf-username/my-awesome-model\")", "source_file": "hub/models-uploading.md", "section_heading": "push to the hub", "char_start": 6269, "char_end": 6341, "token_estimate": 18, "prev_chunk_id": 1333, "next_chunk_id": 1335, "url": "https://huggingface.co/docs/hub/models-uploading", "doc_title": "Uploading models" }, { "chunk_id": 1335, "text": "# reload\nmodel = MyModel.from_pretrained(\"your-hf-username/my-awesome-model\")\n```\n\nAs you can see, the only requirement is that your model inherits from `PyTorchModelHubMixin`. All instance attributes will be automatically serialized to a `config.json` file. Note that the `init` method can only take arguments which are JSON serializable. Python dataclasses are supported.\n\nThis comes with automated download metrics, meaning that you'll be able to see how many times the model is downloaded, the same way they are available for models integrated natively in the Transformers, Diffusers or Timm libraries. With this mixin class, each separate checkpoint is stored on the Hub in a single repository consisting of 2 files:", "source_file": "hub/models-uploading.md", "section_heading": "reload", "char_start": 6343, "char_end": 7064, "token_estimate": 180, "prev_chunk_id": 1334, "next_chunk_id": 1336, "url": "https://huggingface.co/docs/hub/models-uploading", "doc_title": "Uploading models" }, { "chunk_id": 1336, "text": "- a `pytorch_model.bin` or `model.safetensors` file containing the weights\n- a `config.json` file which is a serialized version of the model configuration. This class is used for counting download metrics: everytime a user calls `from_pretrained` to load a `config.json`, the count goes up by one. See [this guide](https://huggingface.co/docs/hub/models-download-stats) regarding automated download metrics.\n\nIt's recommended to add a model card to each checkpoint so that people can read what the model is about, have a link to the paper, etc.\n\nVisit [the huggingface_hub's documentation](https://huggingface.co/docs/huggingface_hub/guides/integrations) to learn more.\n\nAlternatively, one can also simply programmatically upload files or folders to the hub: https://huggingface.co/docs/huggingface_hub/guides/upload.", "source_file": "hub/models-uploading.md", "section_heading": "reload", "char_start": 7066, "char_end": 7883, "token_estimate": 204, "prev_chunk_id": 1335, "next_chunk_id": 1337, "url": "https://huggingface.co/docs/hub/models-uploading", "doc_title": "Uploading models" }, { "chunk_id": 1337, "text": "## Using Git\n\nFinally, since model repos are just Git repositories, you can also use Git to push your model files to the Hub. Follow the guide on [Getting Started with Repositories](repositories-getting-started#terminal) to learn about using the `git` CLI to commit and push your models.", "source_file": "hub/models-uploading.md", "section_heading": "Using Git", "char_start": 7885, "char_end": 8172, "token_estimate": 71, "prev_chunk_id": 1336, "next_chunk_id": null, "url": "https://huggingface.co/docs/hub/models-uploading", "doc_title": "Uploading models" }, { "chunk_id": 1338, "text": "# Downloading models", "source_file": "hub/models-downloading.md", "section_heading": "Downloading models", "char_start": 0, "char_end": 20, "token_estimate": 5, "prev_chunk_id": null, "next_chunk_id": 1339, "url": "https://huggingface.co/docs/hub/models-downloading", "doc_title": "Downloading models" }, { "chunk_id": 1339, "text": "## Integrated libraries\n\nIf a model on the Hub is tied to a [supported library](./models-libraries), loading the model can be done in just a few lines. For information on accessing the model, you can click on the \"Use in _Library_\" button on the model page to see how to do so. For example, `distilbert/distilgpt2` shows how to do so with \ud83e\udd17 Transformers below.", "source_file": "hub/models-downloading.md", "section_heading": "Integrated libraries", "char_start": 22, "char_end": 382, "token_estimate": 90, "prev_chunk_id": 1338, "next_chunk_id": 1340, "url": "https://huggingface.co/docs/hub/models-downloading", "doc_title": "Downloading models" }, { "chunk_id": 1340, "text": "## Using the Hugging Face Client Library\n\nYou can use the [`huggingface_hub`](https://github.com/huggingface/huggingface_hub) library to create, delete, update and retrieve information from repos. For example, to download the `HuggingFaceH4/zephyr-7b-beta` model from the command line, run\n```bash\nhf download HuggingFaceH4/zephyr-7b-beta\n```\nSee the [CLI download documentation](https://huggingface.co/docs/huggingface_hub/en/guides/cli#download-an-entire-repository) for more information.\n\nYou can also integrate this into your own library. For example, you can quickly load a Scikit-learn model with a few lines.\n```py\nfrom huggingface_hub import hf_hub_download\nimport joblib\n\nREPO_ID = \"YOUR_REPO_ID\"\nFILENAME = \"sklearn_model.joblib\"\n\nmodel = joblib.load(\n hf_hub_download(repo_id=REPO_ID, filename=FILENAME)\n)\n```", "source_file": "hub/models-downloading.md", "section_heading": "Using the Hugging Face Client Library", "char_start": 384, "char_end": 1207, "token_estimate": 205, "prev_chunk_id": 1339, "next_chunk_id": 1341, "url": "https://huggingface.co/docs/hub/models-downloading", "doc_title": "Downloading models" }, { "chunk_id": 1341, "text": "## Using Git\n\nSince all models on the Model Hub are Xet-backed Git repositories, you can clone the models locally by [installing git-xet](./xet/using-xet-storage#git-xet) and running:\n\n```bash\ngit xet install\ngit lfs install\ngit clone git@hf.co: # example: git clone git@hf.co:bigscience/bloom\n```\n\nIf you have write-access to the particular model repo, you'll also have the ability to commit and push revisions to the model.\n\nAdd your SSH public key to [your user settings](https://huggingface.co/settings/keys) to push changes and/or access private repos.", "source_file": "hub/models-downloading.md", "section_heading": "Using Git", "char_start": 1209, "char_end": 1766, "token_estimate": 139, "prev_chunk_id": 1340, "next_chunk_id": 1342, "url": "https://huggingface.co/docs/hub/models-downloading", "doc_title": "Downloading models" }, { "chunk_id": 1342, "text": "## Faster downloads\n\n`hf_xet` is a Rust-based package leveraging the [Xet storage backend](https://huggingface.co/docs/hub/en/xet/index) to optimize file transfers with chunk-based deduplication. By default, `hf_xet` uses **adaptive concurrency** \u2014 it automatically tunes the number of parallel transfer streams based on real-time network conditions, starting conservatively (1 stream) and scaling up to 64 concurrent streams as bandwidth permits.\n\nFor most machines \u2014 including data center environments \u2014 the default settings will already saturate the available network bandwidth. For advanced users on machines with high bandwidth **and at least 64 GB of RAM**, `HF_XET_HIGH_PERFORMANCE=1` raises concurrency bounds and significantly increases memory buffer sizes, which can help when downloading many large files in parallel.\n\n```bash\nHF_XET_HIGH_PERFORMANCE=1 hf download ...\n```", "source_file": "hub/models-downloading.md", "section_heading": "Faster downloads", "char_start": 1768, "char_end": 2651, "token_estimate": 220, "prev_chunk_id": 1341, "next_chunk_id": null, "url": "https://huggingface.co/docs/hub/models-downloading", "doc_title": "Downloading models" }, { "chunk_id": 1343, "text": "# Dataset Cards", "source_file": "hub/datasets-cards.md", "section_heading": "Dataset Cards", "char_start": 0, "char_end": 15, "token_estimate": 3, "prev_chunk_id": null, "next_chunk_id": 1344, "url": "https://huggingface.co/docs/hub/datasets-cards", "doc_title": "Dataset Cards" }, { "chunk_id": 1344, "text": "## What are Dataset Cards?\n\nEach dataset may be documented by the `README.md` file in the repository. This file is called a **dataset card**, and the Hugging Face Hub will render its contents on the dataset's main page. To inform users about how to responsibly use the data, it's a good idea to include information about any potential biases within the dataset. Generally, dataset cards help users understand the contents of the dataset and give context for how the dataset should be used.\n\nYou can also add dataset metadata to your card. The metadata describes important information about a dataset such as its license, language, and size. It also contains tags to help users discover a dataset on the Hub, and [data files configuration](./datasets-manual-configuration) options. Tags are defined in a YAML metadata section at the top of the `README.md` file.", "source_file": "hub/datasets-cards.md", "section_heading": "What are Dataset Cards?", "char_start": 17, "char_end": 877, "token_estimate": 215, "prev_chunk_id": 1343, "next_chunk_id": 1345, "url": "https://huggingface.co/docs/hub/datasets-cards", "doc_title": "Dataset Cards" }, { "chunk_id": 1345, "text": "## Dataset card metadata\n\nA dataset repo will render its README.md as a dataset card. To control how the Hub displays the card, you should create a YAML section in the README file to define some metadata. Start by adding three --- at the top, then include all of the relevant metadata, and close the section with another group of --- like the example below:\n\n```yaml\nlanguage: \n- \"List of ISO 639-1 code for your language\"\n- lang1\n- lang2\npretty_name: \"Pretty Name of the Dataset\"\ntags:\n- tag1\n- tag2\nlicense: \"any valid license identifier\"\ntask_categories:\n- task1\n- task2\n```\n\nThe metadata that you add to the dataset card enables certain interactions on the Hub. For example:\n\n* Allow users to filter and discover datasets at https://huggingface.co/datasets.\n* If you choose a license using the keywords listed in the right column of [this table](./repositories-licenses), the license will be displayed on the dataset page.", "source_file": "hub/datasets-cards.md", "section_heading": "Dataset card metadata", "char_start": 879, "char_end": 1805, "token_estimate": 231, "prev_chunk_id": 1344, "next_chunk_id": 1346, "url": "https://huggingface.co/docs/hub/datasets-cards", "doc_title": "Dataset Cards" }, { "chunk_id": 1346, "text": "When creating a README.md file in a dataset repository on the Hub, use Metadata UI to fill the main metadata:\n\nTo see metadata fields, see the detailed [Dataset Card specifications](https://github.com/huggingface/hub-docs/blob/main/datasetcard.md?plain=1).", "source_file": "hub/datasets-cards.md", "section_heading": "Dataset card metadata", "char_start": 0, "char_end": 256, "token_estimate": 64, "prev_chunk_id": 1345, "next_chunk_id": 1347, "url": "https://huggingface.co/docs/hub/datasets-cards", "doc_title": "Dataset Cards" }, { "chunk_id": 1347, "text": "### Dataset card creation guide\n\nFor a step-by-step guide on creating a dataset card, check out the [Create a dataset card](https://huggingface.co/docs/datasets/dataset_card) guide.\n\nReading through existing dataset cards, such as the [ELI5 dataset card](https://huggingface.co/datasets/eli5/blob/main/README.md), is a great way to familiarize yourself with the common conventions.", "source_file": "hub/datasets-cards.md", "section_heading": "Dataset card creation guide", "char_start": 2076, "char_end": 2457, "token_estimate": 95, "prev_chunk_id": 1346, "next_chunk_id": 1348, "url": "https://huggingface.co/docs/hub/datasets-cards", "doc_title": "Dataset Cards" }, { "chunk_id": 1348, "text": "### Linking a Paper\n\nIf the dataset card includes a link to a Paper page (either on HF or an Arxiv abstract/PDF), the Hub will extract the arXiv ID and include it in the dataset tags with the format `arxiv:`. Clicking on the tag will let you:\n\n* Visit the Paper page\n* Filter for other models on the Hub that cite the same paper.\n\nRead more about paper pages [here](./paper-pages).", "source_file": "hub/datasets-cards.md", "section_heading": "Linking a Paper", "char_start": 2459, "char_end": 2840, "token_estimate": 95, "prev_chunk_id": 1347, "next_chunk_id": 1349, "url": "https://huggingface.co/docs/hub/datasets-cards", "doc_title": "Dataset Cards" }, { "chunk_id": 1349, "text": "### Force set a dataset modality\n\nThe Hub will automatically detect the modality of a dataset based on the files it contains (audio, video, geospatial, etc.). If you want to force a specific modality, you can add a tag to the dataset card metadata: `3d`, `audio`, `geospatial`, `image`, `tabular`, `text`, `timeseries`, `video`.\n\nFor example, to force the modality to `audio`, add the following to the dataset card metadata:\n\n```yaml\ntags:\n- audio\n```", "source_file": "hub/datasets-cards.md", "section_heading": "Force set a dataset modality", "char_start": 2842, "char_end": 3293, "token_estimate": 112, "prev_chunk_id": 1348, "next_chunk_id": 1350, "url": "https://huggingface.co/docs/hub/datasets-cards", "doc_title": "Dataset Cards" }, { "chunk_id": 1350, "text": "### Associate a library to the dataset\n\nThe dataset page automatically shows libraries and tools that are able to natively load the dataset, but if you want to show another specific library, you can add a tag to the dataset card metadata: `argilla`, `dask`, `datasets`, `distilabel`, `fiftyone`, `mlcroissant`, `pandas`, `webdataset`. See the [list of supported libraries](https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/src/dataset-libraries.ts) for more information, or to propose to add a new library.\n\nFor example, to associate the `argilla` library to the dataset card, add the following to the dataset card metadata:\n\n```yaml\ntags:\n- argilla\n```", "source_file": "hub/datasets-cards.md", "section_heading": "Associate a library to the dataset", "char_start": 3295, "char_end": 3969, "token_estimate": 168, "prev_chunk_id": 1349, "next_chunk_id": null, "url": "https://huggingface.co/docs/hub/datasets-cards", "doc_title": "Dataset Cards" }, { "chunk_id": 1351, "text": "# Libraries\n\nThe Hub has support for dozens of libraries in the Open Source ecosystem. Thanks to the `huggingface_hub` Python library, it's easy to enable sharing your models on the Hub. The Hub supports many libraries, and we're working on expanding this support. We're happy to welcome to the Hub a set of Open Source libraries that are pushing Machine Learning forward.\n\nThe table below summarizes the supported libraries and their level of integration. Find all our supported libraries in [the model-libraries.ts file](https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/src/model-libraries.ts).", "source_file": "hub/models-libraries.md", "section_heading": "Libraries", "char_start": 0, "char_end": 618, "token_estimate": 154, "prev_chunk_id": null, "next_chunk_id": 1352, "url": "https://huggingface.co/docs/hub/models-libraries", "doc_title": "Libraries" }, { "chunk_id": 1352, "text": "| Library | Description | Inference Providers | Widgets | Download from Hub | Push to Hub |\n|-----------------------------------------------------------------------------|--------------------------------------------------------------------------------------|---|---:|---|---|\n| [Adapters](./adapters) | A unified Transformers add-on for parameter-efficient and modular fine-tuning. | \u2705 | \u2705 | \u2705 | \u2705 |\n| [AllenNLP](./allennlp) | An open-source NLP research library, built on PyTorch. | \u2705 | \u2705 | \u2705 | \u274c |\n| [Asteroid](./asteroid) | PyTorch-based audio source separation toolkit | \u2705 | \u2705 | \u2705 | \u274c |\n| [BERTopic](./bertopic) | BERTopic is a topic modeling library for text and images | \u2705 | \u2705 | \u2705 | \u2705 | \n| [Diffusers](./diffusers) | A modular toolbox for inference and training of diffusion models | \u2705 | \u2705 | \u2705 | \u2705 |\n| [docTR](https://github.com/mindee/doctr) | Models and datasets for OCR-related tasks in PyTorch & TensorFlow | \u2705 | \u2705 | \u2705 | \u274c |\n| [ESPnet](./espnet) | End-to-end speech processing toolkit (e.g. TTS) | \u2705 | \u2705 | \u2705 | \u274c |\n| [fastai](./fastai) | Library to train fast and accurate models with state-of-the-art outputs. | \u2705 | \u2705 | \u2705 | \u2705 |\n| [Keras](./keras) | Open-source multi-backend deep learning framework, with support for JAX, TensorFlow, and PyTorch. | \u274c | \u274c | \u2705 | \u2705 |\n| [KerasNLP](https://keras.io/guides/keras_nlp/upload/) | Natural language processing library built on top of Keras that works natively with TensorFlow, JAX, or PyTorch. | \u274c | \u274c | \u2705 | \u2705 |\n| [TF-Keras](./tf-keras) (legacy) | Legacy library that uses a consistent and simple API to build models leveraging TensorFlow and its ecosystem. | \u274c | \u274c | \u2705 | \u2705 |\n| [Flair](./flair) | Very simple framework for state-of-the-art NLP. | \u2705 | \u2705 | \u2705 | \u2705 |\n| [MBRL-Lib](https://github.com/facebookresearch/mbrl-lib) | PyTorch implementations of MBRL Algorithms. | \u274c | \u274c | \u2705 | \u2705 |\n| [MidiTok](https://github.com/Natooz/MidiTok) | Tokenizers for symbolic music / MIDI files. | \u274c | \u274c | \u2705 | \u2705 |\n| [ML-Agents](./ml-agents) | Enables games and simulations made with Unity to serve as environments for training intelligent agents. | \u274c | \u274c | \u2705 | \u2705 |\n| [MLX](./mlx) | Model training and serving framework on Apple silicon made by Apple. | \u274c | \u274c | \u2705 | \u2705 |\n| [NeMo](https://github.com/NVIDIA/NeMo) | Conversational AI toolkit built for researchers | \u2705 | \u2705 | \u2705 | \u274c |\n| [OpenCLIP](./open_clip) | Library for open-source implementation of OpenAI's CLIP | \u274c | \u274c | \u2705 | \u2705 | \n| [PaddleNLP](./paddlenlp) | Easy-to-use and powerful NLP library built on PaddlePaddle | \u2705 | \u2705 | \u2705 | \u2705 |\n| [PEFT](./peft) | Cutting-edge Parameter Efficient Fine-tuning Library | \u2705 | \u2705 | \u2705 | \u2705 |\n| [Pyannote](https://github.com/pyannote/pyannote-audio) | Neural building blocks for speaker diarization. | \u274c | \u274c | \u2705 | \u274c |\n| [PyCTCDecode](https://github.com/kensho-technologies/pyctcdecode) | Language model supported CTC decoding for speech recognition | \u274c | \u274c | \u2705 | \u274c |\n| [Pythae](https://github.com/clementchadebec/benchmark_VAE) | Unified framework for Generative Autoencoders in Python | \u274c | \u274c | \u2705 | \u2705 |\n| [RL-Baselines3-Zoo](./rl-baselines3-zoo) | Training framework for Reinforcement Learning, using [Stable Baselines3](https://github.com/DLR-RM/stable-baselines3).| \u274c | \u2705 | \u2705 | \u2705 |\n| [Sample Factory](./sample-factory) | Codebase for high throughput asynchronous reinforcement learning. | \u274c | \u2705 | \u2705 | \u2705 |\n| [Sentence Transformers](./sentence-transformers) | Compute dense vector representations for sentences, paragraphs, and images. | \u2705 | \u2705 | \u2705 | \u2705 |\n| [SetFit](./setfit) | Efficient few-shot text classification with Sentence Transformers | \u2705 | \u2705 | \u2705 | \u2705 |\n| [spaCy](./spacy) | Advanced Natural Language Processing in Python and Cython. | \u2705 | \u2705 | \u2705 | \u2705 |\n| [SpanMarker](./span_marker) | Familiar, simple and state-of-the-art Named Entity Recognition. | \u2705 | \u2705 | \u2705 | \u2705 |\n| [Scikit Learn (using skops)](https://skops.readthedocs.io/en/stable/) | Machine Learning in Python. | \u2705 | \u2705 | \u2705 | \u2705 |\n| [Speechbrain](./speechbrain) | A PyTorch Powered Speech Toolkit. | \u2705 | \u2705 | \u2705 | \u274c |\n| [Stable-Baselines3](./stable-baselines3) | Set of reliable implementations of deep reinforcement learning algorithms in PyTorch | \u274c | \u2705 | \u2705 | \u2705 |\n| [TensorFlowTTS](https://github.com/TensorSpeech/TensorFlowTTS) | Real-time state-of-the-art speech synthesis architectures. | \u274c | \u274c | \u2705 | \u274c |\n| [Timm](./timm) | Collection of image models, scripts, pretrained weights, etc. | \u2705 | \u2705 | \u2705 | \u2705 |\n| [Transformers](./transformers) | State-of-the-art Natural Language Processing for PyTorch, TensorFlow, and JAX | \u2705 | \u2705 | \u2705 | \u2705 |\n| [Transformers.js](./transformers-js) | State-of-the-art Machine Learning for the web. Run \ud83e\udd17 Transformers directly in your browser, with no need for a server! | \u274c | \u274c | \u2705 | \u274c |\n| [Unity Sentis](./unity-sentis) | Inference engine for the Unity 3D game engine | \u274c | \u274c | \u274c | \u274c |", "source_file": "hub/models-libraries.md", "section_heading": "Libraries", "char_start": 620, "char_end": 7164, "token_estimate": 1636, "prev_chunk_id": 1351, "next_chunk_id": 1353, "url": "https://huggingface.co/docs/hub/models-libraries", "doc_title": "Libraries" }, { "chunk_id": 1353, "text": "### How can I add support for a new library?\n\nIf you're interested in adding your library, please reach out to us! Read about it in [Adding a Library Guide](./models-adding-libraries).", "source_file": "hub/models-libraries.md", "section_heading": "How can I add support for a new library?", "char_start": 7166, "char_end": 7350, "token_estimate": 46, "prev_chunk_id": 1352, "next_chunk_id": null, "url": "https://huggingface.co/docs/hub/models-libraries", "doc_title": "Libraries" }, { "chunk_id": 1354, "text": "# Security\n\nThe Hugging Face Hub offers several security features to ensure that your code and data are secure. Beyond offering [private repositories](./repositories-settings#private-repositories) for models, datasets, and Spaces, the Hub supports access tokens, resource groups, MFA, commit signatures, malware scanning, and more.\n\nHugging Face is GDPR compliant. If a contract or specific data storage is something you'll need, we recommend taking a look at our [Team & Enterprise Support](https://huggingface.co/support). Hugging Face can also offer Business Associate Addendums or GDPR data processing agreements through an [Enterprise Plan](https://huggingface.co/pricing).\n\nHugging Face is also [SOC2 Type 2 certified](https://us.aicpa.org/interestareas/frc/assuranceadvisoryservices/aicpasoc2report.html), meaning we provide security certification to our customers and actively monitor and patch any security weaknesses.\n\nFor any other security questions, please feel free to send us an email at security@huggingface.co.", "source_file": "hub/security.md", "section_heading": "Security", "char_start": 0, "char_end": 1027, "token_estimate": 256, "prev_chunk_id": null, "next_chunk_id": 1355, "url": "https://huggingface.co/docs/hub/security", "doc_title": "Security" }, { "chunk_id": 1355, "text": "## Contents\n\n- [User Access Tokens](./security-tokens)\n- [Two-Factor Authentication (2FA)](./security-2fa)\n- [Git over SSH](./security-git-ssh)\n- [Signing commits with GPG](./security-gpg)\n- [Single Sign-On (SSO)](./security-sso)\n- [Advanced Access Control (Resource Groups)](./security-resource-groups)\n- [Malware Scanning](./security-malware)\n- [Pickle Scanning](./security-pickle)\n- [Secrets Scanning](./security-secrets)\n- [Third-party scanner: Protect AI](./security-protectai)\n- [Third-party scanner: JFrog](./security-jfrog)", "source_file": "hub/security.md", "section_heading": "Contents", "char_start": 1030, "char_end": 1561, "token_estimate": 132, "prev_chunk_id": 1354, "next_chunk_id": null, "url": "https://huggingface.co/docs/hub/security", "doc_title": "Security" } ]