# embeddings_queue

created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 2e2f677b-bcdf-4ea6-9101-fcc679d8470e
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"2e2f677b-bcdf-4ea6-9101-fcc679d8470e\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_memory_anatomy\", \"title\": \"Model training anatomy\", \"tokens\": 2516, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"dd960067-f047-4064-a614-0c4fb3b411f9\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_memory_anatomy\", \"title\": \"Model training anatomy\", \"tokens\": 2516, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"13c1d1df5bd4f7d976e9a09a204c3ffea3813736bd49565008bda2dd6f1fc03d\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"489a3907-4c70-438f-9b16-47bdc0132b83\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_memory_anatomy\", \"title\": \"Model training anatomy\", \"tokens\": 2516, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"70d9b744470facac5683ba1b9c8b619954496285fb913d824bc3401aa314ea8c\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"f003317a-a2bd-4b43-88de-af649a1834da\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"23ced0273f9b27cf845b683a4943362524ccd82cc5bd4ee3b70ac79b0905b1f0\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 1607, \"end_char_idx\": 4120, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "dd960067-f047-4064-a614-0c4fb3b411f9", "doc_id": "dd960067-f047-4064-a614-0c4fb3b411f9", "ref_doc_id": "dd960067-f047-4064-a614-0c4fb3b411f9", "chroma:document": "```py\n>>> import numpy as np\n>>> from datasets import Dataset\n\n\n>>> seq_len, dataset_size = 512, 512\n>>> dummy_data = {\n...     \"input_ids\": np.random.randint(100, 30000, (dataset_size, seq_len)),\n...     \"labels\": np.random.randint(0, 1, (dataset_size)),\n... }\n>>> ds = Dataset.from_dict(dummy_data)\n>>> ds.set_format(\"pt\")\n```\n\nTo print summary statistics for the GPU utilization and the training run with the [`Trainer`] we define two helper functions:\n\n```py\n>>> from pynvml import *\n\n\n>>> def print_gpu_utilization():\n...     nvmlInit()\n...     handle = nvmlDeviceGetHandleByIndex(0)\n...     info = nvmlDeviceGetMemoryInfo(handle)\n...     print(f\"GPU memory occupied: {info.used//1024**2} MB.\")\n\n\n>>> def print_summary(result):\n...     print(f\"Time: {result.metrics['train_runtime']:.2f}\")\n...     print(f\"Samples/second: {result.metrics['train_samples_per_second']:.2f}\")\n...     print_gpu_utilization()\n```\n\nLet's verify that we start with a free GPU memory:\n\n```py\n>>> print_gpu_utilization()\nGPU memory occupied: 0 MB.\n```\n\nThat looks good: the GPU memory is not occupied as we would expect before we load any models. If that's not the case on \nyour machine make sure to stop all processes that are using GPU memory. However, not all free GPU memory can be used by \nthe user. When a model is loaded to the GPU the kernels are also loaded, which can take up 1-2GB of memory. To see how \nmuch it is we load a tiny tensor into the GPU which triggers the kernels to be loaded as well.\n\n```py\n>>> import torch\n\n\n>>> torch.ones((1, 1)).to(\"cuda\")\n>>> print_gpu_utilization()\nGPU memory occupied: 1343 MB.\n```\n\nWe see that the kernels alone take up 1.3GB of GPU memory. Now let's see how much space the model uses.\n\n## Load Model\n\nFirst, we load the `google-bert/bert-large-uncased` model. We load the model weights directly to the GPU so that we can check \nhow much space just the weights use.\n\n\n```py\n>>> from transformers import AutoModelForSequenceClassification\n\n\n>>> model = AutoModelForSequenceClassification.from_pretrained(\"google-bert/bert-large-uncased\").to(\"cuda\")\n>>> print_gpu_utilization()\nGPU memory occupied: 2631 MB.\n```\n\nWe can see that the model weights alone take up 1.3 GB of GPU memory. The exact number depends on the specific \nGPU you are using. Note that on newer GPUs a model can sometimes take up more space since the weights are loaded in an \noptimized fashion that speeds up the usage of the model. Now we can also quickly check if we get the same result \nas with `nvidia-smi` CLI:"}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: f003317a-a2bd-4b43-88de-af649a1834da
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"f003317a-a2bd-4b43-88de-af649a1834da\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_memory_anatomy\", \"title\": \"Model training anatomy\", \"tokens\": 2516, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"dd960067-f047-4064-a614-0c4fb3b411f9\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_memory_anatomy\", \"title\": \"Model training anatomy\", \"tokens\": 2516, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"13c1d1df5bd4f7d976e9a09a204c3ffea3813736bd49565008bda2dd6f1fc03d\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"2e2f677b-bcdf-4ea6-9101-fcc679d8470e\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_memory_anatomy\", \"title\": \"Model training anatomy\", \"tokens\": 2516, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"eb0495ecb28a854c5d1f26501604f3769baea895ce5f629b13fde0b62058607c\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"df6412f0-f686-47b8-bd02-fc652e4cf1a3\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"1566cacb2f23c92f1dfe7fbc0bf6ef2aa26ed03b0885c23d2bfbf941e4e279d4\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 3123, \"end_char_idx\": 6477, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "dd960067-f047-4064-a614-0c4fb3b411f9", "doc_id": "dd960067-f047-4064-a614-0c4fb3b411f9", "ref_doc_id": "dd960067-f047-4064-a614-0c4fb3b411f9", "chroma:document": ">>> torch.ones((1, 1)).to(\"cuda\")\n>>> print_gpu_utilization()\nGPU memory occupied: 1343 MB.\n```\n\nWe see that the kernels alone take up 1.3GB of GPU memory. Now let's see how much space the model uses.\n\n## Load Model\n\nFirst, we load the `google-bert/bert-large-uncased` model. We load the model weights directly to the GPU so that we can check \nhow much space just the weights use.\n\n\n```py\n>>> from transformers import AutoModelForSequenceClassification\n\n\n>>> model = AutoModelForSequenceClassification.from_pretrained(\"google-bert/bert-large-uncased\").to(\"cuda\")\n>>> print_gpu_utilization()\nGPU memory occupied: 2631 MB.\n```\n\nWe can see that the model weights alone take up 1.3 GB of GPU memory. The exact number depends on the specific \nGPU you are using. Note that on newer GPUs a model can sometimes take up more space since the weights are loaded in an \noptimized fashion that speeds up the usage of the model. Now we can also quickly check if we get the same result \nas with `nvidia-smi` CLI:\n\n\n```bash\nnvidia-smi\n```\n\n```bash\nTue Jan 11 08:58:05 2022\n+-----------------------------------------------------------------------------+\n| NVIDIA-SMI 460.91.03    Driver Version: 460.91.03    CUDA Version: 11.2     |\n|-------------------------------+----------------------+----------------------+\n| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n|                               |                      |               MIG M. |\n|===============================+======================+======================|\n|   0  Tesla V100-SXM2...  On   | 00000000:00:04.0 Off |                    0 |\n| N/A   37C    P0    39W / 300W |   2631MiB / 16160MiB |      0%      Default |\n|                               |                      |                  N/A |\n+-------------------------------+----------------------+----------------------+\n\n+-----------------------------------------------------------------------------+\n| Processes:                                                                  |\n|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n|        ID   ID                                                   Usage      |\n|=============================================================================|\n|    0   N/A  N/A      3721      C   ...nvs/codeparrot/bin/python     2629MiB |\n+-----------------------------------------------------------------------------+\n```\n\nWe get the same number as before and you can also see that we are using a V100 GPU with 16GB of memory. So now we can \nstart training the model and see how the GPU memory consumption changes. First, we set up a few standard training \narguments:\n\n```py\ndefault_args = {\n    \"output_dir\": \"tmp\",\n    \"eval_strategy\": \"steps\",\n    \"num_train_epochs\": 1,\n    \"log_level\": \"error\",\n    \"report_to\": \"none\",\n}\n```\n\n<Tip>\n\n If you plan to run multiple experiments, in order to properly clear the memory between experiments, restart the Python \n kernel between experiments.\n\n</Tip>\n\n## Memory utilization at vanilla training\n\nLet's use the [`Trainer`] and train the model without using any GPU performance optimization techniques and a batch size of 4:\n\n```py\n>>> from transformers import TrainingArguments, Trainer, logging\n\n>>> logging.set_verbosity_error()"}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: df6412f0-f686-47b8-bd02-fc652e4cf1a3
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"df6412f0-f686-47b8-bd02-fc652e4cf1a3\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_memory_anatomy\", \"title\": \"Model training anatomy\", \"tokens\": 2516, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"dd960067-f047-4064-a614-0c4fb3b411f9\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_memory_anatomy\", \"title\": \"Model training anatomy\", \"tokens\": 2516, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"13c1d1df5bd4f7d976e9a09a204c3ffea3813736bd49565008bda2dd6f1fc03d\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"f003317a-a2bd-4b43-88de-af649a1834da\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_memory_anatomy\", \"title\": \"Model training anatomy\", \"tokens\": 2516, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"794a406bf0cd4f83901fcce966b84bd322ceca9b1d8495650652ee717530b3f7\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"8203fa41-ce10-4848-abbb-a745d69118f7\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"ce3bd0a4349584d623b0611e962a92bb7ab63b06c0f5212df274e862e9a4bcaf\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 6480, \"end_char_idx\": 8220, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "dd960067-f047-4064-a614-0c4fb3b411f9", "doc_id": "dd960067-f047-4064-a614-0c4fb3b411f9", "ref_doc_id": "dd960067-f047-4064-a614-0c4fb3b411f9", "chroma:document": ">>> training_args = TrainingArguments(per_device_train_batch_size=4, **default_args)\n>>> trainer = Trainer(model=model, args=training_args, train_dataset=ds)\n>>> result = trainer.train()\n>>> print_summary(result)\n```\n\n```\nTime: 57.82\nSamples/second: 8.86\nGPU memory occupied: 14949 MB.\n```\n\nWe see that already a relatively small batch size almost fills up our GPU's entire memory. However, a larger batch size \ncan often result in faster model convergence or better end performance. So ideally we want to tune the batch size to our\nmodel's needs and not to the GPU limitations. What's interesting is that we use much more memory than the size of the model. \nTo understand a bit better why this is the case let's have a look at a model's operations and memory needs.\n\n## Anatomy of Model's Operations\n\nTransformers architecture includes 3 main groups of operations grouped below by compute-intensity.\n\n1. **Tensor Contractions**\n\n    Linear layers and components of Multi-Head Attention all do batched **matrix-matrix multiplications**. These operations are the most compute-intensive part of training a transformer.\n\n2. **Statistical Normalizations**\n\n    Softmax and layer normalization are less compute-intensive than tensor contractions, and involve one or more **reduction operations**, the result of which is then applied via a map.\n\n3. **Element-wise Operators**\n\n    These are the remaining operators: **biases, dropout, activations, and residual connections**. These are the least compute-intensive operations.\n\nThis knowledge can be helpful to know when analyzing performance bottlenecks.\n\nThis summary is derived from [Data Movement Is All You Need: A Case Study on Optimizing Transformers 2020](https://arxiv.org/abs/2007.00072)"}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 8203fa41-ce10-4848-abbb-a745d69118f7
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"8203fa41-ce10-4848-abbb-a745d69118f7\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_memory_anatomy\", \"title\": \"Model training anatomy\", \"tokens\": 2516, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"dd960067-f047-4064-a614-0c4fb3b411f9\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_memory_anatomy\", \"title\": \"Model training anatomy\", \"tokens\": 2516, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"13c1d1df5bd4f7d976e9a09a204c3ffea3813736bd49565008bda2dd6f1fc03d\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"df6412f0-f686-47b8-bd02-fc652e4cf1a3\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_memory_anatomy\", \"title\": \"Model training anatomy\", \"tokens\": 2516, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"0829a9f4370bdd0facadd507bdc0b91bc5faa1915e6ad1c4abf2a1e636f8c5ad\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 6480, \"end_char_idx\": 11390, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "dd960067-f047-4064-a614-0c4fb3b411f9", "doc_id": "dd960067-f047-4064-a614-0c4fb3b411f9", "ref_doc_id": "dd960067-f047-4064-a614-0c4fb3b411f9", "chroma:document": ">>> training_args = TrainingArguments(per_device_train_batch_size=4, **default_args)\n>>> trainer = Trainer(model=model, args=training_args, train_dataset=ds)\n>>> result = trainer.train()\n>>> print_summary(result)\n```\n\n```\nTime: 57.82\nSamples/second: 8.86\nGPU memory occupied: 14949 MB.\n```\n\nWe see that already a relatively small batch size almost fills up our GPU's entire memory. However, a larger batch size \ncan often result in faster model convergence or better end performance. So ideally we want to tune the batch size to our\nmodel's needs and not to the GPU limitations. What's interesting is that we use much more memory than the size of the model. \nTo understand a bit better why this is the case let's have a look at a model's operations and memory needs.\n\n## Anatomy of Model's Operations\n\nTransformers architecture includes 3 main groups of operations grouped below by compute-intensity.\n\n1. **Tensor Contractions**\n\n    Linear layers and components of Multi-Head Attention all do batched **matrix-matrix multiplications**. These operations are the most compute-intensive part of training a transformer.\n\n2. **Statistical Normalizations**\n\n    Softmax and layer normalization are less compute-intensive than tensor contractions, and involve one or more **reduction operations**, the result of which is then applied via a map.\n\n3. **Element-wise Operators**\n\n    These are the remaining operators: **biases, dropout, activations, and residual connections**. These are the least compute-intensive operations.\n\nThis knowledge can be helpful to know when analyzing performance bottlenecks.\n\nThis summary is derived from [Data Movement Is All You Need: A Case Study on Optimizing Transformers 2020](https://arxiv.org/abs/2007.00072)\n\n\n## Anatomy of Model's Memory\n\nWe've seen that training the model uses much more memory than just putting the model on the GPU. This is because there \nare many components during training that use GPU memory. The components on GPU memory are the following:\n\n1. model weights\n2. optimizer states\n3. gradients\n4. forward activations saved for gradient computation\n5. temporary buffers\n6. functionality-specific memory\n\nA typical model trained in mixed precision with AdamW requires 18 bytes per model parameter plus activation memory. For \ninference there are no optimizer states and gradients, so we can subtract those. And thus we end up with 6 bytes per \nmodel parameter for mixed precision inference, plus activation memory.\n\nLet's look at the details.\n\n**Model Weights:**\n\n- 4 bytes * number of parameters for fp32 training\n- 6 bytes * number of parameters for mixed precision training (maintains a model in fp32 and one in fp16 in memory)\n\n**Optimizer States:**\n\n- 8 bytes * number of parameters for normal AdamW (maintains 2 states)\n- 2 bytes * number of parameters for 8-bit AdamW optimizers like [bitsandbytes](https://github.com/TimDettmers/bitsandbytes)\n- 4 bytes * number of parameters for optimizers like SGD with momentum (maintains only 1 state)\n\n**Gradients**\n\n- 4 bytes * number of parameters for either fp32 or mixed precision training (gradients are always kept in fp32)\n\n**Forward Activations**\n\n- size depends on many factors, the key ones being sequence length, hidden size and batch size.\n\nThere are the input and output that are being passed and returned by the forward and the backward functions and the \nforward activations saved for gradient computation.\n\n**Temporary Memory**\n\nAdditionally, there are all kinds of temporary variables which get released once the calculation is done, but in the \nmoment these could require additional memory and could push to OOM. Therefore, when coding it's crucial to think \nstrategically about such temporary variables and sometimes to explicitly free those as soon as they are no longer needed.\n\n**Functionality-specific memory**\n\nThen, your software could have special memory needs. For example, when generating text using beam search, the software \nneeds to maintain multiple copies of inputs and outputs.\n\n**`forward` vs `backward` Execution Speed**\n\nFor convolutions and linear layers there are 2x flops in the backward compared to the forward, which generally translates \ninto ~2x slower (sometimes more, because sizes in the backward tend to be more awkward). Activations are usually \nbandwidth-limited, and it\u2019s typical for an activation to have to read more data in the backward than in the forward \n(e.g. activation forward reads once, writes once, activation backward reads twice, gradOutput and output of the forward, \nand writes once, gradInput).\n\nAs you can see, there are potentially a few places where we could save GPU memory or speed up operations. \nNow that you understand what affects GPU utilization and computation speed, refer to \nthe [Methods and tools for efficient training on a single GPU](perf_train_gpu_one) documentation page to learn about \nperformance optimization techniques."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 3d52a79e-41ec-478a-8460-aa6ef8e1f6a6
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perplexity", "title": "Perplexity of fixed-length models", "tokens": 1903, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"3d52a79e-41ec-478a-8460-aa6ef8e1f6a6\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perplexity\", \"title\": \"Perplexity of fixed-length models\", \"tokens\": 1903, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"0187f108-be22-444b-a494-a0c549691954\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perplexity\", \"title\": \"Perplexity of fixed-length models\", \"tokens\": 1903, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"c29ba1f258b9e32a5b6f976fff7045260dca085781f1e2dff67156b969945dc5\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"3b518f4b-2d4e-4f6e-b29b-efaefeb08537\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"349273f6595ed9a52b59bc0c7e6170d465dee7e40a42eb62ca7e02927db7b804\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 0, \"end_char_idx\": 3254, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "0187f108-be22-444b-a494-a0c549691954", "doc_id": "0187f108-be22-444b-a494-a0c549691954", "ref_doc_id": "0187f108-be22-444b-a494-a0c549691954", "chroma:document": "# Perplexity of fixed-length models\n\n[[open-in-colab]]\n\nPerplexity (PPL) is one of the most common metrics for evaluating language models. Before diving in, we should note\nthat the metric applies specifically to classical language models (sometimes called autoregressive or causal language\nmodels) and is not well defined for masked language models like BERT (see [summary of the models](model_summary)).\n\nPerplexity is defined as the exponentiated average negative log-likelihood of a sequence. If we have a tokenized\nsequence \\\\(X = (x_0, x_1, \\dots, x_t)\\\\), then the perplexity of \\\\(X\\\\) is,\n\n$$\\text{PPL}(X) = \\exp \\left\\{ {-\\frac{1}{t}\\sum_i^t \\log p_\\theta (x_i|x_{<i}) } \\right\\}$$\n\nwhere \\\\(\\log p_\\theta (x_i|x_{<i})\\\\) is the log-likelihood of the ith token conditioned on the preceding tokens \\\\(x_{<i}\\\\) according to our model. Intuitively, it can be thought of as an evaluation of the model's ability to predict uniformly among the set of specified tokens in a corpus. Importantly, this means that the tokenization procedure has a direct impact on a model's perplexity which should always be taken into consideration when comparing different models.\n\nThis is also equivalent to the exponentiation of the cross-entropy between the data and model predictions. For more\nintuition about perplexity and its relationship to Bits Per Character (BPC) and data compression, check out this\n[fantastic blog post on The Gradient](https://thegradient.pub/understanding-evaluation-metrics-for-language-models/).\n\n## Calculating PPL with fixed-length models\n\nIf we weren't limited by a model's context size, we would evaluate the model's perplexity by autoregressively\nfactorizing a sequence and conditioning on the entire preceding subsequence at each step, as shown below.\n\n<img width=\"600\" alt=\"Full decomposition of a sequence with unlimited context length\" src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/ppl_full.gif\"/>\n\nWhen working with approximate models, however, we typically have a constraint on the number of tokens the model can\nprocess. The largest version of [GPT-2](model_doc/gpt2), for example, has a fixed length of 1024 tokens, so we\ncannot calculate \\\\(p_\\theta(x_t|x_{<t})\\\\) directly when \\\\(t\\\\) is greater than 1024.\n\nInstead, the sequence is typically broken into subsequences equal to the model's maximum input size. If a model's max\ninput size is \\\\(k\\\\), we then approximate the likelihood of a token \\\\(x_t\\\\) by conditioning only on the\n\\\\(k-1\\\\) tokens that precede it rather than the entire context. When evaluating the model's perplexity of a\nsequence, a tempting but suboptimal approach is to break the sequence into disjoint chunks and add up the decomposed\nlog-likelihoods of each segment independently.\n\n<img width=\"600\" alt=\"Suboptimal PPL not taking advantage of full available context\" src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/ppl_chunked.gif\"/>\n\nThis is quick to compute since the perplexity of each segment can be computed in one forward pass, but serves as a poor\napproximation of the fully-factorized perplexity and will typically yield a higher (worse) PPL because the model will\nhave less context at most of the prediction steps."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 3b518f4b-2d4e-4f6e-b29b-efaefeb08537
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perplexity", "title": "Perplexity of fixed-length models", "tokens": 1903, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"3b518f4b-2d4e-4f6e-b29b-efaefeb08537\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perplexity\", \"title\": \"Perplexity of fixed-length models\", \"tokens\": 1903, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"0187f108-be22-444b-a494-a0c549691954\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perplexity\", \"title\": \"Perplexity of fixed-length models\", \"tokens\": 1903, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"c29ba1f258b9e32a5b6f976fff7045260dca085781f1e2dff67156b969945dc5\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"3d52a79e-41ec-478a-8460-aa6ef8e1f6a6\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perplexity\", \"title\": \"Perplexity of fixed-length models\", \"tokens\": 1903, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"d7916dff950d62ff915eec3023ee3506d5dcfa7f723cd1b0ee2480735a823bff\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"6e33fa6f-57f5-4401-a4c8-8f86d5cbb9d8\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"d00b2ac07bc0c169ee16cb9e6f6a3a39734c923ce99e6ef2856b8bf083a4c9f1\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 1777, \"end_char_idx\": 5107, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "0187f108-be22-444b-a494-a0c549691954", "doc_id": "0187f108-be22-444b-a494-a0c549691954", "ref_doc_id": "0187f108-be22-444b-a494-a0c549691954", "chroma:document": "<img width=\"600\" alt=\"Full decomposition of a sequence with unlimited context length\" src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/ppl_full.gif\"/>\n\nWhen working with approximate models, however, we typically have a constraint on the number of tokens the model can\nprocess. The largest version of [GPT-2](model_doc/gpt2), for example, has a fixed length of 1024 tokens, so we\ncannot calculate \\\\(p_\\theta(x_t|x_{<t})\\\\) directly when \\\\(t\\\\) is greater than 1024.\n\nInstead, the sequence is typically broken into subsequences equal to the model's maximum input size. If a model's max\ninput size is \\\\(k\\\\), we then approximate the likelihood of a token \\\\(x_t\\\\) by conditioning only on the\n\\\\(k-1\\\\) tokens that precede it rather than the entire context. When evaluating the model's perplexity of a\nsequence, a tempting but suboptimal approach is to break the sequence into disjoint chunks and add up the decomposed\nlog-likelihoods of each segment independently.\n\n<img width=\"600\" alt=\"Suboptimal PPL not taking advantage of full available context\" src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/ppl_chunked.gif\"/>\n\nThis is quick to compute since the perplexity of each segment can be computed in one forward pass, but serves as a poor\napproximation of the fully-factorized perplexity and will typically yield a higher (worse) PPL because the model will\nhave less context at most of the prediction steps.\n\nInstead, the PPL of fixed-length models should be evaluated with a sliding-window strategy. This involves repeatedly\nsliding the context window so that the model has more context when making each prediction.\n\n<img width=\"600\" alt=\"Sliding window PPL taking advantage of all available context\" src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/ppl_sliding.gif\"/>\n\nThis is a closer approximation to the true decomposition of the sequence probability and will typically yield a more\nfavorable score. The downside is that it requires a separate forward pass for each token in the corpus. A good\npractical compromise is to employ a strided sliding window, moving the context by larger strides rather than sliding by\n1 token a time. This allows computation to proceed much faster while still giving the model a large context to make\npredictions at each step.\n\n## Example: Calculating perplexity with GPT-2 in \ud83e\udd17 Transformers\n\nLet's demonstrate this process with GPT-2.\n\n```python\nfrom transformers import GPT2LMHeadModel, GPT2TokenizerFast\n\ndevice = \"cuda\"\nmodel_id = \"openai-community/gpt2-large\"\nmodel = GPT2LMHeadModel.from_pretrained(model_id).to(device)\ntokenizer = GPT2TokenizerFast.from_pretrained(model_id)\n```\n\nWe'll load in the WikiText-2 dataset and evaluate the perplexity using a few different sliding-window strategies. Since\nthis dataset is small and we're just doing one forward pass over the set, we can just load and encode the entire\ndataset in memory.\n\n```python\nfrom datasets import load_dataset\n\ntest = load_dataset(\"wikitext\", \"wikitext-2-raw-v1\", split=\"test\")\nencodings = tokenizer(\"\\n\\n\".join(test[\"text\"]), return_tensors=\"pt\")\n```\n\nWith \ud83e\udd17 Transformers, we can simply pass the `input_ids` as the `labels` to our model, and the average negative\nlog-likelihood for each token is returned as the loss."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 6e33fa6f-57f5-4401-a4c8-8f86d5cbb9d8
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perplexity", "title": "Perplexity of fixed-length models", "tokens": 1903, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"6e33fa6f-57f5-4401-a4c8-8f86d5cbb9d8\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perplexity\", \"title\": \"Perplexity of fixed-length models\", \"tokens\": 1903, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"0187f108-be22-444b-a494-a0c549691954\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perplexity\", \"title\": \"Perplexity of fixed-length models\", \"tokens\": 1903, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"c29ba1f258b9e32a5b6f976fff7045260dca085781f1e2dff67156b969945dc5\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"3b518f4b-2d4e-4f6e-b29b-efaefeb08537\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perplexity\", \"title\": \"Perplexity of fixed-length models\", \"tokens\": 1903, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"4e9d73b0f3eb332f77da00dd67c47d8c9a9edc87c83486902d6b910756073a42\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"007b7110-091d-4989-99a4-f53d593815cd\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"cc7119436ec9342d105aafdbd37a8a900fc506df9e37bc54541fe10956c0782b\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 3465, \"end_char_idx\": 6335, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "0187f108-be22-444b-a494-a0c549691954", "doc_id": "0187f108-be22-444b-a494-a0c549691954", "ref_doc_id": "0187f108-be22-444b-a494-a0c549691954", "chroma:document": "<img width=\"600\" alt=\"Sliding window PPL taking advantage of all available context\" src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/ppl_sliding.gif\"/>\n\nThis is a closer approximation to the true decomposition of the sequence probability and will typically yield a more\nfavorable score. The downside is that it requires a separate forward pass for each token in the corpus. A good\npractical compromise is to employ a strided sliding window, moving the context by larger strides rather than sliding by\n1 token a time. This allows computation to proceed much faster while still giving the model a large context to make\npredictions at each step.\n\n## Example: Calculating perplexity with GPT-2 in \ud83e\udd17 Transformers\n\nLet's demonstrate this process with GPT-2.\n\n```python\nfrom transformers import GPT2LMHeadModel, GPT2TokenizerFast\n\ndevice = \"cuda\"\nmodel_id = \"openai-community/gpt2-large\"\nmodel = GPT2LMHeadModel.from_pretrained(model_id).to(device)\ntokenizer = GPT2TokenizerFast.from_pretrained(model_id)\n```\n\nWe'll load in the WikiText-2 dataset and evaluate the perplexity using a few different sliding-window strategies. Since\nthis dataset is small and we're just doing one forward pass over the set, we can just load and encode the entire\ndataset in memory.\n\n```python\nfrom datasets import load_dataset\n\ntest = load_dataset(\"wikitext\", \"wikitext-2-raw-v1\", split=\"test\")\nencodings = tokenizer(\"\\n\\n\".join(test[\"text\"]), return_tensors=\"pt\")\n```\n\nWith \ud83e\udd17 Transformers, we can simply pass the `input_ids` as the `labels` to our model, and the average negative\nlog-likelihood for each token is returned as the loss. With our sliding window approach, however, there is overlap in\nthe tokens we pass to the model at each iteration. We don't want the log-likelihood for the tokens we're just treating\nas context to be included in our loss, so we can set these targets to `-100` so that they are ignored. The following\nis an example of how we could do this with a stride of `512`. This means that the model will have at least 512 tokens\nfor context when calculating the conditional likelihood of any one token (provided there are 512 preceding tokens\navailable to condition on).\n\n```python\nimport torch\nfrom tqdm import tqdm\n\nmax_length = model.config.n_positions\nstride = 512\nseq_len = encodings.input_ids.size(1)\n\nnlls = []\nprev_end_loc = 0\nfor begin_loc in tqdm(range(0, seq_len, stride)):\n    end_loc = min(begin_loc + max_length, seq_len)\n    trg_len = end_loc - prev_end_loc  # may be different from stride on last loop\n    input_ids = encodings.input_ids[:, begin_loc:end_loc].to(device)\n    target_ids = input_ids.clone()\n    target_ids[:, :-trg_len] = -100\n\n    with torch.no_grad():\n        outputs = model(input_ids, labels=target_ids)\n\n        # loss is calculated using CrossEntropyLoss which averages over valid labels\n        # N.B."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 007b7110-091d-4989-99a4-f53d593815cd
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perplexity", "title": "Perplexity of fixed-length models", "tokens": 1903, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"007b7110-091d-4989-99a4-f53d593815cd\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perplexity\", \"title\": \"Perplexity of fixed-length models\", \"tokens\": 1903, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"0187f108-be22-444b-a494-a0c549691954\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perplexity\", \"title\": \"Perplexity of fixed-length models\", \"tokens\": 1903, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"c29ba1f258b9e32a5b6f976fff7045260dca085781f1e2dff67156b969945dc5\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"6e33fa6f-57f5-4401-a4c8-8f86d5cbb9d8\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perplexity\", \"title\": \"Perplexity of fixed-length models\", \"tokens\": 1903, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"5360e1737ae012a7c10509fa76687258ea419f54944909678c469293c284d652\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 4755, \"end_char_idx\": 7362, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "0187f108-be22-444b-a494-a0c549691954", "doc_id": "0187f108-be22-444b-a494-a0c549691954", "ref_doc_id": "0187f108-be22-444b-a494-a0c549691954", "chroma:document": "```python\nfrom datasets import load_dataset\n\ntest = load_dataset(\"wikitext\", \"wikitext-2-raw-v1\", split=\"test\")\nencodings = tokenizer(\"\\n\\n\".join(test[\"text\"]), return_tensors=\"pt\")\n```\n\nWith \ud83e\udd17 Transformers, we can simply pass the `input_ids` as the `labels` to our model, and the average negative\nlog-likelihood for each token is returned as the loss. With our sliding window approach, however, there is overlap in\nthe tokens we pass to the model at each iteration. We don't want the log-likelihood for the tokens we're just treating\nas context to be included in our loss, so we can set these targets to `-100` so that they are ignored. The following\nis an example of how we could do this with a stride of `512`. This means that the model will have at least 512 tokens\nfor context when calculating the conditional likelihood of any one token (provided there are 512 preceding tokens\navailable to condition on).\n\n```python\nimport torch\nfrom tqdm import tqdm\n\nmax_length = model.config.n_positions\nstride = 512\nseq_len = encodings.input_ids.size(1)\n\nnlls = []\nprev_end_loc = 0\nfor begin_loc in tqdm(range(0, seq_len, stride)):\n    end_loc = min(begin_loc + max_length, seq_len)\n    trg_len = end_loc - prev_end_loc  # may be different from stride on last loop\n    input_ids = encodings.input_ids[:, begin_loc:end_loc].to(device)\n    target_ids = input_ids.clone()\n    target_ids[:, :-trg_len] = -100\n\n    with torch.no_grad():\n        outputs = model(input_ids, labels=target_ids)\n\n        # loss is calculated using CrossEntropyLoss which averages over valid labels\n        # N.B. the model only calculates loss over trg_len - 1 labels, because it internally shifts the labels\n        # to the left by 1.\n        neg_log_likelihood = outputs.loss\n\n    nlls.append(neg_log_likelihood)\n\n    prev_end_loc = end_loc\n    if end_loc == seq_len:\n        break\n\nppl = torch.exp(torch.stack(nlls).mean())\n```\n\nRunning this with the stride length equal to the max input length is equivalent to the suboptimal, non-sliding-window\nstrategy we discussed above. The smaller the stride, the more context the model will have in making each prediction,\nand the better the reported perplexity will typically be.\n\nWhen we run the above with `stride = 1024`, i.e. no overlap, the resulting PPL is `19.44`, which is about the same\nas the `19.93` reported in the GPT-2 paper. By using `stride = 512` and thereby employing our striding window\nstrategy, this jumps down to `16.45`. This is not only a more favorable score, but is calculated in a way that is\ncloser to the true autoregressive decomposition of a sequence likelihood."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: dc0f214b-f341-449c-9f79-01dca56bd165
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5169, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"dc0f214b-f341-449c-9f79-01dca56bd165\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"6b319276-4cfc-4b19-9444-e4bce696d684\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"59c23c3a8ad0aefa4ce8789029e0bdfa70897112b3745184bb7e11013fc1cbf4\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"e9127836-c8be-456d-ae01-fa4742b32348\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"e086b5bc17fe6ebc4a01b3ace6dd5d430f698c2cd575cf6fd8f41de6f639bb9f\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 0, \"end_char_idx\": 3420, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "ref_doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "chroma:document": "# Agents and tools\n\n[[open-in-colab]]\n\n### What is an agent?\n\nLarge Language Models (LLMs) trained to perform [causal language modeling](./tasks/language_modeling.) can tackle a wide range of tasks, but they often struggle with basic tasks like logic, calculation, and search. When prompted in domains in which they do not perform well, they often fail to generate the answer we expect them to.\n\nOne approach to overcome this weakness is to create an *agent*.\n\nAn agent is a system that uses an LLM as its engine, and it has access to functions called *tools*.\n\nThese *tools* are functions for performing a task, and they contain all necessary description for the agent to properly use them.\n\nThe agent can be programmed to:\n- devise a series of actions/tools and run them all at once like the [`CodeAgent`] for example\n- plan and execute actions/tools one by one and wait for the outcome of each action before launching the next one like the [`ReactJsonAgent`] for example\n\n### Types of agents\n\n#### Code agent\n\nThis agent has a planning step, then generates python code to execute all its actions at once. It natively handles different input and output types for its tools, thus it is the recommended choice for multimodal tasks.\n\n#### React agents\n\nThis is the go-to agent to solve reasoning tasks, since the ReAct framework ([Yao et al., 2022](https://huggingface.co/papers/2210.03629)) makes it really efficient to think on the basis of its previous observations.\n\nWe implement two versions of ReactJsonAgent: \n- [`ReactJsonAgent`] generates tool calls as a JSON in its output.\n- [`ReactCodeAgent`] is a new type of ReactJsonAgent that generates its tool calls as blobs of code, which works really well for LLMs that have strong coding performance.\n\n> [!TIP]\n> Read [Open-source LLMs as LangChain Agents](https://huggingface.co/blog/open-source-llms-as-agents) blog post to learn more the ReAct agent.\n\n![Framework of a React Agent](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/open-source-llms-as-agents/ReAct.png)\n\nFor example, here is how a ReAct Code agent would work its way through the following question.\n\n```py3\n>>> agent.run(\n...     \"How many more blocks (also denoted as layers) in BERT base encoder than the encoder from the architecture proposed in Attention is All You Need?\",\n... )\n=====New task=====\nHow many more blocks (also denoted as layers) in BERT base encoder than the encoder from the architecture proposed in Attention is All You Need?\n====Agent is executing the code below:\nbert_blocks = search(query=\"number of blocks in BERT base encoder\")\nprint(\"BERT blocks:\", bert_blocks)\n====\nPrint outputs:\nBERT blocks: twelve encoder blocks\n\n====Agent is executing the code below:\nattention_layer = search(query=\"number of layers in Attention is All You Need\")\nprint(\"Attention layers:\", attention_layer)\n====\nPrint outputs:\nAttention layers: Encoder: The encoder is composed of a stack of N = 6 identical layers. Each layer has two sub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, position- 2 Page 3 Figure 1: The Transformer - model architecture.\n\n====Agent is executing the code below:\nbert_blocks = 12\nattention_layers = 6\ndiff = bert_blocks - attention_layers\nprint(\"Difference in blocks:\", diff)\nfinal_answer(diff)\n====\n\nPrint outputs:\nDifference in blocks: 6\n\nFinal answer: 6\n```\n\n### How can I build an agent?"}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: e9127836-c8be-456d-ae01-fa4742b32348
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5169, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"e9127836-c8be-456d-ae01-fa4742b32348\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"6b319276-4cfc-4b19-9444-e4bce696d684\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"59c23c3a8ad0aefa4ce8789029e0bdfa70897112b3745184bb7e11013fc1cbf4\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"dc0f214b-f341-449c-9f79-01dca56bd165\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"602df2d721188a254a6f9a2f94571b9b5d33ad21b37fcc84cfe5e13439098d03\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"0b47165b-a56e-4816-bff7-bc6ce037218a\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"fc951d84db93366d6ab24e514d6bf5545e055b80ffccdc97c958c79c021e5344\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 1755, \"end_char_idx\": 4397, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "ref_doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "chroma:document": "> [!TIP]\n> Read [Open-source LLMs as LangChain Agents](https://huggingface.co/blog/open-source-llms-as-agents) blog post to learn more the ReAct agent.\n\n![Framework of a React Agent](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/open-source-llms-as-agents/ReAct.png)\n\nFor example, here is how a ReAct Code agent would work its way through the following question.\n\n```py3\n>>> agent.run(\n...     \"How many more blocks (also denoted as layers) in BERT base encoder than the encoder from the architecture proposed in Attention is All You Need?\",\n... )\n=====New task=====\nHow many more blocks (also denoted as layers) in BERT base encoder than the encoder from the architecture proposed in Attention is All You Need?\n====Agent is executing the code below:\nbert_blocks = search(query=\"number of blocks in BERT base encoder\")\nprint(\"BERT blocks:\", bert_blocks)\n====\nPrint outputs:\nBERT blocks: twelve encoder blocks\n\n====Agent is executing the code below:\nattention_layer = search(query=\"number of layers in Attention is All You Need\")\nprint(\"Attention layers:\", attention_layer)\n====\nPrint outputs:\nAttention layers: Encoder: The encoder is composed of a stack of N = 6 identical layers. Each layer has two sub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, position- 2 Page 3 Figure 1: The Transformer - model architecture.\n\n====Agent is executing the code below:\nbert_blocks = 12\nattention_layers = 6\ndiff = bert_blocks - attention_layers\nprint(\"Difference in blocks:\", diff)\nfinal_answer(diff)\n====\n\nPrint outputs:\nDifference in blocks: 6\n\nFinal answer: 6\n```\n\n### How can I build an agent?\n\nTo initialize an agent, you need these arguments:\n\n- an LLM to power your agent - the agent is not exactly the LLM, it\u2019s more like the agent is a program that uses an LLM as its engine.\n- a system prompt: what the LLM engine will be prompted with to generate its output\n- a toolbox from which the agent pick tools to execute\n- a parser to extract from the LLM output which tools are to call and with which arguments\n\nUpon initialization of the agent system, the tool attributes are used to generate a tool description, then baked into the agent\u2019s `system_prompt` to let it know which tools it can use and why.\n\nTo start with, please install the `agents` extras in order to install all default dependencies.\n\n```bash\npip install transformers[agents]\n```\n\nBuild your LLM engine by defining a `llm_engine` method which accepts a list of [messages](./chat_templating.) and returns text. This callable also needs to accept a `stop` argument that indicates when to stop generating."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 0b47165b-a56e-4816-bff7-bc6ce037218a
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5169, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"0b47165b-a56e-4816-bff7-bc6ce037218a\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"6b319276-4cfc-4b19-9444-e4bce696d684\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"59c23c3a8ad0aefa4ce8789029e0bdfa70897112b3745184bb7e11013fc1cbf4\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"e9127836-c8be-456d-ae01-fa4742b32348\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f5cb08943b5e8117600f765ec7d0bbbd786cad5290bc4a124b05654762ee02dd\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"2ab033b8-925b-42d4-bbe0-3e5e89d2bcdf\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"c71e4e63eee97a0b82502febc8a219f72109dc51917715da03fbeedfd1bf69ff\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 2974, \"end_char_idx\": 6175, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "ref_doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "chroma:document": "Each layer has two sub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, position- 2 Page 3 Figure 1: The Transformer - model architecture.\n\n====Agent is executing the code below:\nbert_blocks = 12\nattention_layers = 6\ndiff = bert_blocks - attention_layers\nprint(\"Difference in blocks:\", diff)\nfinal_answer(diff)\n====\n\nPrint outputs:\nDifference in blocks: 6\n\nFinal answer: 6\n```\n\n### How can I build an agent?\n\nTo initialize an agent, you need these arguments:\n\n- an LLM to power your agent - the agent is not exactly the LLM, it\u2019s more like the agent is a program that uses an LLM as its engine.\n- a system prompt: what the LLM engine will be prompted with to generate its output\n- a toolbox from which the agent pick tools to execute\n- a parser to extract from the LLM output which tools are to call and with which arguments\n\nUpon initialization of the agent system, the tool attributes are used to generate a tool description, then baked into the agent\u2019s `system_prompt` to let it know which tools it can use and why.\n\nTo start with, please install the `agents` extras in order to install all default dependencies.\n\n```bash\npip install transformers[agents]\n```\n\nBuild your LLM engine by defining a `llm_engine` method which accepts a list of [messages](./chat_templating.) and returns text. This callable also needs to accept a `stop` argument that indicates when to stop generating.\n\n```python\nfrom huggingface_hub import login, InferenceClient\n\nlogin(\"<YOUR_HUGGINGFACEHUB_API_TOKEN>\")\n\nclient = InferenceClient(model=\"meta-llama/Meta-Llama-3-70B-Instruct\")\n\ndef llm_engine(messages, stop_sequences=[\"Task\"]) -> str:\n    response = client.chat_completion(messages, stop=stop_sequences, max_tokens=1000)\n    answer = response.choices[0].message.content\n    return answer\n```\n\nYou could use any `llm_engine` method as long as:\n1. it follows the [messages format](./chat_templating.md) for its input (`List[Dict[str, str]]`) and returns a `str`\n2. it stops generating outputs at the sequences passed in the argument `stop`\n\nYou also need a `tools` argument which accepts a list of `Tools`. You can provide an empty list for `tools`, but use the default toolbox with the optional argument `add_base_tools=True`.\n\nNow you can create an agent, like [`CodeAgent`], and run it. For convenience, we also provide the [`HfEngine`] class that uses `huggingface_hub.InferenceClient` under the hood.\n\n```python\nfrom transformers import CodeAgent, HfEngine\n\nllm_engine = HfEngine(model=\"meta-llama/Meta-Llama-3-70B-Instruct\")\nagent = CodeAgent(tools=[], llm_engine=llm_engine, add_base_tools=True)\n\nagent.run(\n    \"Could you translate this sentence from French, say it out loud and return the audio.\",\n    sentence=\"O\u00f9 est la boulangerie la plus proche?\",\n)\n```\n\nThis will be handy in case of emergency baguette need!\nYou can even leave the argument `llm_engine` undefined, and an [`HfEngine`] will be created by default.\n\n```python\nfrom transformers import CodeAgent\n\nagent = CodeAgent(tools=[], add_base_tools=True)\n\nagent.run(\n    \"Could you translate this sentence from French, say it out loud and give me the audio.\",\n    sentence=\"O\u00f9 est la boulangerie la plus proche?"}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 2ab033b8-925b-42d4-bbe0-3e5e89d2bcdf
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5169, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"2ab033b8-925b-42d4-bbe0-3e5e89d2bcdf\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"6b319276-4cfc-4b19-9444-e4bce696d684\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"59c23c3a8ad0aefa4ce8789029e0bdfa70897112b3745184bb7e11013fc1cbf4\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"0b47165b-a56e-4816-bff7-bc6ce037218a\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"342d5ea53214de1328c5054bfc651be1933d745eac096fc3750819a7e2c0908f\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"417a5da4-2263-4228-83e9-ad961fe663ec\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"7c3f613913b1b07e82a2d5ce6a28d39ac8612f414c169b264c0d614e341a1d07\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 5103, \"end_char_idx\": 8473, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "ref_doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "chroma:document": "You can provide an empty list for `tools`, but use the default toolbox with the optional argument `add_base_tools=True`.\n\nNow you can create an agent, like [`CodeAgent`], and run it. For convenience, we also provide the [`HfEngine`] class that uses `huggingface_hub.InferenceClient` under the hood.\n\n```python\nfrom transformers import CodeAgent, HfEngine\n\nllm_engine = HfEngine(model=\"meta-llama/Meta-Llama-3-70B-Instruct\")\nagent = CodeAgent(tools=[], llm_engine=llm_engine, add_base_tools=True)\n\nagent.run(\n    \"Could you translate this sentence from French, say it out loud and return the audio.\",\n    sentence=\"O\u00f9 est la boulangerie la plus proche?\",\n)\n```\n\nThis will be handy in case of emergency baguette need!\nYou can even leave the argument `llm_engine` undefined, and an [`HfEngine`] will be created by default.\n\n```python\nfrom transformers import CodeAgent\n\nagent = CodeAgent(tools=[], add_base_tools=True)\n\nagent.run(\n    \"Could you translate this sentence from French, say it out loud and give me the audio.\",\n    sentence=\"O\u00f9 est la boulangerie la plus proche?\",\n)\n```\n\nNote that we used an additional `sentence` argument: you can pass text as additional arguments to the model.\n\nYou can also use this to indicate the path to local or remote files for the model to use:\n\n```py\nfrom transformers import ReactCodeAgent\n\nagent = ReactCodeAgent(tools=[], llm_engine=llm_engine, add_base_tools=True)\n\nagent.run(\"Why does Mike not know many people in New York?\", audio=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/recording.mp3\")\n```\n\n\nThe prompt and output parser were automatically defined, but you can easily inspect them by calling the `system_prompt_template` on your agent.\n\n```python\nprint(agent.system_prompt_template)\n```\n\nIt's important to explain as clearly as possible the task you want to perform.\nEvery [`~Agent.run`] operation is independent, and since an agent is powered by an LLM, minor variations in your prompt might yield completely different results.\nYou can also run an agent consecutively for different tasks: each time the attributes `agent.task` and `agent.logs` will be re-initialized.\n\n\n#### Code execution\n\nA Python interpreter executes the code on a set of inputs passed along with your tools.\nThis should be safe because the only functions that can be called are the tools you provided (especially if it's only tools by Hugging Face) and the print function, so you're already limited in what can be executed.\n\nThe Python interpreter also doesn't allow imports by default outside of a safe list, so all the most obvious attacks shouldn't be an issue.\nYou can still authorize additional imports by passing the authorized modules as a list of strings in argument `additional_authorized_imports` upon initialization of your [`ReactCodeAgent`] or [`CodeAgent`]:\n\n```py\n>>> from transformers import ReactCodeAgent\n\n>>> agent = ReactCodeAgent(tools=[], additional_authorized_imports=['requests', 'bs4'])\n>>> agent.run(\"Could you get me the title of the page at url 'https://huggingface.co/blog'?\")\n\n(...)\n'Hugging Face \u2013 Blog'\n```\n\nThe execution will stop at any code trying to perform an illegal operation or if there is a regular Python error with the code generated by the agent.\n\n> [!WARNING]\n> The LLM can generate arbitrary code that will then be executed: do not add any unsafe imports!"}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 417a5da4-2263-4228-83e9-ad961fe663ec
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5169, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"417a5da4-2263-4228-83e9-ad961fe663ec\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"6b319276-4cfc-4b19-9444-e4bce696d684\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"59c23c3a8ad0aefa4ce8789029e0bdfa70897112b3745184bb7e11013fc1cbf4\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"2ab033b8-925b-42d4-bbe0-3e5e89d2bcdf\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"afb496755c12509e63c487b32c10dc00f98a0629b878d8e30f794c03352a5c53\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"74d860cf-9d90-4ab8-bb67-c0bdcf72d92e\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"2e8a143dd2627f08f892417ad8e81b2516a532a0eb698ea901adfb8a63245691\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 6692, \"end_char_idx\": 10359, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "ref_doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "chroma:document": "The prompt and output parser were automatically defined, but you can easily inspect them by calling the `system_prompt_template` on your agent.\n\n```python\nprint(agent.system_prompt_template)\n```\n\nIt's important to explain as clearly as possible the task you want to perform.\nEvery [`~Agent.run`] operation is independent, and since an agent is powered by an LLM, minor variations in your prompt might yield completely different results.\nYou can also run an agent consecutively for different tasks: each time the attributes `agent.task` and `agent.logs` will be re-initialized.\n\n\n#### Code execution\n\nA Python interpreter executes the code on a set of inputs passed along with your tools.\nThis should be safe because the only functions that can be called are the tools you provided (especially if it's only tools by Hugging Face) and the print function, so you're already limited in what can be executed.\n\nThe Python interpreter also doesn't allow imports by default outside of a safe list, so all the most obvious attacks shouldn't be an issue.\nYou can still authorize additional imports by passing the authorized modules as a list of strings in argument `additional_authorized_imports` upon initialization of your [`ReactCodeAgent`] or [`CodeAgent`]:\n\n```py\n>>> from transformers import ReactCodeAgent\n\n>>> agent = ReactCodeAgent(tools=[], additional_authorized_imports=['requests', 'bs4'])\n>>> agent.run(\"Could you get me the title of the page at url 'https://huggingface.co/blog'?\")\n\n(...)\n'Hugging Face \u2013 Blog'\n```\n\nThe execution will stop at any code trying to perform an illegal operation or if there is a regular Python error with the code generated by the agent.\n\n> [!WARNING]\n> The LLM can generate arbitrary code that will then be executed: do not add any unsafe imports!\n\n### The system prompt\n\nAn agent, or rather the LLM that drives the agent, generates an output based on the system prompt. The system prompt can be customized and tailored to the intended task. For example, check the system prompt for the [`ReactCodeAgent`] (below version is slightly simplified).\n\n```text\nYou will be given a task to solve as best you can.\nYou have access to the following tools:\n<<tool_descriptions>>\n\nTo solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences.\n\nAt each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task, then the tools that you want to use.\nThen in the 'Code:' sequence, you shold write the code in simple Python. The code sequence must end with '/End code' sequence.\nDuring each intermediate step, you can use 'print()' to save whatever important information you will then need.\nThese print outputs will then be available in the 'Observation:' field, for using this information as input for the next step.\n\nIn the end you have to return a final answer using the `final_answer` tool.\n\nHere are a few examples using notional tools:\n---\n{examples}\n\nAbove example were using notional tools that might not exist for you. You only have acces to those tools:\n<<tool_names>>\nYou also can perform computations in the python code you generate.\n\nAlways provide a 'Thought:' and a 'Code:\\n```py' sequence ending with '```<end_code>' sequence. You MUST provide at least the 'Code:' sequence to move forward.\n\nRemember to not perform too many operations in a single code block! You should split the task into intermediate code blocks.\nPrint results at the end of each step to save the intermediate results. Then use final_answer() to return the final result.\n\nRemember to make sure that variables you use are all defined.\n\nNow Begin!"}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 74d860cf-9d90-4ab8-bb67-c0bdcf72d92e
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5169, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"74d860cf-9d90-4ab8-bb67-c0bdcf72d92e\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"6b319276-4cfc-4b19-9444-e4bce696d684\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"59c23c3a8ad0aefa4ce8789029e0bdfa70897112b3745184bb7e11013fc1cbf4\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"417a5da4-2263-4228-83e9-ad961fe663ec\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"464224f50d9666f4469f2da15cd95750544fd8c4a17c75dc78d3d6558096ec10\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"aa6c451b-2590-45e7-bbab-ffbfdf655c9a\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"910a6b9dabc332606eed91decb9a5bb857238f301fb1013279bc3652aa737a24\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 8597, \"end_char_idx\": 11445, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "ref_doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "chroma:document": "The system prompt can be customized and tailored to the intended task. For example, check the system prompt for the [`ReactCodeAgent`] (below version is slightly simplified).\n\n```text\nYou will be given a task to solve as best you can.\nYou have access to the following tools:\n<<tool_descriptions>>\n\nTo solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences.\n\nAt each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task, then the tools that you want to use.\nThen in the 'Code:' sequence, you shold write the code in simple Python. The code sequence must end with '/End code' sequence.\nDuring each intermediate step, you can use 'print()' to save whatever important information you will then need.\nThese print outputs will then be available in the 'Observation:' field, for using this information as input for the next step.\n\nIn the end you have to return a final answer using the `final_answer` tool.\n\nHere are a few examples using notional tools:\n---\n{examples}\n\nAbove example were using notional tools that might not exist for you. You only have acces to those tools:\n<<tool_names>>\nYou also can perform computations in the python code you generate.\n\nAlways provide a 'Thought:' and a 'Code:\\n```py' sequence ending with '```<end_code>' sequence. You MUST provide at least the 'Code:' sequence to move forward.\n\nRemember to not perform too many operations in a single code block! You should split the task into intermediate code blocks.\nPrint results at the end of each step to save the intermediate results. Then use final_answer() to return the final result.\n\nRemember to make sure that variables you use are all defined.\n\nNow Begin!\n```\n\nThe system prompt includes:\n- An *introduction* that explains how the agent should behave and what tools are.\n- A description of all the tools that is defined by a `<<tool_descriptions>>` token that is dynamically replaced at runtime with the tools defined/chosen by the user.\n    - The tool description comes from the tool attributes, `name`, `description`, `inputs` and `output_type`,  and a simple `jinja2` template that you can refine.\n- The expected output format.\n\nYou could improve the system prompt, for example, by adding an explanation of the output format.\n\nFor maximum flexibility, you can overwrite the whole system prompt template by passing your custom prompt as an argument to the `system_prompt` parameter.\n\n```python\nfrom transformers import ReactJsonAgent\nfrom transformers.agents import PythonInterpreterTool\n\nagent = ReactJsonAgent(tools=[PythonInterpreterTool()], system_prompt=\"{your_custom_prompt}\")\n```\n\n> [!WARNING]\n> Please make sure to define the `<<tool_descriptions>>` string somewhere in the `template` so the agent is aware \nof the available tools."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: aa6c451b-2590-45e7-bbab-ffbfdf655c9a
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5169, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"aa6c451b-2590-45e7-bbab-ffbfdf655c9a\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"6b319276-4cfc-4b19-9444-e4bce696d684\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"59c23c3a8ad0aefa4ce8789029e0bdfa70897112b3745184bb7e11013fc1cbf4\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"74d860cf-9d90-4ab8-bb67-c0bdcf72d92e\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"83383029adef2e0a70981a4caa375fd9ac3a90ab43fe32c4238e88e23868bbbb\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"2b64091f-9183-4c34-8b92-bdd4aa0ad5da\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"529c68a103c37035bd58003dba137a840a96e7af9fc865412e7a0b90fdfc313e\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 9624, \"end_char_idx\": 13661, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "ref_doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "chroma:document": "Here are a few examples using notional tools:\n---\n{examples}\n\nAbove example were using notional tools that might not exist for you. You only have acces to those tools:\n<<tool_names>>\nYou also can perform computations in the python code you generate.\n\nAlways provide a 'Thought:' and a 'Code:\\n```py' sequence ending with '```<end_code>' sequence. You MUST provide at least the 'Code:' sequence to move forward.\n\nRemember to not perform too many operations in a single code block! You should split the task into intermediate code blocks.\nPrint results at the end of each step to save the intermediate results. Then use final_answer() to return the final result.\n\nRemember to make sure that variables you use are all defined.\n\nNow Begin!\n```\n\nThe system prompt includes:\n- An *introduction* that explains how the agent should behave and what tools are.\n- A description of all the tools that is defined by a `<<tool_descriptions>>` token that is dynamically replaced at runtime with the tools defined/chosen by the user.\n    - The tool description comes from the tool attributes, `name`, `description`, `inputs` and `output_type`,  and a simple `jinja2` template that you can refine.\n- The expected output format.\n\nYou could improve the system prompt, for example, by adding an explanation of the output format.\n\nFor maximum flexibility, you can overwrite the whole system prompt template by passing your custom prompt as an argument to the `system_prompt` parameter.\n\n```python\nfrom transformers import ReactJsonAgent\nfrom transformers.agents import PythonInterpreterTool\n\nagent = ReactJsonAgent(tools=[PythonInterpreterTool()], system_prompt=\"{your_custom_prompt}\")\n```\n\n> [!WARNING]\n> Please make sure to define the `<<tool_descriptions>>` string somewhere in the `template` so the agent is aware \nof the available tools.\n\n\n### Inspecting an agent run\n\nHere are a few useful attributes to inspect what happened after a run:\n- `agent.logs` stores the fine-grained logs of the agent. At every step of the agent's run, everything gets stored in a dictionary that then is appended to `agent.logs`.\n- Running `agent.write_inner_memory_from_logs()` creates an inner memory of the agent's logs for the LLM to view, as a list of chat messages. This method goes over each step of the log and only stores what it's interested in as a message: for instance, it will save the system prompt and task in separate messages, then for each step it will store the LLM output as a message, and the tool call output as another message. Use this if you want a higher-level view of what has happened - but not every log will be transcripted by this method.\n\n## Tools\n\nA tool is an atomic function to be used by an agent.\n\nYou can for instance check the [`PythonInterpreterTool`]: it has a name, a description, input descriptions, an output type, and a `__call__` method to perform the action.\n\nWhen the agent is initialized, the tool attributes are used to generate a tool description which is baked into the agent's system prompt. This lets the agent know which tools it can use and why.\n\n### Default toolbox\n\nTransformers comes with a default toolbox for empowering agents, that you can add to your agent upon initialization with argument `add_base_tools = True`:\n\n- **Document question answering**: given a document (such as a PDF) in image format, answer a question on this document ([Donut](./model_doc/donut))\n- **Image question answering**: given an image, answer a question on this image ([VILT](./model_doc/vilt))\n- **Speech to text**: given an audio recording of a person talking, transcribe the speech into text ([Whisper](./model_doc/whisper))\n- **Text to speech**: convert text to speech ([SpeechT5](./model_doc/speecht5))\n- **Translation**: translates a given sentence from source language to target language.\n- **Python code interpreter**: runs your the LLM generated Python code in a secure environment. This tool will only be added to [`ReactJsonAgent`] if you use `add_base_tools=True`, since code-based tools can already execute Python code"}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 2b64091f-9183-4c34-8b92-bdd4aa0ad5da
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5169, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"2b64091f-9183-4c34-8b92-bdd4aa0ad5da\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"6b319276-4cfc-4b19-9444-e4bce696d684\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"59c23c3a8ad0aefa4ce8789029e0bdfa70897112b3745184bb7e11013fc1cbf4\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"aa6c451b-2590-45e7-bbab-ffbfdf655c9a\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"5ff911b2ea43dec3e81151fca8c0dbb451f6e5dc2f2f7a39d66957298fa2d559\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"1a9f94d6-51c9-472b-9d5d-9a184ba6c0fe\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"88476ff75c52c41a13390e4d1645b6bf50bc75b63a8097f11c4754d11ced2406\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 13664, \"end_char_idx\": 15877, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "ref_doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "chroma:document": "You can manually use a tool by calling the [`load_tool`] function and a task to perform.\n\n\n```python\nfrom transformers import load_tool\n\ntool = load_tool(\"text-to-speech\")\naudio = tool(\"This is a text to speech tool\")\n```\n\n\n### Create a new tool\n\nYou can create your own tool for use cases not covered by the default tools from Hugging Face.\nFor example, let's create a tool that returns the most downloaded model for a given task from the Hub.\n\nYou'll start with the code below.\n\n```python\nfrom huggingface_hub import list_models\n\ntask = \"text-classification\"\n\nmodel = next(iter(list_models(filter=task, sort=\"downloads\", direction=-1)))\nprint(model.id)\n```\n\nThis code can be converted into a class that inherits from the [`Tool`] superclass.\n\n\nThe custom tool needs:\n- An attribute `name`, which corresponds to the name of the tool itself. The name usually describes what the tool does. Since the code returns the model with the most downloads for a task, let's name is `model_download_counter`.\n- An attribute `description` is used to populate the agent's system prompt.\n- An `inputs` attribute, which is a dictionary with keys `\"type\"` and `\"description\"`. It contains information that helps the Python interpreter make educated choices about the input.\n- An `output_type` attribute, which specifies the output type.\n- A `forward` method which contains the inference code to be executed.\n\n\n```python\nfrom transformers import Tool\nfrom huggingface_hub import list_models\n\nclass HFModelDownloadsTool(Tool):\n    name = \"model_download_counter\"\n    description = (\n        \"This is a tool that returns the most downloaded model of a given task on the Hugging Face Hub. \"\n        \"It returns the name of the checkpoint.\"\n    )\n\n    inputs = {\n        \"task\": {\n            \"type\": \"text\",\n            \"description\": \"the task category (such as text-classification, depth-estimation, etc)\",\n        }\n    }\n    output_type = \"text\"\n\n    def forward(self, task: str):\n        model = next(iter(list_models(filter=task, sort=\"downloads\", direction=-1)))\n        return model.id\n```\n\nNow that the custom `HfModelDownloadsTool` class is ready, you can save it to a file named `model_downloads.py` and import it for use."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 1a9f94d6-51c9-472b-9d5d-9a184ba6c0fe
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5169, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"1a9f94d6-51c9-472b-9d5d-9a184ba6c0fe\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"6b319276-4cfc-4b19-9444-e4bce696d684\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"59c23c3a8ad0aefa4ce8789029e0bdfa70897112b3745184bb7e11013fc1cbf4\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"2b64091f-9183-4c34-8b92-bdd4aa0ad5da\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"9aec6e495a892527da234f3f4718da0c998eadd26f11f35487417a36e01dc474\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"17e09ec8-059b-438b-baeb-c29b86591a82\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"b135bc356bee18b528c1d4046da4f95d0702bda3910087f66f1b092548c14379\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 14410, \"end_char_idx\": 17169, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "ref_doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "chroma:document": "The custom tool needs:\n- An attribute `name`, which corresponds to the name of the tool itself. The name usually describes what the tool does. Since the code returns the model with the most downloads for a task, let's name is `model_download_counter`.\n- An attribute `description` is used to populate the agent's system prompt.\n- An `inputs` attribute, which is a dictionary with keys `\"type\"` and `\"description\"`. It contains information that helps the Python interpreter make educated choices about the input.\n- An `output_type` attribute, which specifies the output type.\n- A `forward` method which contains the inference code to be executed.\n\n\n```python\nfrom transformers import Tool\nfrom huggingface_hub import list_models\n\nclass HFModelDownloadsTool(Tool):\n    name = \"model_download_counter\"\n    description = (\n        \"This is a tool that returns the most downloaded model of a given task on the Hugging Face Hub. \"\n        \"It returns the name of the checkpoint.\"\n    )\n\n    inputs = {\n        \"task\": {\n            \"type\": \"text\",\n            \"description\": \"the task category (such as text-classification, depth-estimation, etc)\",\n        }\n    }\n    output_type = \"text\"\n\n    def forward(self, task: str):\n        model = next(iter(list_models(filter=task, sort=\"downloads\", direction=-1)))\n        return model.id\n```\n\nNow that the custom `HfModelDownloadsTool` class is ready, you can save it to a file named `model_downloads.py` and import it for use.\n\n\n```python\nfrom model_downloads import HFModelDownloadsTool\n\ntool = HFModelDownloadsTool()\n```\n\nYou can also share your custom tool to the Hub by calling [`~Tool.push_to_hub`] on the tool. Make sure you've created a repository for it on the Hub and are using a token with read access.\n\n```python\ntool.push_to_hub(\"{your_username}/hf-model-downloads\")\n```\n\nLoad the tool with the [`~Tool.load_tool`] function and pass it to the `tools` parameter in your agent.\n\n```python\nfrom transformers import load_tool, CodeAgent\n\nmodel_download_tool = load_tool(\"m-ric/hf-model-downloads\")\nagent = CodeAgent(tools=[model_download_tool], llm_engine=llm_engine)\nagent.run(\n    \"Can you give me the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub?\"\n)\n```\n\nYou get the following:\n```text\n======== New task ========\nCan you give me the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub?\n==== Agent is executing the code below:\nmost_downloaded_model = model_download_counter(task=\"text-to-video\")\nprint(f\"The most downloaded model for the 'text-to-video' task is {most_downloaded_model}.\")\n====\n```\n\nAnd the output:\n`\"The most downloaded model for the 'text-to-video' task is ByteDance/AnimateDiff-Lightning.\"`"}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 17e09ec8-059b-438b-baeb-c29b86591a82
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5169, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"17e09ec8-059b-438b-baeb-c29b86591a82\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"6b319276-4cfc-4b19-9444-e4bce696d684\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"59c23c3a8ad0aefa4ce8789029e0bdfa70897112b3745184bb7e11013fc1cbf4\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"1a9f94d6-51c9-472b-9d5d-9a184ba6c0fe\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"a02cff3a919f9536e203d4300a3b9e26f7bc26c3b7eb1104211f0fa03a392492\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"440394b3-1a29-4ffb-8c1f-3e06fbedfe01\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"2c8c16a8a1470e35526a92a91bcbb35c86b892c3738273e1aecd3a7ec652c881\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 15880, \"end_char_idx\": 18993, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "ref_doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "chroma:document": "```python\nfrom model_downloads import HFModelDownloadsTool\n\ntool = HFModelDownloadsTool()\n```\n\nYou can also share your custom tool to the Hub by calling [`~Tool.push_to_hub`] on the tool. Make sure you've created a repository for it on the Hub and are using a token with read access.\n\n```python\ntool.push_to_hub(\"{your_username}/hf-model-downloads\")\n```\n\nLoad the tool with the [`~Tool.load_tool`] function and pass it to the `tools` parameter in your agent.\n\n```python\nfrom transformers import load_tool, CodeAgent\n\nmodel_download_tool = load_tool(\"m-ric/hf-model-downloads\")\nagent = CodeAgent(tools=[model_download_tool], llm_engine=llm_engine)\nagent.run(\n    \"Can you give me the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub?\"\n)\n```\n\nYou get the following:\n```text\n======== New task ========\nCan you give me the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub?\n==== Agent is executing the code below:\nmost_downloaded_model = model_download_counter(task=\"text-to-video\")\nprint(f\"The most downloaded model for the 'text-to-video' task is {most_downloaded_model}.\")\n====\n```\n\nAnd the output:\n`\"The most downloaded model for the 'text-to-video' task is ByteDance/AnimateDiff-Lightning.\"`\n\n\n### Manage your agent's toolbox\n\nIf you have already initialized an agent, it is inconvenient to reinitialize it from scratch with a tool you want to use. With Transformers, you can manage an agent's toolbox by adding or replacing a tool.\n\nLet's add the `model_download_tool` to an existing agent initialized with only the default toolbox.\n\n```python\nfrom transformers import CodeAgent\n\nagent = CodeAgent(tools=[], llm_engine=llm_engine, add_base_tools=True)\nagent.toolbox.add_tool(model_download_tool)\n```\nNow we can leverage both the new tool and the previous text-to-speech tool:\n\n```python\nagent.run(\n    \"Can you read out loud the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub and return the audio?\"\n)\n```\n\n\n| **Audio**                                                                                                                                            |\n|------------------------------------------------------------------------------------------------------------------------------------------------------|\n| <audio controls><source src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/damo.wav\" type=\"audio/wav\"/> |\n\n\n> [!WARNING]\n> Beware when adding tools to an agent that already works well because it can bias selection towards your tool or select another tool other than the one already defined.\n\n\nUse the `agent.toolbox.update_tool()` method to replace an existing tool in the agent's toolbox.\nThis is useful if your new tool is a one-to-one replacement of the existing tool because the agent already knows how to perform that specific task.\nJust make sure the new tool follows the same API as the replaced tool or adapt the system prompt template to ensure all examples using the replaced tool are updated."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 440394b3-1a29-4ffb-8c1f-3e06fbedfe01
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5169, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"440394b3-1a29-4ffb-8c1f-3e06fbedfe01\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"6b319276-4cfc-4b19-9444-e4bce696d684\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"59c23c3a8ad0aefa4ce8789029e0bdfa70897112b3745184bb7e11013fc1cbf4\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"17e09ec8-059b-438b-baeb-c29b86591a82\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"c2308414b5a8c0e6cdce58c94828a3f9242201f9c7888611d67ca917ad5d33d6\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"c3fe5058-6331-46dc-a1d1-73a8b8b86089\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"b62fb82e1bdbd6ed7f0ddd97846387ecc4e088ee0ea82873ccaf71b598459f8e\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 17172, \"end_char_idx\": 19766, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "ref_doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "chroma:document": "### Manage your agent's toolbox\n\nIf you have already initialized an agent, it is inconvenient to reinitialize it from scratch with a tool you want to use. With Transformers, you can manage an agent's toolbox by adding or replacing a tool.\n\nLet's add the `model_download_tool` to an existing agent initialized with only the default toolbox.\n\n```python\nfrom transformers import CodeAgent\n\nagent = CodeAgent(tools=[], llm_engine=llm_engine, add_base_tools=True)\nagent.toolbox.add_tool(model_download_tool)\n```\nNow we can leverage both the new tool and the previous text-to-speech tool:\n\n```python\nagent.run(\n    \"Can you read out loud the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub and return the audio?\"\n)\n```\n\n\n| **Audio**                                                                                                                                            |\n|------------------------------------------------------------------------------------------------------------------------------------------------------|\n| <audio controls><source src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/damo.wav\" type=\"audio/wav\"/> |\n\n\n> [!WARNING]\n> Beware when adding tools to an agent that already works well because it can bias selection towards your tool or select another tool other than the one already defined.\n\n\nUse the `agent.toolbox.update_tool()` method to replace an existing tool in the agent's toolbox.\nThis is useful if your new tool is a one-to-one replacement of the existing tool because the agent already knows how to perform that specific task.\nJust make sure the new tool follows the same API as the replaced tool or adapt the system prompt template to ensure all examples using the replaced tool are updated.\n\n\n### Use a collection of tools\n\nYou can leverage tool collections by using the ToolCollection object, with the slug of the collection you want to use.\nThen pass them as a list to initialize you agent, and start using them!\n\n```py\nfrom transformers import ToolCollection, ReactCodeAgent\n\nimage_tool_collection = ToolCollection(collection_slug=\"huggingface-tools/diffusion-tools-6630bb19a942c2306a2cdb6f\")\nagent = ReactCodeAgent(tools=[*image_tool_collection.tools], add_base_tools=True)\n\nagent.run(\"Please draw me a picture of rivers and lakes.\")\n```\n\nTo speed up the start, tools are loaded only if called by the agent.\n\nThis gets you this image:\n\n<img src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rivers_and_lakes.png\">"}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: c3fe5058-6331-46dc-a1d1-73a8b8b86089
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5169, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"c3fe5058-6331-46dc-a1d1-73a8b8b86089\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"6b319276-4cfc-4b19-9444-e4bce696d684\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"59c23c3a8ad0aefa4ce8789029e0bdfa70897112b3745184bb7e11013fc1cbf4\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"440394b3-1a29-4ffb-8c1f-3e06fbedfe01\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"c4454efe4237f2399b07f47836bfb83620409a5324385ff8bf498b14a7a8b90f\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"a60b1c36-6f07-4f2d-948d-142a0c5c2b75\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"37fb43898d0c221117e7f563ec97a41da207080bed7328dedf0a62e450175a68\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 17937, \"end_char_idx\": 21751, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "ref_doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "chroma:document": "| **Audio**                                                                                                                                            |\n|------------------------------------------------------------------------------------------------------------------------------------------------------|\n| <audio controls><source src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/damo.wav\" type=\"audio/wav\"/> |\n\n\n> [!WARNING]\n> Beware when adding tools to an agent that already works well because it can bias selection towards your tool or select another tool other than the one already defined.\n\n\nUse the `agent.toolbox.update_tool()` method to replace an existing tool in the agent's toolbox.\nThis is useful if your new tool is a one-to-one replacement of the existing tool because the agent already knows how to perform that specific task.\nJust make sure the new tool follows the same API as the replaced tool or adapt the system prompt template to ensure all examples using the replaced tool are updated.\n\n\n### Use a collection of tools\n\nYou can leverage tool collections by using the ToolCollection object, with the slug of the collection you want to use.\nThen pass them as a list to initialize you agent, and start using them!\n\n```py\nfrom transformers import ToolCollection, ReactCodeAgent\n\nimage_tool_collection = ToolCollection(collection_slug=\"huggingface-tools/diffusion-tools-6630bb19a942c2306a2cdb6f\")\nagent = ReactCodeAgent(tools=[*image_tool_collection.tools], add_base_tools=True)\n\nagent.run(\"Please draw me a picture of rivers and lakes.\")\n```\n\nTo speed up the start, tools are loaded only if called by the agent.\n\nThis gets you this image:\n\n<img src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rivers_and_lakes.png\">\n\n\n### Use gradio-tools\n\n[gradio-tools](https://github.com/freddyaboulton/gradio-tools) is a powerful library that allows using Hugging\nFace Spaces as tools. It supports many existing Spaces as well as custom Spaces.\n\nTransformers supports `gradio_tools` with the [`Tool.from_gradio`] method. For example, let's use the [`StableDiffusionPromptGeneratorTool`](https://github.com/freddyaboulton/gradio-tools/blob/main/gradio_tools/tools/prompt_generator.py) from `gradio-tools` toolkit for improving prompts to generate better images.\n\nImport and instantiate the tool, then pass it to the `Tool.from_gradio` method:\n\n```python\nfrom gradio_tools import StableDiffusionPromptGeneratorTool\nfrom transformers import Tool, load_tool, CodeAgent\n\ngradio_prompt_generator_tool = StableDiffusionPromptGeneratorTool()\nprompt_generator_tool = Tool.from_gradio(gradio_prompt_generator_tool)\n```\n\nNow you can use it just like any other tool. For example, let's improve the prompt  `a rabbit wearing a space suit`.\n\n```python\nimage_generation_tool = load_tool('huggingface-tools/text-to-image')\nagent = CodeAgent(tools=[prompt_generator_tool, image_generation_tool], llm_engine=llm_engine)\n\nagent.run(\n    \"Improve this prompt, then generate an image of it.\", prompt='A rabbit wearing a space suit'\n)\n```\n\nThe model adequately leverages the tool:\n```text\n======== New task ========\nImprove this prompt, then generate an image of it.\nYou have been provided with these initial arguments: {'prompt': 'A rabbit wearing a space suit'}.\n==== Agent is executing the code below:\nimproved_prompt = StableDiffusionPromptGenerator(query=prompt)\nwhile improved_prompt == \"QUEUE_FULL\":\n    improved_prompt = StableDiffusionPromptGenerator(query=prompt)\nprint(f\"The improved prompt is {improved_prompt}.\")\nimage = image_generator(prompt=improved_prompt)\n====\n```\n\nBefore finally generating the image:\n\n<img src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rabbit.png\">"}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: a60b1c36-6f07-4f2d-948d-142a0c5c2b75
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5169, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"a60b1c36-6f07-4f2d-948d-142a0c5c2b75\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"6b319276-4cfc-4b19-9444-e4bce696d684\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"59c23c3a8ad0aefa4ce8789029e0bdfa70897112b3745184bb7e11013fc1cbf4\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"c3fe5058-6331-46dc-a1d1-73a8b8b86089\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5169, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"6ee320839a77f969c7cbb7c70caa16294d5010c1b76f0a70c2227457ec01a0d4\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 21754, \"end_char_idx\": 22587, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "ref_doc_id": "6b319276-4cfc-4b19-9444-e4bce696d684", "chroma:document": "> [!WARNING]\n> gradio-tools require *textual* inputs and outputs even when working with different modalities like image and audio objects. Image and audio inputs and outputs are currently incompatible.\n\n### Use LangChain tools\n\nWe love Langchain and think it has a very compelling suite of tools.\nTo import a tool from LangChain, use the `from_langchain()` method.\n\nHere is how you can use it to recreate the intro's search result using a LangChain web search tool.\n\n```python\nfrom langchain.agents import load_tools\nfrom transformers import Tool, ReactCodeAgent\n\nsearch_tool = Tool.from_langchain(load_tools([\"serpapi\"])[0])\n\nagent = ReactCodeAgent(tools=[search_tool])\n\nagent.run(\"How many more blocks (also denoted as layers) in BERT base encoder than the encoder from the architecture proposed in Attention is All You Need?\")\n```"}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: f027f808-7a34-42da-a6d8-2e5bfc2ceed0
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/philosophy", "title": "Philosophy", "tokens": 1289, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"f027f808-7a34-42da-a6d8-2e5bfc2ceed0\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/philosophy\", \"title\": \"Philosophy\", \"tokens\": 1289, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"e50bb35a-0f9c-47ff-94d7-51d0c3a48f35\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/philosophy\", \"title\": \"Philosophy\", \"tokens\": 1289, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"4983a475d3ab0a23ac72363becda0b29a8e21c1d3851ad40ab1f87acbe8b622f\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"75556187-fdee-4952-8225-7c09de6c7be4\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"6b282abe1fdaeab27847be3c03cf5c9f5af417d1ff98b5cc7d7500ce718b05e3\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 0, \"end_char_idx\": 3305, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "e50bb35a-0f9c-47ff-94d7-51d0c3a48f35", "doc_id": "e50bb35a-0f9c-47ff-94d7-51d0c3a48f35", "ref_doc_id": "e50bb35a-0f9c-47ff-94d7-51d0c3a48f35", "chroma:document": "# Philosophy\n\n\ud83e\udd17 Transformers is an opinionated library built for:\n\n- machine learning researchers and educators seeking to use, study or extend large-scale Transformers models.\n- hands-on practitioners who want to fine-tune those models or serve them in production, or both.\n- engineers who just want to download a pretrained model and use it to solve a given machine learning task.\n\nThe library was designed with two strong goals in mind:\n\n1. Be as easy and fast to use as possible:\n\n  - We strongly limited the number of user-facing abstractions to learn, in fact, there are almost no abstractions,\n    just three standard classes required to use each model: [configuration](main_classes/configuration),\n    [models](main_classes/model), and a preprocessing class ([tokenizer](main_classes/tokenizer) for NLP, [image processor](main_classes/image_processor) for vision, [feature extractor](main_classes/feature_extractor) for audio, and [processor](main_classes/processors) for multimodal inputs).\n  - 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,\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`] for quickly\n    using a model for inference on a given task and [`Trainer`] to quickly train or fine-tune a PyTorch model (all TensorFlow models are compatible with `Keras.fit`).\n  - As a consequence, this library is NOT a modular toolbox of building blocks for neural nets. If you want to\n    extend or build upon the library, just use regular Python, PyTorch, TensorFlow, Keras modules and inherit from the base\n    classes of the library to reuse functionalities like model loading and saving. If you'd like to learn more about our coding philosophy for models, check out our [Repeat Yourself](https://huggingface.co/blog/transformers-design-philosophy) blog post.\n\n2. Provide state-of-the-art models with performances as close as possible to the original models:\n\n  - We provide at least one example for each architecture which reproduces a result provided by the official authors\n    of said architecture.\n  - The code is usually as close to the original code base as possible which means some PyTorch code may be not as\n    *pytorchic* as it could be as a result of being converted TensorFlow code and vice versa.\n\nA few other goals:\n\n- Expose the models' internals as consistently as possible:\n\n  - We give access, using a single API, to the full hidden-states and attention weights.\n  - The preprocessing classes and base model APIs are standardized to easily switch between models.\n\n- Incorporate a subjective selection of promising tools for fine-tuning and investigating these models:\n\n  - A simple and consistent way to add new tokens to the vocabulary and embeddings for fine-tuning.\n  - Simple ways to mask and prune Transformer heads.\n\n- Easily switch between PyTorch, TensorFlow 2.0 and Flax, allowing training with one framework and inference with another."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 75556187-fdee-4952-8225-7c09de6c7be4
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/philosophy", "title": "Philosophy", "tokens": 1289, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"75556187-fdee-4952-8225-7c09de6c7be4\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/philosophy\", \"title\": \"Philosophy\", \"tokens\": 1289, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"e50bb35a-0f9c-47ff-94d7-51d0c3a48f35\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/philosophy\", \"title\": \"Philosophy\", \"tokens\": 1289, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"4983a475d3ab0a23ac72363becda0b29a8e21c1d3851ad40ab1f87acbe8b622f\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"f027f808-7a34-42da-a6d8-2e5bfc2ceed0\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/philosophy\", \"title\": \"Philosophy\", \"tokens\": 1289, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"fc8a9d35635f59b8774892de5f6f41aadbb50cd816d2ba2a0b2850555c2288a0\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"8b92632d-0fdc-499e-a281-f4dfe43d47bb\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"b5e72fff8aaaa7dee0ec177f6f1691305ae94d5e91286918e78e74a15032e1ec\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 1450, \"end_char_idx\": 5068, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "e50bb35a-0f9c-47ff-94d7-51d0c3a48f35", "doc_id": "e50bb35a-0f9c-47ff-94d7-51d0c3a48f35", "ref_doc_id": "e50bb35a-0f9c-47ff-94d7-51d0c3a48f35", "chroma:document": "- On top of those three base classes, the library provides two APIs: [`pipeline`] for quickly\n    using a model for inference on a given task and [`Trainer`] to quickly train or fine-tune a PyTorch model (all TensorFlow models are compatible with `Keras.fit`).\n  - As a consequence, this library is NOT a modular toolbox of building blocks for neural nets. If you want to\n    extend or build upon the library, just use regular Python, PyTorch, TensorFlow, Keras modules and inherit from the base\n    classes of the library to reuse functionalities like model loading and saving. If you'd like to learn more about our coding philosophy for models, check out our [Repeat Yourself](https://huggingface.co/blog/transformers-design-philosophy) blog post.\n\n2. Provide state-of-the-art models with performances as close as possible to the original models:\n\n  - We provide at least one example for each architecture which reproduces a result provided by the official authors\n    of said architecture.\n  - The code is usually as close to the original code base as possible which means some PyTorch code may be not as\n    *pytorchic* as it could be as a result of being converted TensorFlow code and vice versa.\n\nA few other goals:\n\n- Expose the models' internals as consistently as possible:\n\n  - We give access, using a single API, to the full hidden-states and attention weights.\n  - The preprocessing classes and base model APIs are standardized to easily switch between models.\n\n- Incorporate a subjective selection of promising tools for fine-tuning and investigating these models:\n\n  - A simple and consistent way to add new tokens to the vocabulary and embeddings for fine-tuning.\n  - Simple ways to mask and prune Transformer heads.\n\n- Easily switch between PyTorch, TensorFlow 2.0 and Flax, allowing training with one framework and inference with another.\n\n## Main concepts\n\nThe library is built around three types of classes for each model:\n\n- **Model classes** can be PyTorch models ([torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)), Keras models ([tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model)) or JAX/Flax models ([flax.linen.Module](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html)) that work with the pretrained weights provided in the library.\n- **Configuration classes** store the hyperparameters required to build a model (such as the number of layers and hidden size). You don't always need to instantiate these yourself. In particular, if you are using a pretrained model without any modification, creating the model will automatically take care of instantiating the configuration (which is part of the model).\n- **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 provide methods for encoding and decoding strings in a list of token embedding indices to be fed to a model. [Image processors](main_classes/image_processor) preprocess vision inputs, [feature extractors](main_classes/feature_extractor) preprocess audio inputs, and a [processor](main_classes/processors) handles multimodal inputs.\n\nAll these classes can be instantiated from pretrained instances, saved locally, and shared on the Hub with three methods:\n\n- `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."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 8b92632d-0fdc-499e-a281-f4dfe43d47bb
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/philosophy", "title": "Philosophy", "tokens": 1289, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"8b92632d-0fdc-499e-a281-f4dfe43d47bb\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/philosophy\", \"title\": \"Philosophy\", \"tokens\": 1289, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"e50bb35a-0f9c-47ff-94d7-51d0c3a48f35\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/philosophy\", \"title\": \"Philosophy\", \"tokens\": 1289, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"4983a475d3ab0a23ac72363becda0b29a8e21c1d3851ad40ab1f87acbe8b622f\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"75556187-fdee-4952-8225-7c09de6c7be4\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/philosophy\", \"title\": \"Philosophy\", \"tokens\": 1289, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"49d6ea5744e2f03094dba0f410c1a455dcc95dad84a5836d3dd241892f432956\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 3307, \"end_char_idx\": 5351, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "e50bb35a-0f9c-47ff-94d7-51d0c3a48f35", "doc_id": "e50bb35a-0f9c-47ff-94d7-51d0c3a48f35", "ref_doc_id": "e50bb35a-0f9c-47ff-94d7-51d0c3a48f35", "chroma:document": "## Main concepts\n\nThe library is built around three types of classes for each model:\n\n- **Model classes** can be PyTorch models ([torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)), Keras models ([tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model)) or JAX/Flax models ([flax.linen.Module](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html)) that work with the pretrained weights provided in the library.\n- **Configuration classes** store the hyperparameters required to build a model (such as the number of layers and hidden size). You don't always need to instantiate these yourself. In particular, if you are using a pretrained model without any modification, creating the model will automatically take care of instantiating the configuration (which is part of the model).\n- **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 provide methods for encoding and decoding strings in a list of token embedding indices to be fed to a model. [Image processors](main_classes/image_processor) preprocess vision inputs, [feature extractors](main_classes/feature_extractor) preprocess audio inputs, and a [processor](main_classes/processors) handles multimodal inputs.\n\nAll these classes can be instantiated from pretrained instances, saved locally, and shared on the Hub with three methods:\n\n- `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."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 1a0d9e27-4bdc-4811-afc7-519f7dfc5ae7
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/add_new_pipeline", "title": "How to create a custom pipeline?", "tokens": 2459, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"1a0d9e27-4bdc-4811-afc7-519f7dfc5ae7\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/add_new_pipeline\", \"title\": \"How to create a custom pipeline?\", \"tokens\": 2459, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"e92f453c-f424-4ab2-a416-4b1dcd2194ad\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/add_new_pipeline\", \"title\": \"How to create a custom pipeline?\", \"tokens\": 2459, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"dfc723367cd5a652da183b279025448c9e43e96dcb711ddab3229f7038b46a09\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"78d7b25a-08ca-4778-a30b-04ee8a96c15d\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"4df29ee53ebefe7dd4e6d4cfe2a526e8f13c5186113c82817fdfa82629878812\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 0, \"end_char_idx\": 891, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "e92f453c-f424-4ab2-a416-4b1dcd2194ad", "doc_id": "e92f453c-f424-4ab2-a416-4b1dcd2194ad", "ref_doc_id": "e92f453c-f424-4ab2-a416-4b1dcd2194ad", "chroma:document": "# How to create a custom pipeline?\n\nIn this guide, we will see how to create a custom pipeline and share it on the [Hub](https://hf.co/models) or add it to the\n\ud83e\udd17 Transformers library.\n\nFirst and foremost, you need to decide the raw entries the pipeline will be able to take. It can be strings, raw bytes,\ndictionaries or whatever seems to be the most likely desired input. Try to keep these inputs as pure Python as possible\nas it makes compatibility easier (even through other languages via JSON). Those will be the `inputs` of the\npipeline (`preprocess`).\n\nThen define the `outputs`. Same policy as the `inputs`. The simpler, the better. Those will be the outputs of\n`postprocess` method.\n\nStart by inheriting the base class `Pipeline` with the 4 methods needed to implement `preprocess`,\n`_forward`, `postprocess`, and `_sanitize_parameters`.\n\n\n```python\nfrom transformers import Pipeline"}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 78d7b25a-08ca-4778-a30b-04ee8a96c15d
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/add_new_pipeline", "title": "How to create a custom pipeline?", "tokens": 2459, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"78d7b25a-08ca-4778-a30b-04ee8a96c15d\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/add_new_pipeline\", \"title\": \"How to create a custom pipeline?\", \"tokens\": 2459, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"e92f453c-f424-4ab2-a416-4b1dcd2194ad\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/add_new_pipeline\", \"title\": \"How to create a custom pipeline?\", \"tokens\": 2459, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"dfc723367cd5a652da183b279025448c9e43e96dcb711ddab3229f7038b46a09\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"1a0d9e27-4bdc-4811-afc7-519f7dfc5ae7\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/add_new_pipeline\", \"title\": \"How to create a custom pipeline?\", \"tokens\": 2459, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"5a1bdc5dc9e62136184136e5608d98b7799e6c70c34a6be289716d73f4b98552\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"a6a587e8-26f8-494f-8d96-f8a4caf6bfab\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"3ad1db1736d739b5537e5f409aee2129ce00d29d385af562a6e308d11cfa206b\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 0, \"end_char_idx\": 3544, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "e92f453c-f424-4ab2-a416-4b1dcd2194ad", "doc_id": "e92f453c-f424-4ab2-a416-4b1dcd2194ad", "ref_doc_id": "e92f453c-f424-4ab2-a416-4b1dcd2194ad", "chroma:document": "# How to create a custom pipeline?\n\nIn this guide, we will see how to create a custom pipeline and share it on the [Hub](https://hf.co/models) or add it to the\n\ud83e\udd17 Transformers library.\n\nFirst and foremost, you need to decide the raw entries the pipeline will be able to take. It can be strings, raw bytes,\ndictionaries or whatever seems to be the most likely desired input. Try to keep these inputs as pure Python as possible\nas it makes compatibility easier (even through other languages via JSON). Those will be the `inputs` of the\npipeline (`preprocess`).\n\nThen define the `outputs`. Same policy as the `inputs`. The simpler, the better. Those will be the outputs of\n`postprocess` method.\n\nStart by inheriting the base class `Pipeline` with the 4 methods needed to implement `preprocess`,\n`_forward`, `postprocess`, and `_sanitize_parameters`.\n\n\n```python\nfrom transformers import Pipeline\n\n\nclass MyPipeline(Pipeline):\n    def _sanitize_parameters(self, **kwargs):\n        preprocess_kwargs = {}\n        if \"maybe_arg\" in kwargs:\n            preprocess_kwargs[\"maybe_arg\"] = kwargs[\"maybe_arg\"]\n        return preprocess_kwargs, {}, {}\n\n    def preprocess(self, inputs, maybe_arg=2):\n        model_input = Tensor(inputs[\"input_ids\"])\n        return {\"model_input\": model_input}\n\n    def _forward(self, model_inputs):\n        # model_inputs == {\"model_input\": model_input}\n        outputs = self.model(**model_inputs)\n        # Maybe {\"logits\": Tensor(...)}\n        return outputs\n\n    def postprocess(self, model_outputs):\n        best_class = model_outputs[\"logits\"].softmax(-1)\n        return best_class\n```\n\nThe structure of this breakdown is to support relatively seamless support for CPU/GPU, while supporting doing\npre/postprocessing on the CPU on different threads\n\n`preprocess` will take the originally defined inputs, and turn them into something feedable to the model. It might\ncontain more information and is usually a `Dict`.\n\n`_forward` is the implementation detail and is not meant to be called directly. `forward` is the preferred\ncalled method as it contains safeguards to make sure everything is working on the expected device. If anything is\nlinked to a real model it belongs in the `_forward` method, anything else is in the preprocess/postprocess.\n\n`postprocess` methods will take the output of `_forward` and turn it into the final output that was decided\nearlier.\n\n`_sanitize_parameters` exists to allow users to pass any parameters whenever they wish, be it at initialization\ntime `pipeline(...., maybe_arg=4)` or at call time `pipe = pipeline(...); output = pipe(...., maybe_arg=4)`.\n\nThe returns of `_sanitize_parameters` are the 3 dicts of kwargs that will be passed directly to `preprocess`,\n`_forward`, and `postprocess`. Don't fill anything if the caller didn't call with any extra parameter. That\nallows to keep the default arguments in the function definition which is always more \"natural\".\n\nA classic example would be a `top_k` argument in the post processing in classification tasks.\n\n```python\n>>> pipe = pipeline(\"my-new-task\")\n>>> pipe(\"This is a test\")\n[{\"label\": \"1-star\", \"score\": 0.8}, {\"label\": \"2-star\", \"score\": 0.1}, {\"label\": \"3-star\", \"score\": 0.05}\n{\"label\": \"4-star\", \"score\": 0.025}, {\"label\": \"5-star\", \"score\": 0.025}]\n\n>>> pipe(\"This is a test\", top_k=2)\n[{\"label\": \"1-star\", \"score\": 0.8}, {\"label\": \"2-star\", \"score\": 0.1}]\n```\n\nIn order to achieve that, we'll update our `postprocess` method with a default parameter to `5`. and edit\n`_sanitize_parameters` to allow this new parameter."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: a6a587e8-26f8-494f-8d96-f8a4caf6bfab
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/add_new_pipeline", "title": "How to create a custom pipeline?", "tokens": 2459, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"a6a587e8-26f8-494f-8d96-f8a4caf6bfab\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/add_new_pipeline\", \"title\": \"How to create a custom pipeline?\", \"tokens\": 2459, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"e92f453c-f424-4ab2-a416-4b1dcd2194ad\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/add_new_pipeline\", \"title\": \"How to create a custom pipeline?\", \"tokens\": 2459, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"dfc723367cd5a652da183b279025448c9e43e96dcb711ddab3229f7038b46a09\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"78d7b25a-08ca-4778-a30b-04ee8a96c15d\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/add_new_pipeline\", \"title\": \"How to create a custom pipeline?\", \"tokens\": 2459, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"b8003103246d4f67904e3849182ba389cb80620b3d4c6ed4dc900f6b92d848ec\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"e025e6b5-3a6c-450b-91e0-fb9bb6b50c67\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"645742bf4165fdef73410a9af72f609f053bf3891fc91390c816e280edcd69fa\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 3547, \"end_char_idx\": 6671, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "e92f453c-f424-4ab2-a416-4b1dcd2194ad", "doc_id": "e92f453c-f424-4ab2-a416-4b1dcd2194ad", "ref_doc_id": "e92f453c-f424-4ab2-a416-4b1dcd2194ad", "chroma:document": "```python\ndef postprocess(self, model_outputs, top_k=5):\n    best_class = model_outputs[\"logits\"].softmax(-1)\n    # Add logic to handle top_k\n    return best_class\n\n\ndef _sanitize_parameters(self, **kwargs):\n    preprocess_kwargs = {}\n    if \"maybe_arg\" in kwargs:\n        preprocess_kwargs[\"maybe_arg\"] = kwargs[\"maybe_arg\"]\n\n    postprocess_kwargs = {}\n    if \"top_k\" in kwargs:\n        postprocess_kwargs[\"top_k\"] = kwargs[\"top_k\"]\n    return preprocess_kwargs, {}, postprocess_kwargs\n```\n\nTry to keep the inputs/outputs very simple and ideally JSON-serializable as it makes the pipeline usage very easy\nwithout requiring users to understand new kinds of objects. It's also relatively common to support many different types\nof arguments for ease of use (audio files, which can be filenames, URLs or pure bytes)\n\n\n\n## Adding it to the list of supported tasks\n\nTo register your `new-task` to the list of supported tasks, you have to add it to the `PIPELINE_REGISTRY`:\n\n```python\nfrom transformers.pipelines import PIPELINE_REGISTRY\n\nPIPELINE_REGISTRY.register_pipeline(\n    \"new-task\",\n    pipeline_class=MyPipeline,\n    pt_model=AutoModelForSequenceClassification,\n)\n```\n\nYou can specify a default model if you want, in which case it should come with a specific revision (which can be the name of a branch or a commit hash, here we took `\"abcdef\"`) as well as the type:\n\n```python\nPIPELINE_REGISTRY.register_pipeline(\n    \"new-task\",\n    pipeline_class=MyPipeline,\n    pt_model=AutoModelForSequenceClassification,\n    default={\"pt\": (\"user/awesome_model\", \"abcdef\")},\n    type=\"text\",  # current support type: text, audio, image, multimodal\n)\n```\n\n## Share your pipeline on the Hub\n\nTo share your custom pipeline on the Hub, you just have to save the custom code of your `Pipeline` subclass in a\npython file. For instance, let's say we want to use a custom pipeline for sentence pair classification like this:\n\n```py\nimport numpy as np\n\nfrom transformers import Pipeline\n\n\ndef softmax(outputs):\n    maxes = np.max(outputs, axis=-1, keepdims=True)\n    shifted_exp = np.exp(outputs - maxes)\n    return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True)\n\n\nclass PairClassificationPipeline(Pipeline):\n    def _sanitize_parameters(self, **kwargs):\n        preprocess_kwargs = {}\n        if \"second_text\" in kwargs:\n            preprocess_kwargs[\"second_text\"] = kwargs[\"second_text\"]\n        return preprocess_kwargs, {}, {}\n\n    def preprocess(self, text, second_text=None):\n        return self.tokenizer(text, text_pair=second_text, return_tensors=self.framework)\n\n    def _forward(self, model_inputs):\n        return self.model(**model_inputs)\n\n    def postprocess(self, model_outputs):\n        logits = model_outputs.logits[0].numpy()\n        probabilities = softmax(logits)\n\n        best_class = np.argmax(probabilities)\n        label = self.model.config.id2label[best_class]\n        score = probabilities[best_class].item()\n        logits = logits.tolist()\n        return {\"label\": label, \"score\": score, \"logits\": logits}\n```\n\nThe implementation is framework agnostic, and will work for PyTorch and TensorFlow models."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: e025e6b5-3a6c-450b-91e0-fb9bb6b50c67
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/add_new_pipeline", "title": "How to create a custom pipeline?", "tokens": 2459, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"e025e6b5-3a6c-450b-91e0-fb9bb6b50c67\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/add_new_pipeline\", \"title\": \"How to create a custom pipeline?\", \"tokens\": 2459, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"e92f453c-f424-4ab2-a416-4b1dcd2194ad\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/add_new_pipeline\", \"title\": \"How to create a custom pipeline?\", \"tokens\": 2459, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"dfc723367cd5a652da183b279025448c9e43e96dcb711ddab3229f7038b46a09\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"a6a587e8-26f8-494f-8d96-f8a4caf6bfab\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/add_new_pipeline\", \"title\": \"How to create a custom pipeline?\", \"tokens\": 2459, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"e444a6e1d042f7840ac54f752aa59c8816da1b113c21883faacd20b643982387\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"7c70cf9c-74bf-4c19-86d5-890663bfc38a\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"0109fa6cdc0dc26448456cb225bc2491261baa4645be00eadc10cd95393cd269\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 5522, \"end_char_idx\": 8897, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "e92f453c-f424-4ab2-a416-4b1dcd2194ad", "doc_id": "e92f453c-f424-4ab2-a416-4b1dcd2194ad", "ref_doc_id": "e92f453c-f424-4ab2-a416-4b1dcd2194ad", "chroma:document": "def softmax(outputs):\n    maxes = np.max(outputs, axis=-1, keepdims=True)\n    shifted_exp = np.exp(outputs - maxes)\n    return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True)\n\n\nclass PairClassificationPipeline(Pipeline):\n    def _sanitize_parameters(self, **kwargs):\n        preprocess_kwargs = {}\n        if \"second_text\" in kwargs:\n            preprocess_kwargs[\"second_text\"] = kwargs[\"second_text\"]\n        return preprocess_kwargs, {}, {}\n\n    def preprocess(self, text, second_text=None):\n        return self.tokenizer(text, text_pair=second_text, return_tensors=self.framework)\n\n    def _forward(self, model_inputs):\n        return self.model(**model_inputs)\n\n    def postprocess(self, model_outputs):\n        logits = model_outputs.logits[0].numpy()\n        probabilities = softmax(logits)\n\n        best_class = np.argmax(probabilities)\n        label = self.model.config.id2label[best_class]\n        score = probabilities[best_class].item()\n        logits = logits.tolist()\n        return {\"label\": label, \"score\": score, \"logits\": logits}\n```\n\nThe implementation is framework agnostic, and will work for PyTorch and TensorFlow models. If we have saved this in\na file named `pair_classification.py`, we can then import it and register it like this:\n\n```py\nfrom pair_classification import PairClassificationPipeline\nfrom transformers.pipelines import PIPELINE_REGISTRY\nfrom transformers import AutoModelForSequenceClassification, TFAutoModelForSequenceClassification\n\nPIPELINE_REGISTRY.register_pipeline(\n    \"pair-classification\",\n    pipeline_class=PairClassificationPipeline,\n    pt_model=AutoModelForSequenceClassification,\n    tf_model=TFAutoModelForSequenceClassification,\n)\n```\n\nOnce this is done, we can use it with a pretrained model. For instance `sgugger/finetuned-bert-mrpc` has been\nfine-tuned on the MRPC dataset, which classifies pairs of sentences as paraphrases or not.\n\n```py\nfrom transformers import pipeline\n\nclassifier = pipeline(\"pair-classification\", model=\"sgugger/finetuned-bert-mrpc\")\n```\n\nThen we can share it on the Hub by using the `push_to_hub` method:\n\n```py\nclassifier.push_to_hub(\"test-dynamic-pipeline\")\n```\n\nThis will copy the file where you defined `PairClassificationPipeline` inside the folder `\"test-dynamic-pipeline\"`,\nalong with saving the model and tokenizer of the pipeline, before pushing everything into the repository\n`{your_username}/test-dynamic-pipeline`. After that, anyone can use it as long as they provide the option\n`trust_remote_code=True`:\n\n```py\nfrom transformers import pipeline\n\nclassifier = pipeline(model=\"{your_username}/test-dynamic-pipeline\", trust_remote_code=True)\n```\n\n## Add the pipeline to \ud83e\udd17 Transformers\n\nIf you want to contribute your pipeline to \ud83e\udd17 Transformers, you will need to add a new module in the `pipelines` submodule\nwith the code of your pipeline, then add it to the list of tasks defined in `pipelines/__init__.py`.\n\nThen you will need to add tests. Create a new file `tests/test_pipelines_MY_PIPELINE.py` with examples of the other tests.\n\nThe `run_pipeline_test` function will be very generic and run on small random models on every possible\narchitecture as defined by `model_mapping` and `tf_model_mapping`.\n\nThis is very important to test future compatibility, meaning if someone adds a new model for\n`XXXForQuestionAnswering` then the pipeline test will attempt to run on it."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 7c70cf9c-74bf-4c19-86d5-890663bfc38a
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/add_new_pipeline", "title": "How to create a custom pipeline?", "tokens": 2459, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"7c70cf9c-74bf-4c19-86d5-890663bfc38a\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/add_new_pipeline\", \"title\": \"How to create a custom pipeline?\", \"tokens\": 2459, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"e92f453c-f424-4ab2-a416-4b1dcd2194ad\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/add_new_pipeline\", \"title\": \"How to create a custom pipeline?\", \"tokens\": 2459, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"dfc723367cd5a652da183b279025448c9e43e96dcb711ddab3229f7038b46a09\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"e025e6b5-3a6c-450b-91e0-fb9bb6b50c67\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/add_new_pipeline\", \"title\": \"How to create a custom pipeline?\", \"tokens\": 2459, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"d687fb8640f5efe63d4efff7e4b381b197a161109c1fcdcdb92bd45e5b87f1a4\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 7279, \"end_char_idx\": 10081, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "e92f453c-f424-4ab2-a416-4b1dcd2194ad", "doc_id": "e92f453c-f424-4ab2-a416-4b1dcd2194ad", "ref_doc_id": "e92f453c-f424-4ab2-a416-4b1dcd2194ad", "chroma:document": "For instance `sgugger/finetuned-bert-mrpc` has been\nfine-tuned on the MRPC dataset, which classifies pairs of sentences as paraphrases or not.\n\n```py\nfrom transformers import pipeline\n\nclassifier = pipeline(\"pair-classification\", model=\"sgugger/finetuned-bert-mrpc\")\n```\n\nThen we can share it on the Hub by using the `push_to_hub` method:\n\n```py\nclassifier.push_to_hub(\"test-dynamic-pipeline\")\n```\n\nThis will copy the file where you defined `PairClassificationPipeline` inside the folder `\"test-dynamic-pipeline\"`,\nalong with saving the model and tokenizer of the pipeline, before pushing everything into the repository\n`{your_username}/test-dynamic-pipeline`. After that, anyone can use it as long as they provide the option\n`trust_remote_code=True`:\n\n```py\nfrom transformers import pipeline\n\nclassifier = pipeline(model=\"{your_username}/test-dynamic-pipeline\", trust_remote_code=True)\n```\n\n## Add the pipeline to \ud83e\udd17 Transformers\n\nIf you want to contribute your pipeline to \ud83e\udd17 Transformers, you will need to add a new module in the `pipelines` submodule\nwith the code of your pipeline, then add it to the list of tasks defined in `pipelines/__init__.py`.\n\nThen you will need to add tests. Create a new file `tests/test_pipelines_MY_PIPELINE.py` with examples of the other tests.\n\nThe `run_pipeline_test` function will be very generic and run on small random models on every possible\narchitecture as defined by `model_mapping` and `tf_model_mapping`.\n\nThis is very important to test future compatibility, meaning if someone adds a new model for\n`XXXForQuestionAnswering` then the pipeline test will attempt to run on it. Because the models are random it's\nimpossible to check for actual values, that's why there is a helper `ANY` that will simply attempt to match the\noutput of the pipeline TYPE.\n\nYou also *need* to implement 2 (ideally 4) tests.\n\n- `test_small_model_pt` : Define 1 small model for this pipeline (doesn't matter if the results don't make sense)\n  and test the pipeline outputs. The results should be the same as `test_small_model_tf`.\n- `test_small_model_tf` : Define 1 small model for this pipeline (doesn't matter if the results don't make sense)\n  and test the pipeline outputs. The results should be the same as `test_small_model_pt`.\n- `test_large_model_pt` (`optional`): Tests the pipeline on a real pipeline where the results are supposed to\n  make sense. These tests are slow and should be marked as such. Here the goal is to showcase the pipeline and to make\n  sure there is no drift in future releases.\n- `test_large_model_tf` (`optional`): Tests the pipeline on a real pipeline where the results are supposed to\n  make sense. These tests are slow and should be marked as such. Here the goal is to showcase the pipeline and to make\n  sure there is no drift in future releases."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 1ac3556a-8265-4a3a-87f4-9a899a58ad34
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/multilingual", "title": "Multilingual models for inference", "tokens": 2131, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"1ac3556a-8265-4a3a-87f4-9a899a58ad34\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/multilingual\", \"title\": \"Multilingual models for inference\", \"tokens\": 2131, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"56061158-702f-4a03-9dad-6ee1e382e411\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/multilingual\", \"title\": \"Multilingual models for inference\", \"tokens\": 2131, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"99d49851d4b4888e9d48b6a53ece48eb75860dc6f6a5b1d5abccd4d0e20bfb29\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"e0a5ec3f-c40a-4d26-8bb2-4175175c6863\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"6746c3bd46cebe250934c963231c302122487af67cac19d1d09d2848ba1ac019\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 0, \"end_char_idx\": 2495, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "56061158-702f-4a03-9dad-6ee1e382e411", "doc_id": "56061158-702f-4a03-9dad-6ee1e382e411", "ref_doc_id": "56061158-702f-4a03-9dad-6ee1e382e411", "chroma:document": "# Multilingual models for inference\n\n[[open-in-colab]]\n\nThere are several multilingual models in \ud83e\udd17 Transformers, and their inference usage differs from monolingual models. Not *all* multilingual model usage is different though. Some models, like [google-bert/bert-base-multilingual-uncased](https://huggingface.co/google-bert/bert-base-multilingual-uncased), can be used just like a monolingual model. This guide will show you how to use multilingual models whose usage differs for inference.\n\n## XLM\n\nXLM has ten different checkpoints, only one of which is monolingual. The nine remaining model checkpoints can be split into two categories: the checkpoints that use language embeddings and those that don't.\n\n### XLM with language embeddings\n\nThe following XLM models use language embeddings to specify the language used at inference:\n\n- `FacebookAI/xlm-mlm-ende-1024` (Masked language modeling, English-German)\n- `FacebookAI/xlm-mlm-enfr-1024` (Masked language modeling, English-French)\n- `FacebookAI/xlm-mlm-enro-1024` (Masked language modeling, English-Romanian)\n- `FacebookAI/xlm-mlm-xnli15-1024` (Masked language modeling, XNLI languages)\n- `FacebookAI/xlm-mlm-tlm-xnli15-1024` (Masked language modeling + translation, XNLI languages)\n- `FacebookAI/xlm-clm-enfr-1024` (Causal language modeling, English-French)\n- `FacebookAI/xlm-clm-ende-1024` (Causal language modeling, English-German)\n\nLanguage embeddings are represented as a tensor of the same shape as the `input_ids` passed to the model. The values in these tensors depend on the language used and are identified by the tokenizer's `lang2id` and `id2lang` attributes.\n\nIn this example, load the `FacebookAI/xlm-clm-enfr-1024` checkpoint (Causal language modeling, English-French):\n\n```py\n>>> import torch\n>>> from transformers import XLMTokenizer, XLMWithLMHeadModel\n\n>>> tokenizer = XLMTokenizer.from_pretrained(\"FacebookAI/xlm-clm-enfr-1024\")\n>>> model = XLMWithLMHeadModel.from_pretrained(\"FacebookAI/xlm-clm-enfr-1024\")\n```\n\nThe `lang2id` attribute of the tokenizer displays this model's languages and their ids:\n\n```py\n>>> print(tokenizer.lang2id)\n{'en': 0, 'fr': 1}\n```\n\nNext, create an example input:\n\n```py\n>>> input_ids = torch.tensor([tokenizer.encode(\"Wikipedia was used to\")])  # batch size of 1\n```\n\nSet the language id as `\"en\"` and use it to define the language embedding. The language embedding is a tensor filled with `0` since that is the language id for English. This tensor should be the same size as `input_ids`."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: e0a5ec3f-c40a-4d26-8bb2-4175175c6863
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/multilingual", "title": "Multilingual models for inference", "tokens": 2131, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"e0a5ec3f-c40a-4d26-8bb2-4175175c6863\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/multilingual\", \"title\": \"Multilingual models for inference\", \"tokens\": 2131, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"56061158-702f-4a03-9dad-6ee1e382e411\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/multilingual\", \"title\": \"Multilingual models for inference\", \"tokens\": 2131, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"99d49851d4b4888e9d48b6a53ece48eb75860dc6f6a5b1d5abccd4d0e20bfb29\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"1ac3556a-8265-4a3a-87f4-9a899a58ad34\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/multilingual\", \"title\": \"Multilingual models for inference\", \"tokens\": 2131, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"dd1ec0afdaeb290e8d3391171eadc9dca2f153697dfbc1ef85508d493641a2d6\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"6bd8d42f-3922-45e2-b3e6-a192a560e33a\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"c88e540e08777fdc3c8b653f88e59d7067e87e01d6bdabaafe984397c2c4285d\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 1500, \"end_char_idx\": 4464, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "56061158-702f-4a03-9dad-6ee1e382e411", "doc_id": "56061158-702f-4a03-9dad-6ee1e382e411", "ref_doc_id": "56061158-702f-4a03-9dad-6ee1e382e411", "chroma:document": "The values in these tensors depend on the language used and are identified by the tokenizer's `lang2id` and `id2lang` attributes.\n\nIn this example, load the `FacebookAI/xlm-clm-enfr-1024` checkpoint (Causal language modeling, English-French):\n\n```py\n>>> import torch\n>>> from transformers import XLMTokenizer, XLMWithLMHeadModel\n\n>>> tokenizer = XLMTokenizer.from_pretrained(\"FacebookAI/xlm-clm-enfr-1024\")\n>>> model = XLMWithLMHeadModel.from_pretrained(\"FacebookAI/xlm-clm-enfr-1024\")\n```\n\nThe `lang2id` attribute of the tokenizer displays this model's languages and their ids:\n\n```py\n>>> print(tokenizer.lang2id)\n{'en': 0, 'fr': 1}\n```\n\nNext, create an example input:\n\n```py\n>>> input_ids = torch.tensor([tokenizer.encode(\"Wikipedia was used to\")])  # batch size of 1\n```\n\nSet the language id as `\"en\"` and use it to define the language embedding. The language embedding is a tensor filled with `0` since that is the language id for English. This tensor should be the same size as `input_ids`. \n\n```py\n>>> language_id = tokenizer.lang2id[\"en\"]  # 0\n>>> langs = torch.tensor([language_id] * input_ids.shape[1])  # torch.tensor([0, 0, 0, ..., 0])\n\n>>> # We reshape it to be of size (batch_size, sequence_length)\n>>> langs = langs.view(1, -1)  # is now of shape [1, sequence_length] (we have a batch size of 1)\n```\n\nNow you can pass the `input_ids` and language embedding to the model:\n\n```py\n>>> outputs = model(input_ids, langs=langs)\n```\n\nThe [run_generation.py](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-generation/run_generation.py) script can generate text with language embeddings using the `xlm-clm` checkpoints.\n\n### XLM without language embeddings\n\nThe following XLM models do not require language embeddings during inference:\n\n- `FacebookAI/xlm-mlm-17-1280` (Masked language modeling, 17 languages)\n- `FacebookAI/xlm-mlm-100-1280` (Masked language modeling, 100 languages)\n\nThese models are used for generic sentence representations, unlike the previous XLM checkpoints.\n\n## BERT\n\nThe following BERT models can be used for multilingual tasks:\n\n- `google-bert/bert-base-multilingual-uncased` (Masked language modeling + Next sentence prediction, 102 languages)\n- `google-bert/bert-base-multilingual-cased` (Masked language modeling + Next sentence prediction, 104 languages)\n\nThese models do not require language embeddings during inference. They should identify the language from the\ncontext and infer accordingly.\n\n## XLM-RoBERTa\n\nThe following XLM-RoBERTa models can be used for multilingual tasks:\n\n- `FacebookAI/xlm-roberta-base` (Masked language modeling, 100 languages)\n- `FacebookAI/xlm-roberta-large` (Masked language modeling, 100 languages)\n\nXLM-RoBERTa was trained on 2.5TB of newly created and cleaned CommonCrawl data in 100 languages. It provides strong gains over previously released multilingual models like mBERT or XLM on downstream tasks like classification, sequence labeling, and question answering."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 6bd8d42f-3922-45e2-b3e6-a192a560e33a
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/multilingual", "title": "Multilingual models for inference", "tokens": 2131, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"6bd8d42f-3922-45e2-b3e6-a192a560e33a\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/multilingual\", \"title\": \"Multilingual models for inference\", \"tokens\": 2131, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"56061158-702f-4a03-9dad-6ee1e382e411\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/multilingual\", \"title\": \"Multilingual models for inference\", \"tokens\": 2131, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"99d49851d4b4888e9d48b6a53ece48eb75860dc6f6a5b1d5abccd4d0e20bfb29\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"e0a5ec3f-c40a-4d26-8bb2-4175175c6863\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/multilingual\", \"title\": \"Multilingual models for inference\", \"tokens\": 2131, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f76c63838b6f33a938df9aba2bbb5c3fcefa1d714944b8c12ef7d9dceac77ddd\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"8f0e72fd-6a09-4bde-bcf2-3fde6d21e6c8\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"f2b7cf5c8aae23948aac1ebb6029475bfe9f3b753b870c1e307871e701573ee0\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 3155, \"end_char_idx\": 5747, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "56061158-702f-4a03-9dad-6ee1e382e411", "doc_id": "56061158-702f-4a03-9dad-6ee1e382e411", "ref_doc_id": "56061158-702f-4a03-9dad-6ee1e382e411", "chroma:document": "### XLM without language embeddings\n\nThe following XLM models do not require language embeddings during inference:\n\n- `FacebookAI/xlm-mlm-17-1280` (Masked language modeling, 17 languages)\n- `FacebookAI/xlm-mlm-100-1280` (Masked language modeling, 100 languages)\n\nThese models are used for generic sentence representations, unlike the previous XLM checkpoints.\n\n## BERT\n\nThe following BERT models can be used for multilingual tasks:\n\n- `google-bert/bert-base-multilingual-uncased` (Masked language modeling + Next sentence prediction, 102 languages)\n- `google-bert/bert-base-multilingual-cased` (Masked language modeling + Next sentence prediction, 104 languages)\n\nThese models do not require language embeddings during inference. They should identify the language from the\ncontext and infer accordingly.\n\n## XLM-RoBERTa\n\nThe following XLM-RoBERTa models can be used for multilingual tasks:\n\n- `FacebookAI/xlm-roberta-base` (Masked language modeling, 100 languages)\n- `FacebookAI/xlm-roberta-large` (Masked language modeling, 100 languages)\n\nXLM-RoBERTa was trained on 2.5TB of newly created and cleaned CommonCrawl data in 100 languages. It provides strong gains over previously released multilingual models like mBERT or XLM on downstream tasks like classification, sequence labeling, and question answering.\n\n## M2M100\n\nThe following M2M100 models can be used for multilingual translation:\n\n- `facebook/m2m100_418M` (Translation)\n- `facebook/m2m100_1.2B` (Translation)\n\nIn this example, load the `facebook/m2m100_418M` checkpoint to translate from Chinese to English. You can set the source language in the tokenizer:\n\n```py\n>>> from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer\n\n>>> en_text = \"Do not meddle in the affairs of wizards, for they are subtle and quick to anger.\"\n>>> chinese_text = \"\u4e0d\u8981\u63d2\u624b\u5deb\u5e2b\u7684\u4e8b\u52d9, \u56e0\u70ba\u4ed6\u5011\u662f\u5fae\u5999\u7684, \u5f88\u5feb\u5c31\u6703\u767c\u6012.\"\n\n>>> tokenizer = M2M100Tokenizer.from_pretrained(\"facebook/m2m100_418M\", src_lang=\"zh\")\n>>> model = M2M100ForConditionalGeneration.from_pretrained(\"facebook/m2m100_418M\")\n```\n\nTokenize the text:\n\n```py\n>>> encoded_zh = tokenizer(chinese_text, return_tensors=\"pt\")\n```\n\nM2M100 forces the target language id as the first generated token to translate to the target language. Set the `forced_bos_token_id` to `en` in the `generate` method to translate to English:\n\n```py\n>>> generated_tokens = model.generate(**encoded_zh, forced_bos_token_id=tokenizer.get_lang_id(\"en\"))\n>>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)\n'Do not interfere with the matters of the witches, because they are delicate and will soon be angry.'"}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 8f0e72fd-6a09-4bde-bcf2-3fde6d21e6c8
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/multilingual", "title": "Multilingual models for inference", "tokens": 2131, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"8f0e72fd-6a09-4bde-bcf2-3fde6d21e6c8\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/multilingual\", \"title\": \"Multilingual models for inference\", \"tokens\": 2131, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"56061158-702f-4a03-9dad-6ee1e382e411\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/multilingual\", \"title\": \"Multilingual models for inference\", \"tokens\": 2131, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"99d49851d4b4888e9d48b6a53ece48eb75860dc6f6a5b1d5abccd4d0e20bfb29\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"6bd8d42f-3922-45e2-b3e6-a192a560e33a\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/multilingual\", \"title\": \"Multilingual models for inference\", \"tokens\": 2131, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"545ef307b6b3d86a545bc63b002bcc673feb3b2919c4613e31ee36611de1b871\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"90db475e-ec82-41e5-b4f8-aa062ef5647e\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"17e8accc0199a9afbabeffe6c84019a2b4b25c21e397fd28984dfeebced517cf\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 4293, \"end_char_idx\": 7079, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "56061158-702f-4a03-9dad-6ee1e382e411", "doc_id": "56061158-702f-4a03-9dad-6ee1e382e411", "ref_doc_id": "56061158-702f-4a03-9dad-6ee1e382e411", "chroma:document": "It provides strong gains over previously released multilingual models like mBERT or XLM on downstream tasks like classification, sequence labeling, and question answering.\n\n## M2M100\n\nThe following M2M100 models can be used for multilingual translation:\n\n- `facebook/m2m100_418M` (Translation)\n- `facebook/m2m100_1.2B` (Translation)\n\nIn this example, load the `facebook/m2m100_418M` checkpoint to translate from Chinese to English. You can set the source language in the tokenizer:\n\n```py\n>>> from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer\n\n>>> en_text = \"Do not meddle in the affairs of wizards, for they are subtle and quick to anger.\"\n>>> chinese_text = \"\u4e0d\u8981\u63d2\u624b\u5deb\u5e2b\u7684\u4e8b\u52d9, \u56e0\u70ba\u4ed6\u5011\u662f\u5fae\u5999\u7684, \u5f88\u5feb\u5c31\u6703\u767c\u6012.\"\n\n>>> tokenizer = M2M100Tokenizer.from_pretrained(\"facebook/m2m100_418M\", src_lang=\"zh\")\n>>> model = M2M100ForConditionalGeneration.from_pretrained(\"facebook/m2m100_418M\")\n```\n\nTokenize the text:\n\n```py\n>>> encoded_zh = tokenizer(chinese_text, return_tensors=\"pt\")\n```\n\nM2M100 forces the target language id as the first generated token to translate to the target language. Set the `forced_bos_token_id` to `en` in the `generate` method to translate to English:\n\n```py\n>>> generated_tokens = model.generate(**encoded_zh, forced_bos_token_id=tokenizer.get_lang_id(\"en\"))\n>>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)\n'Do not interfere with the matters of the witches, because they are delicate and will soon be angry.'\n```\n\n## MBart\n\nThe following MBart models can be used for multilingual translation:\n\n- `facebook/mbart-large-50-one-to-many-mmt` (One-to-many multilingual machine translation, 50 languages)\n- `facebook/mbart-large-50-many-to-many-mmt` (Many-to-many multilingual machine translation, 50 languages)\n- `facebook/mbart-large-50-many-to-one-mmt` (Many-to-one multilingual machine translation, 50 languages)\n- `facebook/mbart-large-50` (Multilingual translation, 50 languages)\n- `facebook/mbart-large-cc25`\n\nIn this example, load the `facebook/mbart-large-50-many-to-many-mmt` checkpoint to translate Finnish to English. You can set the source language in the tokenizer:\n\n```py\n>>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM\n\n>>> en_text = \"Do not meddle in the affairs of wizards, for they are subtle and quick to anger.\"\n>>> fi_text = \"\u00c4l\u00e4 sekaannu velhojen asioihin, sill\u00e4 ne ovat hienovaraisia ja nopeasti vihaisia.\"\n\n>>> tokenizer = AutoTokenizer.from_pretrained(\"facebook/mbart-large-50-many-to-many-mmt\", src_lang=\"fi_FI\")\n>>> model = AutoModelForSeq2SeqLM.from_pretrained(\"facebook/mbart-large-50-many-to-many-mmt\")\n```\n\nTokenize the text:\n\n```py\n>>> encoded_en = tokenizer(en_text, return_tensors=\"pt\")\n```\n\nMBart forces the target language id as the first generated token to translate to the target language."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 90db475e-ec82-41e5-b4f8-aa062ef5647e
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/multilingual", "title": "Multilingual models for inference", "tokens": 2131, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"90db475e-ec82-41e5-b4f8-aa062ef5647e\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/multilingual\", \"title\": \"Multilingual models for inference\", \"tokens\": 2131, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"56061158-702f-4a03-9dad-6ee1e382e411\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/multilingual\", \"title\": \"Multilingual models for inference\", \"tokens\": 2131, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"99d49851d4b4888e9d48b6a53ece48eb75860dc6f6a5b1d5abccd4d0e20bfb29\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"8f0e72fd-6a09-4bde-bcf2-3fde6d21e6c8\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/multilingual\", \"title\": \"Multilingual models for inference\", \"tokens\": 2131, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"178e8d36ec7f838dd3801571daf9668cdc117479b261d291e2981659140f661d\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 5748, \"end_char_idx\": 7633, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "56061158-702f-4a03-9dad-6ee1e382e411", "doc_id": "56061158-702f-4a03-9dad-6ee1e382e411", "ref_doc_id": "56061158-702f-4a03-9dad-6ee1e382e411", "chroma:document": "```\n\n## MBart\n\nThe following MBart models can be used for multilingual translation:\n\n- `facebook/mbart-large-50-one-to-many-mmt` (One-to-many multilingual machine translation, 50 languages)\n- `facebook/mbart-large-50-many-to-many-mmt` (Many-to-many multilingual machine translation, 50 languages)\n- `facebook/mbart-large-50-many-to-one-mmt` (Many-to-one multilingual machine translation, 50 languages)\n- `facebook/mbart-large-50` (Multilingual translation, 50 languages)\n- `facebook/mbart-large-cc25`\n\nIn this example, load the `facebook/mbart-large-50-many-to-many-mmt` checkpoint to translate Finnish to English. You can set the source language in the tokenizer:\n\n```py\n>>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM\n\n>>> en_text = \"Do not meddle in the affairs of wizards, for they are subtle and quick to anger.\"\n>>> fi_text = \"\u00c4l\u00e4 sekaannu velhojen asioihin, sill\u00e4 ne ovat hienovaraisia ja nopeasti vihaisia.\"\n\n>>> tokenizer = AutoTokenizer.from_pretrained(\"facebook/mbart-large-50-many-to-many-mmt\", src_lang=\"fi_FI\")\n>>> model = AutoModelForSeq2SeqLM.from_pretrained(\"facebook/mbart-large-50-many-to-many-mmt\")\n```\n\nTokenize the text:\n\n```py\n>>> encoded_en = tokenizer(en_text, return_tensors=\"pt\")\n```\n\nMBart forces the target language id as the first generated token to translate to the target language. Set the `forced_bos_token_id` to `en` in the `generate` method to translate to English:\n\n```py\n>>> generated_tokens = model.generate(**encoded_en, forced_bos_token_id=tokenizer.lang_code_to_id[\"en_XX\"])\n>>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)\n\"Don't interfere with the wizard's affairs, because they are subtle, will soon get angry.\"\n```\n\nIf you are using the `facebook/mbart-large-50-many-to-one-mmt` checkpoint, you don't need to force the target language id as the first generated token otherwise the usage is the same."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: f6d16d56-0029-4b12-b8d9-75aa22e78236
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"f6d16d56-0029-4b12-b8d9-75aa22e78236\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"4696622d-0fbc-4438-b7b9-4d41582f3855\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"547ee66977115761f6778ec77a0f4395de63815dbe390968fa02dc78b9a4a944\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"1cee13c9-ba59-4fcb-940e-12c524468bdf\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"1635fd4e22cf59f4b430f695011bf44b5fffba2c7c4672a4914ecc2f1e15e203\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 0, \"end_char_idx\": 3468, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "doc_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "ref_doc_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "chroma:document": "# Debugging\n\nTraining on multiple GPUs can be a tricky endeavor whether you're running into installation issues or communication problems between your GPUs. This debugging guide covers some issues you may run into and how to resolve them.\n\n## DeepSpeed CUDA installation\n\nIf you're using DeepSpeed, you've probably already installed it with the following command.\n\n```bash\npip install deepspeed\n```\n\nDeepSpeed compiles CUDA C++ code and it can be a potential source of errors when building PyTorch extensions that require CUDA. These errors depend on how CUDA is installed on your system, and this section focuses on PyTorch built with *CUDA 10.2*.\n\n<Tip>\n\nFor any other installation issues, please [open an issue](https://github.com/microsoft/DeepSpeed/issues) with the DeepSpeed team.\n\n</Tip>\n\n### Non-identical CUDA toolkits\n\nPyTorch comes with its own CUDA toolkit, but to use DeepSpeed with PyTorch, you need to have an identical version of CUDA installed system-wide. For example, if you installed PyTorch with `cudatoolkit==10.2` in your Python environment, then you'll also need to have CUDA 10.2 installed system-wide. If you don't have CUDA installed system-wide, you should install it first.\n\nThe exact location may vary from system to system, but `usr/local/cuda-10.2` is the most common location on many Unix systems. When CUDA is correctly setup and added to your `PATH` environment variable, you can find the installation location with the following command:\n\n```bash\nwhich nvcc\n```\n\n### Multiple CUDA toolkits\n\nYou may also have more than one CUDA toolkit installed system-wide.\n\n```bash\n/usr/local/cuda-10.2\n/usr/local/cuda-11.0\n```\n\nTypically, package installers set the paths to whatever the last version was installed. If the package build fails because it can't find the right CUDA version (despite it being installed system-wide already), then you need to configure the `PATH` and `LD_LIBRARY_PATH` environment variables to point to the correct path.\n\nTake a look at the contents of these environment variables first:\n\n```bash\necho $PATH\necho $LD_LIBRARY_PATH\n```\n\n`PATH` lists the locations of the executables and `LD_LIBRARY_PATH` lists where to look for shared libraries. Earlier entries are prioritized over later ones, and `:` is used to separate multiple entries. To tell the build program where to find the specific CUDA toolkit you want, insert the correct path to list first. This command prepends rather than overwrites the existing values.\n\n```bash\n# adjust the version and full path if needed\nexport PATH=/usr/local/cuda-10.2/bin:$PATH\nexport LD_LIBRARY_PATH=/usr/local/cuda-10.2/lib64:$LD_LIBRARY_PATH\n```\n\nIn addition, you should also check the directories you assign actually exist. The `lib64` sub-directory contains various CUDA `.so` objects (like `libcudart.so`) and while it is unlikely your system names them differently, you should check the actual names and change them accordingly.\n\n### Older CUDA versions\n\nSometimes, older CUDA versions may refuse to build with newer compilers. For example, if you have `gcc-9` but CUDA wants `gcc-7`. Usually, installing the latest CUDA toolkit enables support for the newer compiler.\n\nYou could also install an older version of the compiler in addition to the one you're currently using (or it may already be installed but it's not used by default and the build system can't see it). To resolve this, you can create a symlink to give the build system visibility to the older compiler."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 1cee13c9-ba59-4fcb-940e-12c524468bdf
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"1cee13c9-ba59-4fcb-940e-12c524468bdf\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"4696622d-0fbc-4438-b7b9-4d41582f3855\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"547ee66977115761f6778ec77a0f4395de63815dbe390968fa02dc78b9a4a944\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"f6d16d56-0029-4b12-b8d9-75aa22e78236\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"6a2b8a6790004e7a196543e42a6464a579b2ee21af138cd57f97ad0ce280ad85\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"27446ea5-c49b-4e57-89a5-d48cdff00add\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"b17cdd84ce2e3fef5fce5abab17b3b17fe97571a06420e6851585ff069949e56\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 1739, \"end_char_idx\": 4520, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "doc_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "ref_doc_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "chroma:document": "If the package build fails because it can't find the right CUDA version (despite it being installed system-wide already), then you need to configure the `PATH` and `LD_LIBRARY_PATH` environment variables to point to the correct path.\n\nTake a look at the contents of these environment variables first:\n\n```bash\necho $PATH\necho $LD_LIBRARY_PATH\n```\n\n`PATH` lists the locations of the executables and `LD_LIBRARY_PATH` lists where to look for shared libraries. Earlier entries are prioritized over later ones, and `:` is used to separate multiple entries. To tell the build program where to find the specific CUDA toolkit you want, insert the correct path to list first. This command prepends rather than overwrites the existing values.\n\n```bash\n# adjust the version and full path if needed\nexport PATH=/usr/local/cuda-10.2/bin:$PATH\nexport LD_LIBRARY_PATH=/usr/local/cuda-10.2/lib64:$LD_LIBRARY_PATH\n```\n\nIn addition, you should also check the directories you assign actually exist. The `lib64` sub-directory contains various CUDA `.so` objects (like `libcudart.so`) and while it is unlikely your system names them differently, you should check the actual names and change them accordingly.\n\n### Older CUDA versions\n\nSometimes, older CUDA versions may refuse to build with newer compilers. For example, if you have `gcc-9` but CUDA wants `gcc-7`. Usually, installing the latest CUDA toolkit enables support for the newer compiler.\n\nYou could also install an older version of the compiler in addition to the one you're currently using (or it may already be installed but it's not used by default and the build system can't see it). To resolve this, you can create a symlink to give the build system visibility to the older compiler.\n\n```bash\n# adapt the path to your system\nsudo ln -s /usr/bin/gcc-7  /usr/local/cuda-10.2/bin/gcc\nsudo ln -s /usr/bin/g++-7  /usr/local/cuda-10.2/bin/g++\n```\n\n### Prebuild\n\nIf you're still having issues with installing DeepSpeed or if you're building DeepSpeed at run time, you can try to prebuild the DeepSpeed modules before installing them. To make a local build for DeepSpeed:\n\n```bash\ngit clone https://github.com/microsoft/DeepSpeed/\ncd DeepSpeed\nrm -rf build\nTORCH_CUDA_ARCH_LIST=\"8.6\" DS_BUILD_CPU_ADAM=1 DS_BUILD_UTILS=1 pip install . \\\n--global-option=\"build_ext\" --global-option=\"-j8\" --no-cache -v \\\n--disable-pip-version-check 2>&1 | tee build.log\n```\n\n<Tip>\n\nTo use NVMe offload, add the `DS_BUILD_AIO=1` parameter to the build command and make sure you install the libaio-dev package system-wide.\n\n</Tip>\n\nNext, you'll have to specify your GPU's architecture by editing the `TORCH_CUDA_ARCH_LIST` variable (find a complete list of NVIDIA GPUs and their corresponding architectures on this [page](https://developer.nvidia.com/cuda-gpus))."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 27446ea5-c49b-4e57-89a5-d48cdff00add
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"27446ea5-c49b-4e57-89a5-d48cdff00add\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"4696622d-0fbc-4438-b7b9-4d41582f3855\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"547ee66977115761f6778ec77a0f4395de63815dbe390968fa02dc78b9a4a944\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"1cee13c9-ba59-4fcb-940e-12c524468bdf\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"915ac2171943b31988024743b6ccda8c5a05f467dcb682bce6a4eb09dfd6c696\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"a670987e-8c5e-4781-85be-cd1caa5e9d4a\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"8a12dec6c11fbf78aa24e990ad2d9ad9c584ecff3a4e98d1d9f0b156676110d3\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 3027, \"end_char_idx\": 5739, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "doc_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "ref_doc_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "chroma:document": "For example, if you have `gcc-9` but CUDA wants `gcc-7`. Usually, installing the latest CUDA toolkit enables support for the newer compiler.\n\nYou could also install an older version of the compiler in addition to the one you're currently using (or it may already be installed but it's not used by default and the build system can't see it). To resolve this, you can create a symlink to give the build system visibility to the older compiler.\n\n```bash\n# adapt the path to your system\nsudo ln -s /usr/bin/gcc-7  /usr/local/cuda-10.2/bin/gcc\nsudo ln -s /usr/bin/g++-7  /usr/local/cuda-10.2/bin/g++\n```\n\n### Prebuild\n\nIf you're still having issues with installing DeepSpeed or if you're building DeepSpeed at run time, you can try to prebuild the DeepSpeed modules before installing them. To make a local build for DeepSpeed:\n\n```bash\ngit clone https://github.com/microsoft/DeepSpeed/\ncd DeepSpeed\nrm -rf build\nTORCH_CUDA_ARCH_LIST=\"8.6\" DS_BUILD_CPU_ADAM=1 DS_BUILD_UTILS=1 pip install . \\\n--global-option=\"build_ext\" --global-option=\"-j8\" --no-cache -v \\\n--disable-pip-version-check 2>&1 | tee build.log\n```\n\n<Tip>\n\nTo use NVMe offload, add the `DS_BUILD_AIO=1` parameter to the build command and make sure you install the libaio-dev package system-wide.\n\n</Tip>\n\nNext, you'll have to specify your GPU's architecture by editing the `TORCH_CUDA_ARCH_LIST` variable (find a complete list of NVIDIA GPUs and their corresponding architectures on this [page](https://developer.nvidia.com/cuda-gpus)). To check the PyTorch version that corresponds to your architecture, run the following command:\n\n```bash\npython -c \"import torch; print(torch.cuda.get_arch_list())\"\n```\n\nFind the architecture for a GPU with the following command:\n\n<hfoptions id=\"arch\">\n<hfoption id=\"same GPUs\">\n\n```bash\nCUDA_VISIBLE_DEVICES=0 python -c \"import torch; print(torch.cuda.get_device_capability())\"\n```\n\n</hfoption>\n<hfoption id=\"specific GPU\">\n\nTo find the architecture for GPU `0`:\n\n```bash\nCUDA_VISIBLE_DEVICES=0 python -c \"import torch; \\\nprint(torch.cuda.get_device_properties(torch.device('cuda')))\n\"_CudaDeviceProperties(name='GeForce RTX 3090', major=8, minor=6, total_memory=24268MB, multi_processor_count=82)\"\n```\n\nThis means your GPU architecture is `8.6`.\n\n</hfoption>\n</hfoptions>\n\nIf you get `8, 6`, then you can set `TORCH_CUDA_ARCH_LIST=\"8.6\"`. For multiple GPUs with different architectures, list them like `TORCH_CUDA_ARCH_LIST=\"6.1;8.6\"`.\n\nIt is also possible to not specify `TORCH_CUDA_ARCH_LIST` and the build program automatically queries the GPU architecture of the build. However, it may or may not match the actual GPU on the target machine which is why it is better to explicitly specify the correct architecture."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: a670987e-8c5e-4781-85be-cd1caa5e9d4a
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"a670987e-8c5e-4781-85be-cd1caa5e9d4a\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"4696622d-0fbc-4438-b7b9-4d41582f3855\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"547ee66977115761f6778ec77a0f4395de63815dbe390968fa02dc78b9a4a944\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"27446ea5-c49b-4e57-89a5-d48cdff00add\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f11f7473bb66309ee7128bab94dce7a93966e9d6014d08a483d0c9ed90ef45a9\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"a3011077-9cde-4e33-b07c-ea24a7093a04\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"d41a0b1ff0448b3bca8072a63edd39838056f5c3adb7a07e32a1afb634b19516\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 4281, \"end_char_idx\": 7107, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "doc_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "ref_doc_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "chroma:document": "</Tip>\n\nNext, you'll have to specify your GPU's architecture by editing the `TORCH_CUDA_ARCH_LIST` variable (find a complete list of NVIDIA GPUs and their corresponding architectures on this [page](https://developer.nvidia.com/cuda-gpus)). To check the PyTorch version that corresponds to your architecture, run the following command:\n\n```bash\npython -c \"import torch; print(torch.cuda.get_arch_list())\"\n```\n\nFind the architecture for a GPU with the following command:\n\n<hfoptions id=\"arch\">\n<hfoption id=\"same GPUs\">\n\n```bash\nCUDA_VISIBLE_DEVICES=0 python -c \"import torch; print(torch.cuda.get_device_capability())\"\n```\n\n</hfoption>\n<hfoption id=\"specific GPU\">\n\nTo find the architecture for GPU `0`:\n\n```bash\nCUDA_VISIBLE_DEVICES=0 python -c \"import torch; \\\nprint(torch.cuda.get_device_properties(torch.device('cuda')))\n\"_CudaDeviceProperties(name='GeForce RTX 3090', major=8, minor=6, total_memory=24268MB, multi_processor_count=82)\"\n```\n\nThis means your GPU architecture is `8.6`.\n\n</hfoption>\n</hfoptions>\n\nIf you get `8, 6`, then you can set `TORCH_CUDA_ARCH_LIST=\"8.6\"`. For multiple GPUs with different architectures, list them like `TORCH_CUDA_ARCH_LIST=\"6.1;8.6\"`.\n\nIt is also possible to not specify `TORCH_CUDA_ARCH_LIST` and the build program automatically queries the GPU architecture of the build. However, it may or may not match the actual GPU on the target machine which is why it is better to explicitly specify the correct architecture.\n\nFor training on multiple machines with the same setup, you'll need to make a binary wheel:\n\n```bash\ngit clone https://github.com/microsoft/DeepSpeed/\ncd DeepSpeed\nrm -rf build\nTORCH_CUDA_ARCH_LIST=\"8.6\" DS_BUILD_CPU_ADAM=1 DS_BUILD_UTILS=1 \\\npython setup.py build_ext -j8 bdist_wheel\n```\n\nThis command generates a binary wheel that'll look something like `dist/deepspeed-0.3.13+8cd046f-cp38-cp38-linux_x86_64.whl`. Now you can install this wheel locally or on another machine.\n\n```bash\npip install deepspeed-0.3.13+8cd046f-cp38-cp38-linux_x86_64.whl\n```\n\n## Multi-GPU Network Issues Debug\n\nWhen training or inferencing with `DistributedDataParallel` and multiple GPU, if you run into issue of inter-communication between processes and/or nodes, you can use the following script to diagnose network issues.\n\n```bash\nwget https://raw.githubusercontent.com/huggingface/transformers/main/scripts/distributed/torch-distributed-gpu-test.py\n```\n\nFor example to test how 2 GPUs interact do:\n\n```bash\npython -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py\n```\nIf both processes can talk to each and allocate GPU memory each will print an OK status.\n\nFor more GPUs or nodes adjust the arguments in the script.\n\nYou will find a lot more details inside the diagnostics script and even a recipe to how you could run it in a SLURM environment."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: a3011077-9cde-4e33-b07c-ea24a7093a04
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"a3011077-9cde-4e33-b07c-ea24a7093a04\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"4696622d-0fbc-4438-b7b9-4d41582f3855\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"547ee66977115761f6778ec77a0f4395de63815dbe390968fa02dc78b9a4a944\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"a670987e-8c5e-4781-85be-cd1caa5e9d4a\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"414ee40dcbacb3931e287db6de74897e3d22bdf6d4a2e05cbab24f5ac04bbd6f\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"c5fd7d45-d2b0-4f99-8a9b-143371ed2113\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"576d36afd6b8fa648b546efa9eacd29548d4bf6136e8638374b50434909888bf\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 5596, \"end_char_idx\": 8770, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "doc_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "ref_doc_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "chroma:document": "However, it may or may not match the actual GPU on the target machine which is why it is better to explicitly specify the correct architecture.\n\nFor training on multiple machines with the same setup, you'll need to make a binary wheel:\n\n```bash\ngit clone https://github.com/microsoft/DeepSpeed/\ncd DeepSpeed\nrm -rf build\nTORCH_CUDA_ARCH_LIST=\"8.6\" DS_BUILD_CPU_ADAM=1 DS_BUILD_UTILS=1 \\\npython setup.py build_ext -j8 bdist_wheel\n```\n\nThis command generates a binary wheel that'll look something like `dist/deepspeed-0.3.13+8cd046f-cp38-cp38-linux_x86_64.whl`. Now you can install this wheel locally or on another machine.\n\n```bash\npip install deepspeed-0.3.13+8cd046f-cp38-cp38-linux_x86_64.whl\n```\n\n## Multi-GPU Network Issues Debug\n\nWhen training or inferencing with `DistributedDataParallel` and multiple GPU, if you run into issue of inter-communication between processes and/or nodes, you can use the following script to diagnose network issues.\n\n```bash\nwget https://raw.githubusercontent.com/huggingface/transformers/main/scripts/distributed/torch-distributed-gpu-test.py\n```\n\nFor example to test how 2 GPUs interact do:\n\n```bash\npython -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py\n```\nIf both processes can talk to each and allocate GPU memory each will print an OK status.\n\nFor more GPUs or nodes adjust the arguments in the script.\n\nYou will find a lot more details inside the diagnostics script and even a recipe to how you could run it in a SLURM environment.\n\nAn additional level of debug is to add `NCCL_DEBUG=INFO` environment variable as follows:\n\n```bash\nNCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py\n```\n\nThis will dump a lot of NCCL-related debug information, which you can then search online if you find that some problems are reported. Or if you're not sure how to interpret the output you can share the log file in an Issue.\n\n\n\n## Underflow and Overflow Detection\n\n<Tip>\n\nThis feature is currently available for PyTorch-only.\n\n</Tip>\n\n<Tip>\n\nFor multi-GPU training it requires DDP (`torch.distributed.launch`).\n\n</Tip>\n\n<Tip>\n\nThis feature can be used with any `nn.Module`-based model.\n\n</Tip>\n\nIf you start getting `loss=NaN` or the model inhibits some other abnormal behavior due to `inf` or `nan` in\nactivations or weights one needs to discover where the first underflow or overflow happens and what led to it. Luckily\nyou can accomplish that easily by activating a special module that will do the detection automatically.\n\nIf you're using [`Trainer`], you just need to add:\n\n```bash\n--debug underflow_overflow\n```\n\nto the normal command line arguments, or pass `debug=\"underflow_overflow\"` when creating the\n[`TrainingArguments`] object.\n\nIf you're using your own training loop or another Trainer you can accomplish the same with:\n\n```python\nfrom transformers.debug_utils import DebugUnderflowOverflow\n\ndebug_overflow = DebugUnderflowOverflow(model)\n```\n\n[`~debug_utils.DebugUnderflowOverflow`] inserts hooks into the model that immediately after each\nforward call will test input and output variables and also the corresponding module's weights."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: c5fd7d45-d2b0-4f99-8a9b-143371ed2113
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"c5fd7d45-d2b0-4f99-8a9b-143371ed2113\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"4696622d-0fbc-4438-b7b9-4d41582f3855\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"547ee66977115761f6778ec77a0f4395de63815dbe390968fa02dc78b9a4a944\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"a3011077-9cde-4e33-b07c-ea24a7093a04\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"a69cdb79381112f6e1a581b063f9356133617e7428fb12c061f5712d2aff9ae9\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"4e07793d-4900-485e-8407-8d798c061ddf\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"3b519da78cade1bab1818163fb8e6cd49b88da400252a093db6444e3b11b5a7c\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 7109, \"end_char_idx\": 10398, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "doc_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "ref_doc_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "chroma:document": "An additional level of debug is to add `NCCL_DEBUG=INFO` environment variable as follows:\n\n```bash\nNCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py\n```\n\nThis will dump a lot of NCCL-related debug information, which you can then search online if you find that some problems are reported. Or if you're not sure how to interpret the output you can share the log file in an Issue.\n\n\n\n## Underflow and Overflow Detection\n\n<Tip>\n\nThis feature is currently available for PyTorch-only.\n\n</Tip>\n\n<Tip>\n\nFor multi-GPU training it requires DDP (`torch.distributed.launch`).\n\n</Tip>\n\n<Tip>\n\nThis feature can be used with any `nn.Module`-based model.\n\n</Tip>\n\nIf you start getting `loss=NaN` or the model inhibits some other abnormal behavior due to `inf` or `nan` in\nactivations or weights one needs to discover where the first underflow or overflow happens and what led to it. Luckily\nyou can accomplish that easily by activating a special module that will do the detection automatically.\n\nIf you're using [`Trainer`], you just need to add:\n\n```bash\n--debug underflow_overflow\n```\n\nto the normal command line arguments, or pass `debug=\"underflow_overflow\"` when creating the\n[`TrainingArguments`] object.\n\nIf you're using your own training loop or another Trainer you can accomplish the same with:\n\n```python\nfrom transformers.debug_utils import DebugUnderflowOverflow\n\ndebug_overflow = DebugUnderflowOverflow(model)\n```\n\n[`~debug_utils.DebugUnderflowOverflow`] inserts hooks into the model that immediately after each\nforward call will test input and output variables and also the corresponding module's weights. As soon as `inf` or\n`nan` is detected in at least one element of the activations or weights, the program will assert and print a report\nlike this (this was caught with `google/mt5-small` under fp16 mixed precision):\n\n```\nDetected inf/nan during batch_number=0\nLast 21 forward frames:\nabs min  abs max  metadata\n                  encoder.block.1.layer.1.DenseReluDense.dropout Dropout\n0.00e+00 2.57e+02 input[0]\n0.00e+00 2.85e+02 output\n[...]\n                  encoder.block.2.layer.0 T5LayerSelfAttention\n6.78e-04 3.15e+03 input[0]\n2.65e-04 3.42e+03 output[0]\n             None output[1]\n2.25e-01 1.00e+04 output[2]\n                  encoder.block.2.layer.1.layer_norm T5LayerNorm\n8.69e-02 4.18e-01 weight\n2.65e-04 3.42e+03 input[0]\n1.79e-06 4.65e+00 output\n                  encoder.block.2.layer.1.DenseReluDense.wi_0 Linear\n2.17e-07 4.50e+00 weight\n1.79e-06 4.65e+00 input[0]\n2.68e-06 3.70e+01 output\n                  encoder.block.2.layer.1.DenseReluDense.wi_1 Linear\n8.08e-07 2.66e+01 weight\n1.79e-06 4.65e+00 input[0]\n1.27e-04 2.37e+02 output\n                  encoder.block.2.layer.1.DenseReluDense.dropout Dropout\n0.00e+00 8.76e+03 input[0]\n0.00e+00 9.74e+03 output\n                  encoder.block.2.layer.1.DenseReluDense.wo Linear\n1.01e-06 6.44e+00 weight\n0.00e+00 9.74e+03 input[0]\n3.18e-04 6.27e+04 output\n                  encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense\n1.79e-06 4.65e+00 input[0]\n3.18e-04 6.27e+04 output\n                  encoder.block.2.layer.1.dropout Dropout\n3.18e-04 6.27e+04 input[0]\n0.00e+00      inf output\n```\n\nThe example output has been trimmed in the middle for brevity."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 4e07793d-4900-485e-8407-8d798c061ddf
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"4e07793d-4900-485e-8407-8d798c061ddf\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"4696622d-0fbc-4438-b7b9-4d41582f3855\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"547ee66977115761f6778ec77a0f4395de63815dbe390968fa02dc78b9a4a944\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"c5fd7d45-d2b0-4f99-8a9b-143371ed2113\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"78d7aa0196a160fcb4a24199784dd0958b671579a5c1077de68f02bb9233accf\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"692ebacd-b849-40ee-bc28-09967fc33c97\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"e8bca47fc6f6d00970b20c72a3aebb19b78a20df0ae9f0d10da2fd63e2693fcd\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 10400, \"end_char_idx\": 12865, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "doc_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "ref_doc_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "chroma:document": "The second column shows the value of the absolute largest element, so if you have a closer look at the last few frames,\nthe inputs and outputs were in the range of `1e4`. So when this training was done under fp16 mixed precision the very\nlast step overflowed (since under `fp16` the largest number before `inf` is `64e3`). To avoid overflows under\n`fp16` the activations must remain way below `1e4`, because `1e4 * 1e4 = 1e8` so any matrix multiplication with\nlarge activations is going to lead to a numerical overflow condition.\n\nAt the very start of the trace you can discover at which batch number the problem occurred (here `Detected inf/nan during batch_number=0` means the problem occurred on the first batch).\n\nEach reported frame starts by declaring the fully qualified entry for the corresponding module this frame is reporting\nfor. If we look just at this frame:\n\n```\n                  encoder.block.2.layer.1.layer_norm T5LayerNorm\n8.69e-02 4.18e-01 weight\n2.65e-04 3.42e+03 input[0]\n1.79e-06 4.65e+00 output\n```\n\nHere, `encoder.block.2.layer.1.layer_norm` indicates that it was a layer norm for the first layer, of the second\nblock of the encoder. And the specific calls of the `forward` is `T5LayerNorm`.\n\nLet's look at the last few frames of that report:\n\n```\nDetected inf/nan during batch_number=0\nLast 21 forward frames:\nabs min  abs max  metadata\n[...]\n                  encoder.block.2.layer.1.DenseReluDense.wi_0 Linear\n2.17e-07 4.50e+00 weight\n1.79e-06 4.65e+00 input[0]\n2.68e-06 3.70e+01 output\n                  encoder.block.2.layer.1.DenseReluDense.wi_1 Linear\n8.08e-07 2.66e+01 weight\n1.79e-06 4.65e+00 input[0]\n1.27e-04 2.37e+02 output\n                  encoder.block.2.layer.1.DenseReluDense.wo Linear\n1.01e-06 6.44e+00 weight\n0.00e+00 9.74e+03 input[0]\n3.18e-04 6.27e+04 output\n                  encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense\n1.79e-06 4.65e+00 input[0]\n3.18e-04 6.27e+04 output\n                  encoder.block.2.layer.1.dropout Dropout\n3.18e-04 6.27e+04 input[0]\n0.00e+00      inf output\n```\n\nThe last frame reports for `Dropout.forward` function with the first entry for the only input and the second for the\nonly output. You can see that it was called from an attribute `dropout` inside `DenseReluDense` class. We can see\nthat it happened during the first layer, of the 2nd block, during the very first batch. Finally, the absolute largest\ninput elements was `6.27e+04` and same for the output was `inf`."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 692ebacd-b849-40ee-bc28-09967fc33c97
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"692ebacd-b849-40ee-bc28-09967fc33c97\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"4696622d-0fbc-4438-b7b9-4d41582f3855\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"547ee66977115761f6778ec77a0f4395de63815dbe390968fa02dc78b9a4a944\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"4e07793d-4900-485e-8407-8d798c061ddf\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f4acb9cf56d53fd50146da44cac65c22a97bf878ec53d4afaa490c329e9efe6e\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"eca34eda-3e9e-408a-89bf-d2d3ed5f453e\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"2f2e14cd8e43031c6afd03293286b1960d0b617145d293f7e238aee961e1a13d\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 12582, \"end_char_idx\": 15743, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "doc_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "ref_doc_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "chroma:document": "You can see that it was called from an attribute `dropout` inside `DenseReluDense` class. We can see\nthat it happened during the first layer, of the 2nd block, during the very first batch. Finally, the absolute largest\ninput elements was `6.27e+04` and same for the output was `inf`.\n\nYou can see here, that `T5DenseGatedGeluDense.forward` resulted in output activations, whose absolute max value was\naround 62.7K, which is very close to fp16's top limit of 64K. In the next frame we have `Dropout` which renormalizes\nthe weights, after it zeroed some of the elements, which pushes the absolute max value to more than 64K, and we get an\noverflow (`inf`).\n\nAs you can see it's the previous frames that we need to look into when the numbers start going into very large for fp16\nnumbers.\n\nLet's match the report to the code from `models/t5/modeling_t5.py`:\n\n```python\nclass T5DenseGatedGeluDense(nn.Module):\n    def __init__(self, config):\n        super().__init__()\n        self.wi_0 = nn.Linear(config.d_model, config.d_ff, bias=False)\n        self.wi_1 = nn.Linear(config.d_model, config.d_ff, bias=False)\n        self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)\n        self.dropout = nn.Dropout(config.dropout_rate)\n        self.gelu_act = ACT2FN[\"gelu_new\"]\n\n    def forward(self, hidden_states):\n        hidden_gelu = self.gelu_act(self.wi_0(hidden_states))\n        hidden_linear = self.wi_1(hidden_states)\n        hidden_states = hidden_gelu * hidden_linear\n        hidden_states = self.dropout(hidden_states)\n        hidden_states = self.wo(hidden_states)\n        return hidden_states\n```\n\nNow it's easy to see the `dropout` call, and all the previous calls as well.\n\nSince the detection is happening in a forward hook, these reports are printed immediately after each `forward`\nreturns.\n\nGoing back to the full report, to act on it and to fix the problem, we need to go a few frames up where the numbers\nstarted to go up and most likely switch to the `fp32` mode here, so that the numbers don't overflow when multiplied\nor summed up. Of course, there might be other solutions. For example, we could turn off `amp` temporarily if it's\nenabled, after moving the original `forward` into a helper wrapper, like so:\n\n```python\ndef _forward(self, hidden_states):\n    hidden_gelu = self.gelu_act(self.wi_0(hidden_states))\n    hidden_linear = self.wi_1(hidden_states)\n    hidden_states = hidden_gelu * hidden_linear\n    hidden_states = self.dropout(hidden_states)\n    hidden_states = self.wo(hidden_states)\n    return hidden_states\n\n\nimport torch\n\n\ndef forward(self, hidden_states):\n    if torch.is_autocast_enabled():\n        with torch.cuda.amp.autocast(enabled=False):\n            return self._forward(hidden_states)\n    else:\n        return self._forward(hidden_states)\n```\n\nSince the automatic detector only reports on inputs and outputs of full frames, once you know where to look, you may\nwant to analyse the intermediary stages of any specific `forward` function as well. In such a case you can use the\n`detect_overflow` helper function to inject the detector where you want it, for example:\n\n```python\nfrom debug_utils import detect_overflow"}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: eca34eda-3e9e-408a-89bf-d2d3ed5f453e
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"eca34eda-3e9e-408a-89bf-d2d3ed5f453e\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"4696622d-0fbc-4438-b7b9-4d41582f3855\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"547ee66977115761f6778ec77a0f4395de63815dbe390968fa02dc78b9a4a944\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"692ebacd-b849-40ee-bc28-09967fc33c97\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"1d74b58852baa6f2c03ffdf0315e92b06c54f64d0aa3d5d52ce2bd76a9040ca0\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"aa1dda1e-aa36-4787-b810-8cecbccaa40a\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"22e9aef06fa3af10f84e5e9b19dfdb4165cbfd8a0a16ea156b8dce3c357c6e5e\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 14268, \"end_char_idx\": 17480, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "doc_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "ref_doc_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "chroma:document": "Since the detection is happening in a forward hook, these reports are printed immediately after each `forward`\nreturns.\n\nGoing back to the full report, to act on it and to fix the problem, we need to go a few frames up where the numbers\nstarted to go up and most likely switch to the `fp32` mode here, so that the numbers don't overflow when multiplied\nor summed up. Of course, there might be other solutions. For example, we could turn off `amp` temporarily if it's\nenabled, after moving the original `forward` into a helper wrapper, like so:\n\n```python\ndef _forward(self, hidden_states):\n    hidden_gelu = self.gelu_act(self.wi_0(hidden_states))\n    hidden_linear = self.wi_1(hidden_states)\n    hidden_states = hidden_gelu * hidden_linear\n    hidden_states = self.dropout(hidden_states)\n    hidden_states = self.wo(hidden_states)\n    return hidden_states\n\n\nimport torch\n\n\ndef forward(self, hidden_states):\n    if torch.is_autocast_enabled():\n        with torch.cuda.amp.autocast(enabled=False):\n            return self._forward(hidden_states)\n    else:\n        return self._forward(hidden_states)\n```\n\nSince the automatic detector only reports on inputs and outputs of full frames, once you know where to look, you may\nwant to analyse the intermediary stages of any specific `forward` function as well. In such a case you can use the\n`detect_overflow` helper function to inject the detector where you want it, for example:\n\n```python\nfrom debug_utils import detect_overflow\n\n\nclass T5LayerFF(nn.Module):\n    [...]\n\n    def forward(self, hidden_states):\n        forwarded_states = self.layer_norm(hidden_states)\n        detect_overflow(forwarded_states, \"after layer_norm\")\n        forwarded_states = self.DenseReluDense(forwarded_states)\n        detect_overflow(forwarded_states, \"after DenseReluDense\")\n        return hidden_states + self.dropout(forwarded_states)\n```\n\nYou can see that we added 2 of these and now we track if `inf` or `nan` for `forwarded_states` was detected\nsomewhere in between.\n\nActually, the detector already reports these because each of the calls in the example above is a `nn.Module`, but\nlet's say if you had some local direct calculations this is how you'd do that.\n\nAdditionally, if you're instantiating the debugger in your own code, you can adjust the number of frames printed from\nits default, e.g.:\n\n```python\nfrom transformers.debug_utils import DebugUnderflowOverflow\n\ndebug_overflow = DebugUnderflowOverflow(model, max_frames_to_save=100)\n```\n\n### Specific batch absolute min and max value tracing\n\nThe same debugging class can be used for per-batch tracing with the underflow/overflow detection feature turned off.\n\nLet's say you want to watch the absolute min and max values for all the ingredients of each `forward` call of a given\nbatch, and only do that for batches 1 and 3. Then you instantiate this class as:\n\n```python\ndebug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3])\n```\n\nAnd now full batches 1 and 3 will be traced using the same format as the underflow/overflow detector does.\n\nBatches are 0-indexed.\n\nThis is helpful if you know that the program starts misbehaving after a certain batch number, so you can fast-forward\nright to that area."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: aa1dda1e-aa36-4787-b810-8cecbccaa40a
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"aa1dda1e-aa36-4787-b810-8cecbccaa40a\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"4696622d-0fbc-4438-b7b9-4d41582f3855\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"547ee66977115761f6778ec77a0f4395de63815dbe390968fa02dc78b9a4a944\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"eca34eda-3e9e-408a-89bf-d2d3ed5f453e\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"42be12e575702d8edaf2d5e5380658935b71b208c4384a279974d5ef335e969d\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"24887184-5c73-46e8-8b1d-fd3ed1bd361a\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"2f48625c654a5991b3ced2a4abe32384204c45601fad667a829f56a555f6c2f5\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 15746, \"end_char_idx\": 18653, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "doc_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "ref_doc_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "chroma:document": "class T5LayerFF(nn.Module):\n    [...]\n\n    def forward(self, hidden_states):\n        forwarded_states = self.layer_norm(hidden_states)\n        detect_overflow(forwarded_states, \"after layer_norm\")\n        forwarded_states = self.DenseReluDense(forwarded_states)\n        detect_overflow(forwarded_states, \"after DenseReluDense\")\n        return hidden_states + self.dropout(forwarded_states)\n```\n\nYou can see that we added 2 of these and now we track if `inf` or `nan` for `forwarded_states` was detected\nsomewhere in between.\n\nActually, the detector already reports these because each of the calls in the example above is a `nn.Module`, but\nlet's say if you had some local direct calculations this is how you'd do that.\n\nAdditionally, if you're instantiating the debugger in your own code, you can adjust the number of frames printed from\nits default, e.g.:\n\n```python\nfrom transformers.debug_utils import DebugUnderflowOverflow\n\ndebug_overflow = DebugUnderflowOverflow(model, max_frames_to_save=100)\n```\n\n### Specific batch absolute min and max value tracing\n\nThe same debugging class can be used for per-batch tracing with the underflow/overflow detection feature turned off.\n\nLet's say you want to watch the absolute min and max values for all the ingredients of each `forward` call of a given\nbatch, and only do that for batches 1 and 3. Then you instantiate this class as:\n\n```python\ndebug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3])\n```\n\nAnd now full batches 1 and 3 will be traced using the same format as the underflow/overflow detector does.\n\nBatches are 0-indexed.\n\nThis is helpful if you know that the program starts misbehaving after a certain batch number, so you can fast-forward\nright to that area. Here is a sample truncated output for such configuration:\n\n```\n                  *** Starting batch number=1 ***\nabs min  abs max  metadata\n                  shared Embedding\n1.01e-06 7.92e+02 weight\n0.00e+00 2.47e+04 input[0]\n5.36e-05 7.92e+02 output\n[...]\n                  decoder.dropout Dropout\n1.60e-07 2.27e+01 input[0]\n0.00e+00 2.52e+01 output\n                  decoder T5Stack\n     not a tensor output\n                  lm_head Linear\n1.01e-06 7.92e+02 weight\n0.00e+00 1.11e+00 input[0]\n6.06e-02 8.39e+01 output\n                   T5ForConditionalGeneration\n     not a tensor output\n\n                  *** Starting batch number=3 ***\nabs min  abs max  metadata\n                  shared Embedding\n1.01e-06 7.92e+02 weight\n0.00e+00 2.78e+04 input[0]\n5.36e-05 7.92e+02 output\n[...]\n```\n\nHere you will get a huge number of frames dumped - as many as there were forward calls in your model, so it may or may\nnot what you want, but sometimes it can be easier to use for debugging purposes than a normal debugger. For example, if\na problem starts happening at batch number 150. So you can dump traces for batches 149 and 150 and compare where\nnumbers started to diverge."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 24887184-5c73-46e8-8b1d-fd3ed1bd361a
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"24887184-5c73-46e8-8b1d-fd3ed1bd361a\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"4696622d-0fbc-4438-b7b9-4d41582f3855\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"547ee66977115761f6778ec77a0f4395de63815dbe390968fa02dc78b9a4a944\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"aa1dda1e-aa36-4787-b810-8cecbccaa40a\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/debugging\", \"title\": \"Debugging\", \"tokens\": 5079, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f525c0e0e088c2ddbbfe6b70d4c18b512c74ed37f2e5be1ce05fe5be9d69e04b\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 17319, \"end_char_idx\": 18844, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "doc_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "ref_doc_id": "4696622d-0fbc-4438-b7b9-4d41582f3855", "chroma:document": "Batches are 0-indexed.\n\nThis is helpful if you know that the program starts misbehaving after a certain batch number, so you can fast-forward\nright to that area. Here is a sample truncated output for such configuration:\n\n```\n                  *** Starting batch number=1 ***\nabs min  abs max  metadata\n                  shared Embedding\n1.01e-06 7.92e+02 weight\n0.00e+00 2.47e+04 input[0]\n5.36e-05 7.92e+02 output\n[...]\n                  decoder.dropout Dropout\n1.60e-07 2.27e+01 input[0]\n0.00e+00 2.52e+01 output\n                  decoder T5Stack\n     not a tensor output\n                  lm_head Linear\n1.01e-06 7.92e+02 weight\n0.00e+00 1.11e+00 input[0]\n6.06e-02 8.39e+01 output\n                   T5ForConditionalGeneration\n     not a tensor output\n\n                  *** Starting batch number=3 ***\nabs min  abs max  metadata\n                  shared Embedding\n1.01e-06 7.92e+02 weight\n0.00e+00 2.78e+04 input[0]\n5.36e-05 7.92e+02 output\n[...]\n```\n\nHere you will get a huge number of frames dumped - as many as there were forward calls in your model, so it may or may\nnot what you want, but sometimes it can be easier to use for debugging purposes than a normal debugger. For example, if\na problem starts happening at batch number 150. So you can dump traces for batches 149 and 150 and compare where\nnumbers started to diverge.\n\nYou can also specify the batch number after which to stop the training, with:\n\n```python\ndebug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3], abort_after_batch_num=3)\n```"}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 31c03822-b16c-4585-a335-23c4862d33c7
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/create_a_model", "title": "Create a custom architecture", "tokens": 4699, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"31c03822-b16c-4585-a335-23c4862d33c7\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"b88d0498-9a36-4283-bdc9-3eaf0b29cc02\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8ba46afe581db3eec89c4dc44fce458850ae1d6e4a1482c90791c118a7846287\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"d6641f60-dfa1-4f4c-9439-7d4bad07e698\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"55da9ed7b6c4c530cd7dc6f6ee7194d2350b0b6d00419bd06423fc197fcdbddc\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 0, \"end_char_idx\": 2285, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "ref_doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "chroma:document": "# Create a custom architecture\n\nAn [`AutoClass`](model_doc/auto) automatically infers the model architecture and downloads pretrained configuration and weights. Generally, we recommend using an `AutoClass` to produce checkpoint-agnostic code. But users who want more control over specific model parameters can create a custom \ud83e\udd17 Transformers model from just a few base classes. This could be particularly useful for anyone who is interested in studying, training or experimenting with a \ud83e\udd17 Transformers model. In this guide, dive deeper into creating a custom model without an `AutoClass`. Learn how to:\n\n- Load and customize a model configuration.\n- Create a model architecture.\n- Create a slow and fast tokenizer for text.\n- Create an image processor for vision tasks.\n- Create a feature extractor for audio tasks.\n- Create a processor for multimodal tasks.\n\n## Configuration\n\nA [configuration](main_classes/configuration) refers to a model's specific attributes. Each model configuration has different attributes; for instance, all NLP models have the `hidden_size`, `num_attention_heads`, `num_hidden_layers` and `vocab_size` attributes in common. These attributes specify the number of attention heads or hidden layers to construct a model with.\n\nGet a closer look at [DistilBERT](model_doc/distilbert) by accessing [`DistilBertConfig`] to inspect it's attributes:\n\n```py\n>>> from transformers import DistilBertConfig\n\n>>> config = DistilBertConfig()\n>>> print(config)\nDistilBertConfig {\n  \"activation\": \"gelu\",\n  \"attention_dropout\": 0.1,\n  \"dim\": 768,\n  \"dropout\": 0.1,\n  \"hidden_dim\": 3072,\n  \"initializer_range\": 0.02,\n  \"max_position_embeddings\": 512,\n  \"model_type\": \"distilbert\",\n  \"n_heads\": 12,\n  \"n_layers\": 6,\n  \"pad_token_id\": 0,\n  \"qa_dropout\": 0.1,\n  \"seq_classif_dropout\": 0.2,\n  \"sinusoidal_pos_embds\": false,\n  \"transformers_version\": \"4.16.2\",\n  \"vocab_size\": 30522\n}\n```\n\n[`DistilBertConfig`] displays all the default attributes used to build a base [`DistilBertModel`]. All attributes are customizable, creating space for experimentation. For example, you can customize a default model to:\n\n- Try a different activation function with the `activation` parameter.\n- Use a higher dropout ratio for the attention probabilities with the `attention_dropout` parameter."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: d6641f60-dfa1-4f4c-9439-7d4bad07e698
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/create_a_model", "title": "Create a custom architecture", "tokens": 4699, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"d6641f60-dfa1-4f4c-9439-7d4bad07e698\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"b88d0498-9a36-4283-bdc9-3eaf0b29cc02\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8ba46afe581db3eec89c4dc44fce458850ae1d6e4a1482c90791c118a7846287\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"31c03822-b16c-4585-a335-23c4862d33c7\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"2d53c9c9228d58d35d3e11cb756241329e8f205ac060cdbf5fc0bde50632bbd8\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"e7522d81-4fd0-4f5d-84da-64330043809e\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"65a6652ee58185cb887dbe54220094d198f815b7a5908b56f44800dac1340e38\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 769, \"end_char_idx\": 3693, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "ref_doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "chroma:document": "- Create a feature extractor for audio tasks.\n- Create a processor for multimodal tasks.\n\n## Configuration\n\nA [configuration](main_classes/configuration) refers to a model's specific attributes. Each model configuration has different attributes; for instance, all NLP models have the `hidden_size`, `num_attention_heads`, `num_hidden_layers` and `vocab_size` attributes in common. These attributes specify the number of attention heads or hidden layers to construct a model with.\n\nGet a closer look at [DistilBERT](model_doc/distilbert) by accessing [`DistilBertConfig`] to inspect it's attributes:\n\n```py\n>>> from transformers import DistilBertConfig\n\n>>> config = DistilBertConfig()\n>>> print(config)\nDistilBertConfig {\n  \"activation\": \"gelu\",\n  \"attention_dropout\": 0.1,\n  \"dim\": 768,\n  \"dropout\": 0.1,\n  \"hidden_dim\": 3072,\n  \"initializer_range\": 0.02,\n  \"max_position_embeddings\": 512,\n  \"model_type\": \"distilbert\",\n  \"n_heads\": 12,\n  \"n_layers\": 6,\n  \"pad_token_id\": 0,\n  \"qa_dropout\": 0.1,\n  \"seq_classif_dropout\": 0.2,\n  \"sinusoidal_pos_embds\": false,\n  \"transformers_version\": \"4.16.2\",\n  \"vocab_size\": 30522\n}\n```\n\n[`DistilBertConfig`] displays all the default attributes used to build a base [`DistilBertModel`]. All attributes are customizable, creating space for experimentation. For example, you can customize a default model to:\n\n- Try a different activation function with the `activation` parameter.\n- Use a higher dropout ratio for the attention probabilities with the `attention_dropout` parameter.\n\n```py\n>>> my_config = DistilBertConfig(activation=\"relu\", attention_dropout=0.4)\n>>> print(my_config)\nDistilBertConfig {\n  \"activation\": \"relu\",\n  \"attention_dropout\": 0.4,\n  \"dim\": 768,\n  \"dropout\": 0.1,\n  \"hidden_dim\": 3072,\n  \"initializer_range\": 0.02,\n  \"max_position_embeddings\": 512,\n  \"model_type\": \"distilbert\",\n  \"n_heads\": 12,\n  \"n_layers\": 6,\n  \"pad_token_id\": 0,\n  \"qa_dropout\": 0.1,\n  \"seq_classif_dropout\": 0.2,\n  \"sinusoidal_pos_embds\": false,\n  \"transformers_version\": \"4.16.2\",\n  \"vocab_size\": 30522\n}\n```\n\nPretrained model attributes can be modified in the [`~PretrainedConfig.from_pretrained`] function:\n\n```py\n>>> my_config = DistilBertConfig.from_pretrained(\"distilbert/distilbert-base-uncased\", activation=\"relu\", attention_dropout=0.4)\n```\n\nOnce you are satisfied with your model configuration, you can save it with [`~PretrainedConfig.save_pretrained`]. Your configuration file is stored as a JSON file in the specified save directory:\n\n```py\n>>> my_config.save_pretrained(save_directory=\"./your_model_save_path\")\n```\n\nTo reuse the configuration file, load it with [`~PretrainedConfig.from_pretrained`]:\n\n```py\n>>> my_config = DistilBertConfig.from_pretrained(\"./your_model_save_path/config.json\")\n```\n\n<Tip>\n\nYou can also save your configuration file as a dictionary or even just the difference between your custom configuration attributes and the default configuration attributes!"}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: e7522d81-4fd0-4f5d-84da-64330043809e
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/create_a_model", "title": "Create a custom architecture", "tokens": 4699, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"e7522d81-4fd0-4f5d-84da-64330043809e\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"b88d0498-9a36-4283-bdc9-3eaf0b29cc02\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8ba46afe581db3eec89c4dc44fce458850ae1d6e4a1482c90791c118a7846287\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"d6641f60-dfa1-4f4c-9439-7d4bad07e698\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"30aa4d18f6c54944f006e65568b15bdcdd1786cbf4c081423c11e780afcb1e9d\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"2b83cd8a-a527-4bea-b9a0-52d44d480506\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"9c38af66dfc1c87f16960c9505dcc96df55315b6add0afdbb93600e3c8c778fa\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 2185, \"end_char_idx\": 5237, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "ref_doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "chroma:document": "- Use a higher dropout ratio for the attention probabilities with the `attention_dropout` parameter.\n\n```py\n>>> my_config = DistilBertConfig(activation=\"relu\", attention_dropout=0.4)\n>>> print(my_config)\nDistilBertConfig {\n  \"activation\": \"relu\",\n  \"attention_dropout\": 0.4,\n  \"dim\": 768,\n  \"dropout\": 0.1,\n  \"hidden_dim\": 3072,\n  \"initializer_range\": 0.02,\n  \"max_position_embeddings\": 512,\n  \"model_type\": \"distilbert\",\n  \"n_heads\": 12,\n  \"n_layers\": 6,\n  \"pad_token_id\": 0,\n  \"qa_dropout\": 0.1,\n  \"seq_classif_dropout\": 0.2,\n  \"sinusoidal_pos_embds\": false,\n  \"transformers_version\": \"4.16.2\",\n  \"vocab_size\": 30522\n}\n```\n\nPretrained model attributes can be modified in the [`~PretrainedConfig.from_pretrained`] function:\n\n```py\n>>> my_config = DistilBertConfig.from_pretrained(\"distilbert/distilbert-base-uncased\", activation=\"relu\", attention_dropout=0.4)\n```\n\nOnce you are satisfied with your model configuration, you can save it with [`~PretrainedConfig.save_pretrained`]. Your configuration file is stored as a JSON file in the specified save directory:\n\n```py\n>>> my_config.save_pretrained(save_directory=\"./your_model_save_path\")\n```\n\nTo reuse the configuration file, load it with [`~PretrainedConfig.from_pretrained`]:\n\n```py\n>>> my_config = DistilBertConfig.from_pretrained(\"./your_model_save_path/config.json\")\n```\n\n<Tip>\n\nYou can also save your configuration file as a dictionary or even just the difference between your custom configuration attributes and the default configuration attributes! See the [configuration](main_classes/configuration) documentation for more details.\n\n</Tip>\n\n## Model\n\nThe next step is to create a [model](main_classes/models). The model - also loosely referred to as the architecture - defines what each layer is doing and what operations are happening. Attributes like `num_hidden_layers` from the configuration are used to define the architecture. Every model shares the base class [`PreTrainedModel`] and a few common methods like resizing input embeddings and pruning self-attention heads. In addition, all models are also either a [`torch.nn.Module`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html), [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model) or [`flax.linen.Module`](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html) subclass. This means models are compatible with each of their respective framework's usage.\n\n<frameworkcontent>\n<pt>\nLoad your custom configuration attributes into the model:\n\n```py\n>>> from transformers import DistilBertModel\n\n>>> my_config = DistilBertConfig.from_pretrained(\"./your_model_save_path/config.json\")\n>>> model = DistilBertModel(my_config)\n```\n\nThis creates a model with random values instead of pretrained weights. You won't be able to use this model for anything useful yet until you train it. Training is a costly and time-consuming process. It is generally better to use a pretrained model to obtain better results faster, while using only a fraction of the resources required for training."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 2b83cd8a-a527-4bea-b9a0-52d44d480506
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/create_a_model", "title": "Create a custom architecture", "tokens": 4699, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"2b83cd8a-a527-4bea-b9a0-52d44d480506\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"b88d0498-9a36-4283-bdc9-3eaf0b29cc02\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8ba46afe581db3eec89c4dc44fce458850ae1d6e4a1482c90791c118a7846287\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"e7522d81-4fd0-4f5d-84da-64330043809e\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"b830837d89a7bb447ae983ea0bd2c6dcd8449bae82f0d816a9a5e9d7ee84671d\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"030d0b9b-4cef-4d51-b268-50f1177e9240\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"a3462cecb106da4d9bfa1683f5c57d35282982009306f5e6cc00e7ffb2763289\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 3694, \"end_char_idx\": 7135, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "ref_doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "chroma:document": "See the [configuration](main_classes/configuration) documentation for more details.\n\n</Tip>\n\n## Model\n\nThe next step is to create a [model](main_classes/models). The model - also loosely referred to as the architecture - defines what each layer is doing and what operations are happening. Attributes like `num_hidden_layers` from the configuration are used to define the architecture. Every model shares the base class [`PreTrainedModel`] and a few common methods like resizing input embeddings and pruning self-attention heads. In addition, all models are also either a [`torch.nn.Module`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html), [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model) or [`flax.linen.Module`](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html) subclass. This means models are compatible with each of their respective framework's usage.\n\n<frameworkcontent>\n<pt>\nLoad your custom configuration attributes into the model:\n\n```py\n>>> from transformers import DistilBertModel\n\n>>> my_config = DistilBertConfig.from_pretrained(\"./your_model_save_path/config.json\")\n>>> model = DistilBertModel(my_config)\n```\n\nThis creates a model with random values instead of pretrained weights. You won't be able to use this model for anything useful yet until you train it. Training is a costly and time-consuming process. It is generally better to use a pretrained model to obtain better results faster, while using only a fraction of the resources required for training.\n\nCreate a pretrained model with [`~PreTrainedModel.from_pretrained`]:\n\n```py\n>>> model = DistilBertModel.from_pretrained(\"distilbert/distilbert-base-uncased\")\n```\n\nWhen you load pretrained weights, the default model configuration is automatically loaded if the model is provided by \ud83e\udd17 Transformers. However, you can still replace - some or all of - the default model configuration attributes with your own if you'd like:\n\n```py\n>>> model = DistilBertModel.from_pretrained(\"distilbert/distilbert-base-uncased\", config=my_config)\n```\n</pt>\n<tf>\nLoad your custom configuration attributes into the model:\n\n```py\n>>> from transformers import TFDistilBertModel\n\n>>> my_config = DistilBertConfig.from_pretrained(\"./your_model_save_path/my_config.json\")\n>>> tf_model = TFDistilBertModel(my_config)\n```\n\nThis creates a model with random values instead of pretrained weights. You won't be able to use this model for anything useful yet until you train it. Training is a costly and time-consuming process. It is generally better to use a pretrained model to obtain better results faster, while using only a fraction of the resources required for training.\n\nCreate a pretrained model with [`~TFPreTrainedModel.from_pretrained`]:\n\n```py\n>>> tf_model = TFDistilBertModel.from_pretrained(\"distilbert/distilbert-base-uncased\")\n```\n\nWhen you load pretrained weights, the default model configuration is automatically loaded if the model is provided by \ud83e\udd17 Transformers. However, you can still replace - some or all of - the default model configuration attributes with your own if you'd like:\n\n```py\n>>> tf_model = TFDistilBertModel.from_pretrained(\"distilbert/distilbert-base-uncased\", config=my_config)\n```\n</tf>\n</frameworkcontent>\n\n### Model heads\n\nAt this point, you have a base DistilBERT model which outputs the *hidden states*. The hidden states are passed as inputs to a model head to produce the final output."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 030d0b9b-4cef-4d51-b268-50f1177e9240
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/create_a_model", "title": "Create a custom architecture", "tokens": 4699, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"030d0b9b-4cef-4d51-b268-50f1177e9240\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"b88d0498-9a36-4283-bdc9-3eaf0b29cc02\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8ba46afe581db3eec89c4dc44fce458850ae1d6e4a1482c90791c118a7846287\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"2b83cd8a-a527-4bea-b9a0-52d44d480506\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"3caabefb0490c3cb81e628b8028965bf2f283f3a66b098b079024619c6c4debf\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"28adb58f-5773-4ae7-afd2-663e30cddbe7\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"51e542240f3b7a26af8efd5d7567d61fd9b441bfdf9bed810352ed3448a0f288\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 5536, \"end_char_idx\": 8930, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "ref_doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "chroma:document": "However, you can still replace - some or all of - the default model configuration attributes with your own if you'd like:\n\n```py\n>>> model = DistilBertModel.from_pretrained(\"distilbert/distilbert-base-uncased\", config=my_config)\n```\n</pt>\n<tf>\nLoad your custom configuration attributes into the model:\n\n```py\n>>> from transformers import TFDistilBertModel\n\n>>> my_config = DistilBertConfig.from_pretrained(\"./your_model_save_path/my_config.json\")\n>>> tf_model = TFDistilBertModel(my_config)\n```\n\nThis creates a model with random values instead of pretrained weights. You won't be able to use this model for anything useful yet until you train it. Training is a costly and time-consuming process. It is generally better to use a pretrained model to obtain better results faster, while using only a fraction of the resources required for training.\n\nCreate a pretrained model with [`~TFPreTrainedModel.from_pretrained`]:\n\n```py\n>>> tf_model = TFDistilBertModel.from_pretrained(\"distilbert/distilbert-base-uncased\")\n```\n\nWhen you load pretrained weights, the default model configuration is automatically loaded if the model is provided by \ud83e\udd17 Transformers. However, you can still replace - some or all of - the default model configuration attributes with your own if you'd like:\n\n```py\n>>> tf_model = TFDistilBertModel.from_pretrained(\"distilbert/distilbert-base-uncased\", config=my_config)\n```\n</tf>\n</frameworkcontent>\n\n### Model heads\n\nAt this point, you have a base DistilBERT model which outputs the *hidden states*. The hidden states are passed as inputs to a model head to produce the final output. \ud83e\udd17 Transformers provides a different model head for each task as long as a model supports the task (i.e., you can't use DistilBERT for a sequence-to-sequence task like translation).\n\n<frameworkcontent>\n<pt>\nFor example, [`DistilBertForSequenceClassification`] is a base DistilBERT model with a sequence classification head. The sequence classification head is a linear layer on top of the pooled outputs.\n\n```py\n>>> from transformers import DistilBertForSequenceClassification\n\n>>> model = DistilBertForSequenceClassification.from_pretrained(\"distilbert/distilbert-base-uncased\")\n```\n\nEasily reuse this checkpoint for another task by switching to a different model head. For a question answering task, you would use the [`DistilBertForQuestionAnswering`] model head. The question answering head is similar to the sequence classification head except it is a linear layer on top of the hidden states output.\n\n```py\n>>> from transformers import DistilBertForQuestionAnswering\n\n>>> model = DistilBertForQuestionAnswering.from_pretrained(\"distilbert/distilbert-base-uncased\")\n```\n</pt>\n<tf>\nFor example, [`TFDistilBertForSequenceClassification`] is a base DistilBERT model with a sequence classification head. The sequence classification head is a linear layer on top of the pooled outputs.\n\n```py\n>>> from transformers import TFDistilBertForSequenceClassification\n\n>>> tf_model = TFDistilBertForSequenceClassification.from_pretrained(\"distilbert/distilbert-base-uncased\")\n```\n\nEasily reuse this checkpoint for another task by switching to a different model head. For a question answering task, you would use the [`TFDistilBertForQuestionAnswering`] model head. The question answering head is similar to the sequence classification head except it is a linear layer on top of the hidden states output."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 28adb58f-5773-4ae7-afd2-663e30cddbe7
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/create_a_model", "title": "Create a custom architecture", "tokens": 4699, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"28adb58f-5773-4ae7-afd2-663e30cddbe7\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"b88d0498-9a36-4283-bdc9-3eaf0b29cc02\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8ba46afe581db3eec89c4dc44fce458850ae1d6e4a1482c90791c118a7846287\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"030d0b9b-4cef-4d51-b268-50f1177e9240\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"b5646942feb2cdbfd989b3464da2ae561cfffd6195dbb2cc816e86762e4145fc\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"dc458159-a8ab-419a-a766-c35e0bfbabf9\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"b8c4e69f0cea427df77fb8f616ef9eb3b49e0d8d0834dca5ed2167c5a4668ee6\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 7318, \"end_char_idx\": 10639, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "ref_doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "chroma:document": "<frameworkcontent>\n<pt>\nFor example, [`DistilBertForSequenceClassification`] is a base DistilBERT model with a sequence classification head. The sequence classification head is a linear layer on top of the pooled outputs.\n\n```py\n>>> from transformers import DistilBertForSequenceClassification\n\n>>> model = DistilBertForSequenceClassification.from_pretrained(\"distilbert/distilbert-base-uncased\")\n```\n\nEasily reuse this checkpoint for another task by switching to a different model head. For a question answering task, you would use the [`DistilBertForQuestionAnswering`] model head. The question answering head is similar to the sequence classification head except it is a linear layer on top of the hidden states output.\n\n```py\n>>> from transformers import DistilBertForQuestionAnswering\n\n>>> model = DistilBertForQuestionAnswering.from_pretrained(\"distilbert/distilbert-base-uncased\")\n```\n</pt>\n<tf>\nFor example, [`TFDistilBertForSequenceClassification`] is a base DistilBERT model with a sequence classification head. The sequence classification head is a linear layer on top of the pooled outputs.\n\n```py\n>>> from transformers import TFDistilBertForSequenceClassification\n\n>>> tf_model = TFDistilBertForSequenceClassification.from_pretrained(\"distilbert/distilbert-base-uncased\")\n```\n\nEasily reuse this checkpoint for another task by switching to a different model head. For a question answering task, you would use the [`TFDistilBertForQuestionAnswering`] model head. The question answering head is similar to the sequence classification head except it is a linear layer on top of the hidden states output.\n\n```py\n>>> from transformers import TFDistilBertForQuestionAnswering\n\n>>> tf_model = TFDistilBertForQuestionAnswering.from_pretrained(\"distilbert/distilbert-base-uncased\")\n```\n</tf>\n</frameworkcontent>\n\n## Tokenizer\n\nThe last base class you need before using a model for textual data is a [tokenizer](main_classes/tokenizer) to convert raw text to tensors. There are two types of tokenizers you can use with \ud83e\udd17 Transformers:\n\n- [`PreTrainedTokenizer`]: a Python implementation of a tokenizer.\n- [`PreTrainedTokenizerFast`]: a tokenizer from our Rust-based [\ud83e\udd17 Tokenizer](https://huggingface.co/docs/tokenizers/python/latest/) library. This tokenizer type is significantly faster - especially during batch tokenization - due to its Rust implementation. The fast tokenizer also offers additional methods like *offset mapping* which maps tokens to their original words or characters.\n\nBoth tokenizers support common methods such as encoding and decoding, adding new tokens, and managing special tokens.\n\n<Tip warning={true}>\n\nNot every model supports a fast tokenizer. Take a look at this [table](index#supported-frameworks) to check if a model has fast tokenizer support.\n\n</Tip>\n\nIf you trained your own tokenizer, you can create one from your *vocabulary* file:\n\n```py\n>>> from transformers import DistilBertTokenizer\n\n>>> my_tokenizer = DistilBertTokenizer(vocab_file=\"my_vocab_file.txt\", do_lower_case=False, padding_side=\"left\")\n```\n\nIt is important to remember the vocabulary from a custom tokenizer will be different from the vocabulary generated by a pretrained model's tokenizer. You need to use a pretrained model's vocabulary if you are using a pretrained model, otherwise the inputs won't make sense."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: dc458159-a8ab-419a-a766-c35e0bfbabf9
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/create_a_model", "title": "Create a custom architecture", "tokens": 4699, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"dc458159-a8ab-419a-a766-c35e0bfbabf9\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"b88d0498-9a36-4283-bdc9-3eaf0b29cc02\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8ba46afe581db3eec89c4dc44fce458850ae1d6e4a1482c90791c118a7846287\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"28adb58f-5773-4ae7-afd2-663e30cddbe7\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"128e5084bde51bbc8dbfd725ffff2f868e26ede5c6070ad3405a1d496b90fa47\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"b1a4d5d1-000a-4e0d-82b6-0061a972dc9b\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"386792257a6e23b1b96aa9b61f0d8aa3a29a42ce3292925605633a905181b9c9\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 8932, \"end_char_idx\": 12134, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "ref_doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "chroma:document": "```py\n>>> from transformers import TFDistilBertForQuestionAnswering\n\n>>> tf_model = TFDistilBertForQuestionAnswering.from_pretrained(\"distilbert/distilbert-base-uncased\")\n```\n</tf>\n</frameworkcontent>\n\n## Tokenizer\n\nThe last base class you need before using a model for textual data is a [tokenizer](main_classes/tokenizer) to convert raw text to tensors. There are two types of tokenizers you can use with \ud83e\udd17 Transformers:\n\n- [`PreTrainedTokenizer`]: a Python implementation of a tokenizer.\n- [`PreTrainedTokenizerFast`]: a tokenizer from our Rust-based [\ud83e\udd17 Tokenizer](https://huggingface.co/docs/tokenizers/python/latest/) library. This tokenizer type is significantly faster - especially during batch tokenization - due to its Rust implementation. The fast tokenizer also offers additional methods like *offset mapping* which maps tokens to their original words or characters.\n\nBoth tokenizers support common methods such as encoding and decoding, adding new tokens, and managing special tokens.\n\n<Tip warning={true}>\n\nNot every model supports a fast tokenizer. Take a look at this [table](index#supported-frameworks) to check if a model has fast tokenizer support.\n\n</Tip>\n\nIf you trained your own tokenizer, you can create one from your *vocabulary* file:\n\n```py\n>>> from transformers import DistilBertTokenizer\n\n>>> my_tokenizer = DistilBertTokenizer(vocab_file=\"my_vocab_file.txt\", do_lower_case=False, padding_side=\"left\")\n```\n\nIt is important to remember the vocabulary from a custom tokenizer will be different from the vocabulary generated by a pretrained model's tokenizer. You need to use a pretrained model's vocabulary if you are using a pretrained model, otherwise the inputs won't make sense. Create a tokenizer with a pretrained model's vocabulary with the [`DistilBertTokenizer`] class:\n\n```py\n>>> from transformers import DistilBertTokenizer\n\n>>> slow_tokenizer = DistilBertTokenizer.from_pretrained(\"distilbert/distilbert-base-uncased\")\n```\n\nCreate a fast tokenizer with the [`DistilBertTokenizerFast`] class:\n\n```py\n>>> from transformers import DistilBertTokenizerFast\n\n>>> fast_tokenizer = DistilBertTokenizerFast.from_pretrained(\"distilbert/distilbert-base-uncased\")\n```\n\n<Tip>\n\nBy default, [`AutoTokenizer`] will try to load a fast tokenizer. You can disable this behavior by setting `use_fast=False` in `from_pretrained`.\n\n</Tip>\n\n## Image processor\n\nAn image processor processes vision inputs. It inherits from the base [`~image_processing_utils.ImageProcessingMixin`] class.\n\nTo use, create an image processor associated with the model you're using. For example, create a default [`ViTImageProcessor`] if you are using [ViT](model_doc/vit) for image classification:\n\n```py\n>>> from transformers import ViTImageProcessor\n\n>>> vit_extractor = ViTImageProcessor()\n>>> print(vit_extractor)\nViTImageProcessor {\n  \"do_normalize\": true,\n  \"do_resize\": true,\n  \"image_processor_type\": \"ViTImageProcessor\",\n  \"image_mean\": [\n    0.5,\n    0.5,\n    0.5\n  ],\n  \"image_std\": [\n    0.5,\n    0.5,\n    0.5\n  ],\n  \"resample\": 2,\n  \"size\": 224\n}\n```\n\n<Tip>\n\nIf you aren't looking for any customization, just use the `from_pretrained` method to load a model's default image processor parameters."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: b1a4d5d1-000a-4e0d-82b6-0061a972dc9b
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/create_a_model", "title": "Create a custom architecture", "tokens": 4699, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"b1a4d5d1-000a-4e0d-82b6-0061a972dc9b\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"b88d0498-9a36-4283-bdc9-3eaf0b29cc02\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8ba46afe581db3eec89c4dc44fce458850ae1d6e4a1482c90791c118a7846287\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"dc458159-a8ab-419a-a766-c35e0bfbabf9\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"96d9dfc5ab4f55c7f7ed6fc982e079881fa69f1ad70ab5ef5128f14d41ff8b5d\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"b2e4241f-bd43-4d1e-a40f-7e747229fd02\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"9d4eb4740ad3e484a8e1400034106a3158e0fc738a15de1cc6c4ef78965d2e41\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 10640, \"end_char_idx\": 13600, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "ref_doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "chroma:document": "Create a tokenizer with a pretrained model's vocabulary with the [`DistilBertTokenizer`] class:\n\n```py\n>>> from transformers import DistilBertTokenizer\n\n>>> slow_tokenizer = DistilBertTokenizer.from_pretrained(\"distilbert/distilbert-base-uncased\")\n```\n\nCreate a fast tokenizer with the [`DistilBertTokenizerFast`] class:\n\n```py\n>>> from transformers import DistilBertTokenizerFast\n\n>>> fast_tokenizer = DistilBertTokenizerFast.from_pretrained(\"distilbert/distilbert-base-uncased\")\n```\n\n<Tip>\n\nBy default, [`AutoTokenizer`] will try to load a fast tokenizer. You can disable this behavior by setting `use_fast=False` in `from_pretrained`.\n\n</Tip>\n\n## Image processor\n\nAn image processor processes vision inputs. It inherits from the base [`~image_processing_utils.ImageProcessingMixin`] class.\n\nTo use, create an image processor associated with the model you're using. For example, create a default [`ViTImageProcessor`] if you are using [ViT](model_doc/vit) for image classification:\n\n```py\n>>> from transformers import ViTImageProcessor\n\n>>> vit_extractor = ViTImageProcessor()\n>>> print(vit_extractor)\nViTImageProcessor {\n  \"do_normalize\": true,\n  \"do_resize\": true,\n  \"image_processor_type\": \"ViTImageProcessor\",\n  \"image_mean\": [\n    0.5,\n    0.5,\n    0.5\n  ],\n  \"image_std\": [\n    0.5,\n    0.5,\n    0.5\n  ],\n  \"resample\": 2,\n  \"size\": 224\n}\n```\n\n<Tip>\n\nIf you aren't looking for any customization, just use the `from_pretrained` method to load a model's default image processor parameters.\n\n</Tip>\n\nModify any of the [`ViTImageProcessor`] parameters to create your custom image processor:\n\n```py\n>>> from transformers import ViTImageProcessor\n\n>>> my_vit_extractor = ViTImageProcessor(resample=\"PIL.Image.BOX\", do_normalize=False, image_mean=[0.3, 0.3, 0.3])\n>>> print(my_vit_extractor)\nViTImageProcessor {\n  \"do_normalize\": false,\n  \"do_resize\": true,\n  \"image_processor_type\": \"ViTImageProcessor\",\n  \"image_mean\": [\n    0.3,\n    0.3,\n    0.3\n  ],\n  \"image_std\": [\n    0.5,\n    0.5,\n    0.5\n  ],\n  \"resample\": \"PIL.Image.BOX\",\n  \"size\": 224\n}\n```\n\n## Backbone\n\n<div style=\"text-align: center\">\n  <img src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/Backbone.png\">\n</div>\n\nComputer vision models consist of a backbone, neck, and head. The backbone extracts features from an input image, the neck combines and enhances the extracted features, and the head is used for the main task (e.g., object detection). Start by initializing a backbone in the model config and specify whether you want to load pretrained weights or load randomly initialized weights. Then you can pass the model config to the model head.\n\nFor example, to load a [ResNet](../model_doc/resnet) backbone into a [MaskFormer](../model_doc/maskformer) model with an instance segmentation head:\n\n<hfoptions id=\"backbone\">\n<hfoption id=\"pretrained weights\">\n\nSet `use_pretrained_backbone=True` to load pretrained ResNet weights for the backbone."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: b2e4241f-bd43-4d1e-a40f-7e747229fd02
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/create_a_model", "title": "Create a custom architecture", "tokens": 4699, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"b2e4241f-bd43-4d1e-a40f-7e747229fd02\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"b88d0498-9a36-4283-bdc9-3eaf0b29cc02\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8ba46afe581db3eec89c4dc44fce458850ae1d6e4a1482c90791c118a7846287\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"b1a4d5d1-000a-4e0d-82b6-0061a972dc9b\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8608cc8d1d78d9328aa85859c1a7c6441178d689be7fae981c8e62ec12c52e0c\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"c51c59fd-c707-4dea-b2c2-b180d88c477a\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"2eba7ff5fec9533153c7fe7fec51544cfc938d8a05de662c05779927fbded44b\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 12136, \"end_char_idx\": 15286, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "ref_doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "chroma:document": "</Tip>\n\nModify any of the [`ViTImageProcessor`] parameters to create your custom image processor:\n\n```py\n>>> from transformers import ViTImageProcessor\n\n>>> my_vit_extractor = ViTImageProcessor(resample=\"PIL.Image.BOX\", do_normalize=False, image_mean=[0.3, 0.3, 0.3])\n>>> print(my_vit_extractor)\nViTImageProcessor {\n  \"do_normalize\": false,\n  \"do_resize\": true,\n  \"image_processor_type\": \"ViTImageProcessor\",\n  \"image_mean\": [\n    0.3,\n    0.3,\n    0.3\n  ],\n  \"image_std\": [\n    0.5,\n    0.5,\n    0.5\n  ],\n  \"resample\": \"PIL.Image.BOX\",\n  \"size\": 224\n}\n```\n\n## Backbone\n\n<div style=\"text-align: center\">\n  <img src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/Backbone.png\">\n</div>\n\nComputer vision models consist of a backbone, neck, and head. The backbone extracts features from an input image, the neck combines and enhances the extracted features, and the head is used for the main task (e.g., object detection). Start by initializing a backbone in the model config and specify whether you want to load pretrained weights or load randomly initialized weights. Then you can pass the model config to the model head.\n\nFor example, to load a [ResNet](../model_doc/resnet) backbone into a [MaskFormer](../model_doc/maskformer) model with an instance segmentation head:\n\n<hfoptions id=\"backbone\">\n<hfoption id=\"pretrained weights\">\n\nSet `use_pretrained_backbone=True` to load pretrained ResNet weights for the backbone.\n\n```py\nfrom transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation\n\nconfig = MaskFormerConfig(backbone=\"microsoft/resnet-50\", use_pretrained_backbone=True) # backbone and neck config\nmodel = MaskFormerForInstanceSegmentation(config) # head\n```\n\n</hfoption>\n<hfoption id=\"random weights\">\n\nSet `use_pretrained_backbone=False` to randomly initialize a ResNet backbone.\n\n```py\nfrom transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation\n\nconfig = MaskFormerConfig(backbone=\"microsoft/resnet-50\", use_pretrained_backbone=False) # backbone and neck config\nmodel = MaskFormerForInstanceSegmentation(config) # head\n```\n\nYou could also load the backbone config separately and then pass it to the model config.\n\n```py\nfrom transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, ResNetConfig\n\nbackbone_config = ResNetConfig()\nconfig = MaskFormerConfig(backbone_config=backbone_config)\nmodel = MaskFormerForInstanceSegmentation(config)\n```\n\n</hfoption>\n</hfoptions id=\"timm backbone\">\n\n[timm](https://hf.co/docs/timm/index) models are loaded within a model with `use_timm_backbone=True` or with [`TimmBackbone`] and [`TimmBackboneConfig`].\n\nUse `use_timm_backbone=True` and `use_pretrained_backbone=True` to load pretrained timm weights for the backbone.\n\n```python\nfrom transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation\n\nconfig = MaskFormerConfig(backbone=\"resnet50\", use_pretrained_backbone=True, use_timm_backbone=True) # backbone and neck config\nmodel = MaskFormerForInstanceSegmentation(config) # head\n```\n\nSet `use_timm_backbone=True` and `use_pretrained_backbone=False` to load a randomly initialized timm backbone."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: c51c59fd-c707-4dea-b2c2-b180d88c477a
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/create_a_model", "title": "Create a custom architecture", "tokens": 4699, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"c51c59fd-c707-4dea-b2c2-b180d88c477a\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"b88d0498-9a36-4283-bdc9-3eaf0b29cc02\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8ba46afe581db3eec89c4dc44fce458850ae1d6e4a1482c90791c118a7846287\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"b2e4241f-bd43-4d1e-a40f-7e747229fd02\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"837b35f10edb1b92ba996718e48600077ea887d04cd93ef25249fee54691612f\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"cb2a81b9-e2b1-495e-9330-0dacdf4a62b3\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"a5a0ec48555ad6214e2ba002241f55c0926715c1cf9fb41be65af115e72cd50e\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 13602, \"end_char_idx\": 16584, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "ref_doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "chroma:document": "```py\nfrom transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation\n\nconfig = MaskFormerConfig(backbone=\"microsoft/resnet-50\", use_pretrained_backbone=True) # backbone and neck config\nmodel = MaskFormerForInstanceSegmentation(config) # head\n```\n\n</hfoption>\n<hfoption id=\"random weights\">\n\nSet `use_pretrained_backbone=False` to randomly initialize a ResNet backbone.\n\n```py\nfrom transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation\n\nconfig = MaskFormerConfig(backbone=\"microsoft/resnet-50\", use_pretrained_backbone=False) # backbone and neck config\nmodel = MaskFormerForInstanceSegmentation(config) # head\n```\n\nYou could also load the backbone config separately and then pass it to the model config.\n\n```py\nfrom transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, ResNetConfig\n\nbackbone_config = ResNetConfig()\nconfig = MaskFormerConfig(backbone_config=backbone_config)\nmodel = MaskFormerForInstanceSegmentation(config)\n```\n\n</hfoption>\n</hfoptions id=\"timm backbone\">\n\n[timm](https://hf.co/docs/timm/index) models are loaded within a model with `use_timm_backbone=True` or with [`TimmBackbone`] and [`TimmBackboneConfig`].\n\nUse `use_timm_backbone=True` and `use_pretrained_backbone=True` to load pretrained timm weights for the backbone.\n\n```python\nfrom transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation\n\nconfig = MaskFormerConfig(backbone=\"resnet50\", use_pretrained_backbone=True, use_timm_backbone=True) # backbone and neck config\nmodel = MaskFormerForInstanceSegmentation(config) # head\n```\n\nSet `use_timm_backbone=True` and `use_pretrained_backbone=False` to load a randomly initialized timm backbone.\n\n```python\nfrom transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation\n\nconfig = MaskFormerConfig(backbone=\"resnet50\", use_pretrained_backbone=False, use_timm_backbone=True) # backbone and neck config\nmodel = MaskFormerForInstanceSegmentation(config) # head\n```\n\nYou could also load the backbone config and use it to create a `TimmBackbone` or pass it to the model config. Timm backbones will load pretrained weights by default. Set `use_pretrained_backbone=False` to load randomly initialized weights.\n\n```python\nfrom transformers import TimmBackboneConfig, TimmBackbone\n\nbackbone_config = TimmBackboneConfig(\"resnet50\", use_pretrained_backbone=False)\n\n# Create a backbone class\nbackbone = TimmBackbone(config=backbone_config)\n\n# Create a model with a timm backbone\nfrom transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation\n\nconfig = MaskFormerConfig(backbone_config=backbone_config)\nmodel = MaskFormerForInstanceSegmentation(config)\n```\n\n## Feature extractor\n\nA feature extractor processes audio inputs. It inherits from the base [`~feature_extraction_utils.FeatureExtractionMixin`] class, and may also inherit from the [`SequenceFeatureExtractor`] class for processing audio inputs.\n\nTo use, create a feature extractor associated with the model you're using."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: cb2a81b9-e2b1-495e-9330-0dacdf4a62b3
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/create_a_model", "title": "Create a custom architecture", "tokens": 4699, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"cb2a81b9-e2b1-495e-9330-0dacdf4a62b3\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"b88d0498-9a36-4283-bdc9-3eaf0b29cc02\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8ba46afe581db3eec89c4dc44fce458850ae1d6e4a1482c90791c118a7846287\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"c51c59fd-c707-4dea-b2c2-b180d88c477a\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"a46ed4f592de4ff7b1e7712b0f999506a52a400975ee09c0dd86b7183fc0cb8b\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"9ade586f-6643-4c94-a316-47e4c3fe52b4\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"f60fa4c524bd51c61f93430adbef83bfb17dbe28ebd3c4be56967f996eff408f\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 14898, \"end_char_idx\": 18073, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "ref_doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "chroma:document": "```python\nfrom transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation\n\nconfig = MaskFormerConfig(backbone=\"resnet50\", use_pretrained_backbone=True, use_timm_backbone=True) # backbone and neck config\nmodel = MaskFormerForInstanceSegmentation(config) # head\n```\n\nSet `use_timm_backbone=True` and `use_pretrained_backbone=False` to load a randomly initialized timm backbone.\n\n```python\nfrom transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation\n\nconfig = MaskFormerConfig(backbone=\"resnet50\", use_pretrained_backbone=False, use_timm_backbone=True) # backbone and neck config\nmodel = MaskFormerForInstanceSegmentation(config) # head\n```\n\nYou could also load the backbone config and use it to create a `TimmBackbone` or pass it to the model config. Timm backbones will load pretrained weights by default. Set `use_pretrained_backbone=False` to load randomly initialized weights.\n\n```python\nfrom transformers import TimmBackboneConfig, TimmBackbone\n\nbackbone_config = TimmBackboneConfig(\"resnet50\", use_pretrained_backbone=False)\n\n# Create a backbone class\nbackbone = TimmBackbone(config=backbone_config)\n\n# Create a model with a timm backbone\nfrom transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation\n\nconfig = MaskFormerConfig(backbone_config=backbone_config)\nmodel = MaskFormerForInstanceSegmentation(config)\n```\n\n## Feature extractor\n\nA feature extractor processes audio inputs. It inherits from the base [`~feature_extraction_utils.FeatureExtractionMixin`] class, and may also inherit from the [`SequenceFeatureExtractor`] class for processing audio inputs.\n\nTo use, create a feature extractor associated with the model you're using. For example, create a default [`Wav2Vec2FeatureExtractor`] if you are using [Wav2Vec2](model_doc/wav2vec2) for audio classification:\n\n```py\n>>> from transformers import Wav2Vec2FeatureExtractor\n\n>>> w2v2_extractor = Wav2Vec2FeatureExtractor()\n>>> print(w2v2_extractor)\nWav2Vec2FeatureExtractor {\n  \"do_normalize\": true,\n  \"feature_extractor_type\": \"Wav2Vec2FeatureExtractor\",\n  \"feature_size\": 1,\n  \"padding_side\": \"right\",\n  \"padding_value\": 0.0,\n  \"return_attention_mask\": false,\n  \"sampling_rate\": 16000\n}\n```\n\n<Tip>\n\nIf you aren't looking for any customization, just use the `from_pretrained` method to load a model's default feature extractor parameters.\n\n</Tip>\n\nModify any of the [`Wav2Vec2FeatureExtractor`] parameters to create your custom feature extractor:\n\n```py\n>>> from transformers import Wav2Vec2FeatureExtractor\n\n>>> w2v2_extractor = Wav2Vec2FeatureExtractor(sampling_rate=8000, do_normalize=False)\n>>> print(w2v2_extractor)\nWav2Vec2FeatureExtractor {\n  \"do_normalize\": false,\n  \"feature_extractor_type\": \"Wav2Vec2FeatureExtractor\",\n  \"feature_size\": 1,\n  \"padding_side\": \"right\",\n  \"padding_value\": 0.0,\n  \"return_attention_mask\": false,\n  \"sampling_rate\": 8000\n}\n```\n\n## Processor\n\nFor models that support multimodal tasks, \ud83e\udd17 Transformers offers a processor class that conveniently wraps processing classes such as a feature extractor and a tokenizer into a single object. For example, let's use the [`Wav2Vec2Processor`] for an automatic speech recognition task (ASR)."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 9ade586f-6643-4c94-a316-47e4c3fe52b4
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/create_a_model", "title": "Create a custom architecture", "tokens": 4699, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"9ade586f-6643-4c94-a316-47e4c3fe52b4\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"b88d0498-9a36-4283-bdc9-3eaf0b29cc02\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8ba46afe581db3eec89c4dc44fce458850ae1d6e4a1482c90791c118a7846287\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"cb2a81b9-e2b1-495e-9330-0dacdf4a62b3\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/create_a_model\", \"title\": \"Create a custom architecture\", \"tokens\": 4699, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"70377aacd483deb02318033f778c383c6603aec1d077483ab963cec3fdd37223\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 16585, \"end_char_idx\": 19176, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "ref_doc_id": "b88d0498-9a36-4283-bdc9-3eaf0b29cc02", "chroma:document": "For example, create a default [`Wav2Vec2FeatureExtractor`] if you are using [Wav2Vec2](model_doc/wav2vec2) for audio classification:\n\n```py\n>>> from transformers import Wav2Vec2FeatureExtractor\n\n>>> w2v2_extractor = Wav2Vec2FeatureExtractor()\n>>> print(w2v2_extractor)\nWav2Vec2FeatureExtractor {\n  \"do_normalize\": true,\n  \"feature_extractor_type\": \"Wav2Vec2FeatureExtractor\",\n  \"feature_size\": 1,\n  \"padding_side\": \"right\",\n  \"padding_value\": 0.0,\n  \"return_attention_mask\": false,\n  \"sampling_rate\": 16000\n}\n```\n\n<Tip>\n\nIf you aren't looking for any customization, just use the `from_pretrained` method to load a model's default feature extractor parameters.\n\n</Tip>\n\nModify any of the [`Wav2Vec2FeatureExtractor`] parameters to create your custom feature extractor:\n\n```py\n>>> from transformers import Wav2Vec2FeatureExtractor\n\n>>> w2v2_extractor = Wav2Vec2FeatureExtractor(sampling_rate=8000, do_normalize=False)\n>>> print(w2v2_extractor)\nWav2Vec2FeatureExtractor {\n  \"do_normalize\": false,\n  \"feature_extractor_type\": \"Wav2Vec2FeatureExtractor\",\n  \"feature_size\": 1,\n  \"padding_side\": \"right\",\n  \"padding_value\": 0.0,\n  \"return_attention_mask\": false,\n  \"sampling_rate\": 8000\n}\n```\n\n## Processor\n\nFor models that support multimodal tasks, \ud83e\udd17 Transformers offers a processor class that conveniently wraps processing classes such as a feature extractor and a tokenizer into a single object. For example, let's use the [`Wav2Vec2Processor`] for an automatic speech recognition task (ASR). ASR transcribes audio to text, so you will need a feature extractor and a tokenizer.\n\nCreate a feature extractor to handle the audio inputs:\n\n```py\n>>> from transformers import Wav2Vec2FeatureExtractor\n\n>>> feature_extractor = Wav2Vec2FeatureExtractor(padding_value=1.0, do_normalize=True)\n```\n\nCreate a tokenizer to handle the text inputs:\n\n```py\n>>> from transformers import Wav2Vec2CTCTokenizer\n\n>>> tokenizer = Wav2Vec2CTCTokenizer(vocab_file=\"my_vocab_file.txt\")\n```\n\nCombine the feature extractor and tokenizer in [`Wav2Vec2Processor`]:\n\n```py\n>>> from transformers import Wav2Vec2Processor\n\n>>> processor = Wav2Vec2Processor(feature_extractor=feature_extractor, tokenizer=tokenizer)\n```\n\nWith two basic classes - configuration and model - and an additional preprocessing class (tokenizer, image processor, feature extractor, or processor), you can create any of the models supported by \ud83e\udd17 Transformers. Each of these base classes are configurable, allowing you to use the specific attributes you want. You can easily setup a model for training or modify an existing pretrained model to fine-tune."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 72e2377b-9b9b-4b55-98a4-137e62e82b3f
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_train_gpu_one", "title": "Methods and tools for efficient training on a single GPU", "tokens": 7716, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"72e2377b-9b9b-4b55-98a4-137e62e82b3f\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"7a488fe5-6358-4f8d-8e94-daa390cebae2\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f4a1199f6734143a23fa61a74b0292b4dc919543135f61bdce1e193e695c4196\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"12d0502b-7165-4c74-8878-7e7ec57959e1\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"1d294bb065ef66ccb5a16ce1cead7cfbf88423f3d17eca5286d30ac185b77512\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 0, \"end_char_idx\": 4663, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "ref_doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "chroma:document": "# Methods and tools for efficient training on a single GPU\n\nThis guide demonstrates practical techniques that you can use to increase the efficiency of your model's training by \noptimizing memory utilization, speeding up the training, or both. If you'd like to understand how GPU is utilized during \ntraining, please refer to the [Model training anatomy](model_memory_anatomy) conceptual guide first. This guide \nfocuses on practical techniques.  \n\n<Tip>\n\nIf you have access to a machine with multiple GPUs, these approaches are still valid, plus you can leverage additional methods outlined in the [multi-GPU section](perf_train_gpu_many).\n\n</Tip>\n\nWhen training large models, there are two aspects that should be considered at the same time: \n\n* Data throughput/training time\n* Model performance\n\nMaximizing the throughput (samples/second) leads to lower training cost. This is generally achieved by utilizing the GPU \nas much as possible and thus filling GPU memory to its limit. If the desired batch size exceeds the limits of the GPU memory, \nthe memory optimization techniques, such as gradient accumulation, can help.\n\nHowever, if the preferred batch size fits into memory, there's no reason to apply memory-optimizing techniques because they can \nslow down the training. Just because one can use a large batch size, does not necessarily mean they should. As part of \nhyperparameter tuning, you should determine which batch size yields the best results and then optimize resources accordingly.\n\nThe methods and tools covered in this guide can be classified based on the effect they have on the training process:\n\n| Method/tool                                                                                                                                             | Improves training speed | Optimizes memory utilization |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------|:------------------------|:-----------------------------|\n| [Batch size choice](#batch-size-choice)                                                                                                                 | Yes                     | Yes                          |\n| [Gradient accumulation](#gradient-accumulation)                                                                                                         | No                      | Yes                          |\n| [Gradient checkpointing](#gradient-checkpointing)                                                                                                       | No                      | Yes                          |\n| [Mixed precision training](#mixed-precision-training)                                                                                                   | Yes                     | Maybe*                       |\n| [torch_empty_cache_steps](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments.torch_empty_cache_steps) | No                      | Yes                          |\n| [Optimizer choice](#optimizer-choice)                                                                                                                   | Yes                     | Yes                          |\n| [Data preloading](#data-preloading)                                                                                                                     | Yes                     | No                           |\n| [DeepSpeed Zero](#deepspeed-zero)                                                                                                                       | No                      | Yes                          |\n| [torch.compile](#using-torchcompile)                                                                                                                    | Yes                     | No                           |\n| [Parameter-Efficient Fine Tuning (PEFT)](#using--peft)                                                                                                  | No                      | Yes                          |\n \n<Tip>\n\n*Note: when using mixed precision with a small model and a large batch size, there will be some memory savings but with a \nlarge model and a small batch size, the memory use will be larger.\n\n</Tip>\n\nYou can combine the above methods to get a cumulative effect. These techniques are available to you whether you are \ntraining your model with [`Trainer`] or writing a pure PyTorch loop, in which case you can [configure these optimizations \nwith \ud83e\udd17 Accelerate](#using--accelerate)."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 12d0502b-7165-4c74-8878-7e7ec57959e1
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_train_gpu_one", "title": "Methods and tools for efficient training on a single GPU", "tokens": 7716, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"12d0502b-7165-4c74-8878-7e7ec57959e1\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"7a488fe5-6358-4f8d-8e94-daa390cebae2\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f4a1199f6734143a23fa61a74b0292b4dc919543135f61bdce1e193e695c4196\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"72e2377b-9b9b-4b55-98a4-137e62e82b3f\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"33662ed06fd11420e69357661dacf9342b61d4091938221c6ddf331891986828\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"db95c774-2592-4f38-91e7-cffc46a1919b\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"eb294357966085c238f3a027bb664ba22bb21e2e71a2a0c452ee62cfd9986e40\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 1502, \"end_char_idx\": 6318, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "ref_doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "chroma:document": "The methods and tools covered in this guide can be classified based on the effect they have on the training process:\n\n| Method/tool                                                                                                                                             | Improves training speed | Optimizes memory utilization |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------|:------------------------|:-----------------------------|\n| [Batch size choice](#batch-size-choice)                                                                                                                 | Yes                     | Yes                          |\n| [Gradient accumulation](#gradient-accumulation)                                                                                                         | No                      | Yes                          |\n| [Gradient checkpointing](#gradient-checkpointing)                                                                                                       | No                      | Yes                          |\n| [Mixed precision training](#mixed-precision-training)                                                                                                   | Yes                     | Maybe*                       |\n| [torch_empty_cache_steps](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments.torch_empty_cache_steps) | No                      | Yes                          |\n| [Optimizer choice](#optimizer-choice)                                                                                                                   | Yes                     | Yes                          |\n| [Data preloading](#data-preloading)                                                                                                                     | Yes                     | No                           |\n| [DeepSpeed Zero](#deepspeed-zero)                                                                                                                       | No                      | Yes                          |\n| [torch.compile](#using-torchcompile)                                                                                                                    | Yes                     | No                           |\n| [Parameter-Efficient Fine Tuning (PEFT)](#using--peft)                                                                                                  | No                      | Yes                          |\n \n<Tip>\n\n*Note: when using mixed precision with a small model and a large batch size, there will be some memory savings but with a \nlarge model and a small batch size, the memory use will be larger.\n\n</Tip>\n\nYou can combine the above methods to get a cumulative effect. These techniques are available to you whether you are \ntraining your model with [`Trainer`] or writing a pure PyTorch loop, in which case you can [configure these optimizations \nwith \ud83e\udd17 Accelerate](#using--accelerate).\n\nIf these methods do not result in sufficient gains, you can explore the following options: \n* [Look into building your own custom Docker container with efficient software prebuilds](#efficient-software-prebuilds)\n* [Consider a model that uses Mixture of Experts (MoE)](#mixture-of-experts)\n* [Convert your model to BetterTransformer to leverage PyTorch native attention](#using-pytorch-native-attention-and-flash-attention)\n\nFinally, if all of the above is still not enough, even after switching to a server-grade GPU like A100, consider moving \nto a multi-GPU setup. All these approaches are still valid in a multi-GPU setup, plus you can leverage additional parallelism \ntechniques outlined in the [multi-GPU section](perf_train_gpu_many). \n\n## Batch size choice\n\nTo achieve optimal performance, start by identifying the appropriate batch size. It is recommended to use batch sizes and \ninput/output neuron counts that are of size 2^N. Often it's a multiple of 8, but it can be \nhigher depending on the hardware being used and the model's dtype.\n\nFor reference, check out NVIDIA's recommendation for [input/output neuron counts](\nhttps://docs.nvidia.com/deeplearning/performance/dl-performance-fully-connected/index.html#input-features) and \n[batch size](https://docs.nvidia.com/deeplearning/performance/dl-performance-fully-connected/index.html#batch-size) for \nfully connected layers (which are involved in GEMMs (General Matrix Multiplications)).\n\n[Tensor Core Requirements](https://docs.nvidia.com/deeplearning/performance/dl-performance-matrix-multiplication/index.html#requirements-tc) \ndefine the multiplier based on the dtype and the hardware."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: db95c774-2592-4f38-91e7-cffc46a1919b
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_train_gpu_one", "title": "Methods and tools for efficient training on a single GPU", "tokens": 7716, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"db95c774-2592-4f38-91e7-cffc46a1919b\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"7a488fe5-6358-4f8d-8e94-daa390cebae2\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f4a1199f6734143a23fa61a74b0292b4dc919543135f61bdce1e193e695c4196\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"12d0502b-7165-4c74-8878-7e7ec57959e1\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"63165444d87b03c9ae27ec3bbf51f4a7f2b7c64fb01ac7d6626a2905335cb9c7\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"4fe101b5-f8cd-4ad6-9fb7-19f7457c2ef5\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"892334beae99862449fa14745627e2e6fb3411fb67ddeac0469caa24e1c160ba\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 4665, \"end_char_idx\": 8258, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "ref_doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "chroma:document": "If these methods do not result in sufficient gains, you can explore the following options: \n* [Look into building your own custom Docker container with efficient software prebuilds](#efficient-software-prebuilds)\n* [Consider a model that uses Mixture of Experts (MoE)](#mixture-of-experts)\n* [Convert your model to BetterTransformer to leverage PyTorch native attention](#using-pytorch-native-attention-and-flash-attention)\n\nFinally, if all of the above is still not enough, even after switching to a server-grade GPU like A100, consider moving \nto a multi-GPU setup. All these approaches are still valid in a multi-GPU setup, plus you can leverage additional parallelism \ntechniques outlined in the [multi-GPU section](perf_train_gpu_many). \n\n## Batch size choice\n\nTo achieve optimal performance, start by identifying the appropriate batch size. It is recommended to use batch sizes and \ninput/output neuron counts that are of size 2^N. Often it's a multiple of 8, but it can be \nhigher depending on the hardware being used and the model's dtype.\n\nFor reference, check out NVIDIA's recommendation for [input/output neuron counts](\nhttps://docs.nvidia.com/deeplearning/performance/dl-performance-fully-connected/index.html#input-features) and \n[batch size](https://docs.nvidia.com/deeplearning/performance/dl-performance-fully-connected/index.html#batch-size) for \nfully connected layers (which are involved in GEMMs (General Matrix Multiplications)).\n\n[Tensor Core Requirements](https://docs.nvidia.com/deeplearning/performance/dl-performance-matrix-multiplication/index.html#requirements-tc) \ndefine the multiplier based on the dtype and the hardware. For instance, for fp16 data type a multiple of 8 is recommended, unless \nit's an A100 GPU, in which case use multiples of 64.\n\nFor parameters that are small, consider also [Dimension Quantization Effects](https://docs.nvidia.com/deeplearning/performance/dl-performance-matrix-multiplication/index.html#dim-quantization). \nThis is where tiling happens and the right multiplier can have a significant speedup.\n\n## Gradient Accumulation\n\nThe **gradient accumulation** method aims to calculate gradients in smaller increments instead of computing them for the \nentire batch at once. This approach involves iteratively calculating gradients in smaller batches by performing forward \nand backward passes through the model and accumulating the gradients during the process. Once a sufficient number of \ngradients have been accumulated, the model's optimization step is executed. By employing gradient accumulation, it \nbecomes possible to increase the **effective batch size** beyond the limitations imposed by the GPU's memory capacity. \nHowever, it is important to note that the additional forward and backward passes introduced by gradient accumulation can \nslow down the training process.\n\nYou can enable gradient accumulation by adding the `gradient_accumulation_steps` argument to  [`TrainingArguments`]: \n\n```py\ntraining_args = TrainingArguments(per_device_train_batch_size=1, gradient_accumulation_steps=4, **default_args)\n```\n\nIn the above example, your effective batch size becomes 4. \n\nAlternatively, use \ud83e\udd17 Accelerate to gain full control over the training loop. Find the \ud83e\udd17 Accelerate example \n[further down in this guide](#using--accelerate).\n\nWhile it is advised to max out GPU usage as much as possible, a high number of gradient accumulation steps can \nresult in a more pronounced training slowdown. Consider the following example. Let's say, the `per_device_train_batch_size=4` \nwithout gradient accumulation hits the GPU's limit."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 4fe101b5-f8cd-4ad6-9fb7-19f7457c2ef5
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_train_gpu_one", "title": "Methods and tools for efficient training on a single GPU", "tokens": 7716, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"4fe101b5-f8cd-4ad6-9fb7-19f7457c2ef5\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"7a488fe5-6358-4f8d-8e94-daa390cebae2\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f4a1199f6734143a23fa61a74b0292b4dc919543135f61bdce1e193e695c4196\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"db95c774-2592-4f38-91e7-cffc46a1919b\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"03bca210cb066a00cee89f818cdc36c6076434d8778cc4552becf9f29b940755\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"b8a2ec4a-d332-4e54-bcf5-59b337eb394c\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"da9605a755e7e7b3993b8b98eae6d58f29cf8b39ebba6fab809a05668083f7a5\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 6446, \"end_char_idx\": 9864, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "ref_doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "chroma:document": "For parameters that are small, consider also [Dimension Quantization Effects](https://docs.nvidia.com/deeplearning/performance/dl-performance-matrix-multiplication/index.html#dim-quantization). \nThis is where tiling happens and the right multiplier can have a significant speedup.\n\n## Gradient Accumulation\n\nThe **gradient accumulation** method aims to calculate gradients in smaller increments instead of computing them for the \nentire batch at once. This approach involves iteratively calculating gradients in smaller batches by performing forward \nand backward passes through the model and accumulating the gradients during the process. Once a sufficient number of \ngradients have been accumulated, the model's optimization step is executed. By employing gradient accumulation, it \nbecomes possible to increase the **effective batch size** beyond the limitations imposed by the GPU's memory capacity. \nHowever, it is important to note that the additional forward and backward passes introduced by gradient accumulation can \nslow down the training process.\n\nYou can enable gradient accumulation by adding the `gradient_accumulation_steps` argument to  [`TrainingArguments`]: \n\n```py\ntraining_args = TrainingArguments(per_device_train_batch_size=1, gradient_accumulation_steps=4, **default_args)\n```\n\nIn the above example, your effective batch size becomes 4. \n\nAlternatively, use \ud83e\udd17 Accelerate to gain full control over the training loop. Find the \ud83e\udd17 Accelerate example \n[further down in this guide](#using--accelerate).\n\nWhile it is advised to max out GPU usage as much as possible, a high number of gradient accumulation steps can \nresult in a more pronounced training slowdown. Consider the following example. Let's say, the `per_device_train_batch_size=4` \nwithout gradient accumulation hits the GPU's limit. If you would like to train with batches of size 64, do not set the \n`per_device_train_batch_size` to 1 and `gradient_accumulation_steps` to 64. Instead, keep `per_device_train_batch_size=4` \nand set `gradient_accumulation_steps=16`. This results in the same effective batch size while making better use of \nthe available GPU resources.\n\nFor additional information, please refer to batch size and gradient accumulation benchmarks for [RTX-3090](https://github.com/huggingface/transformers/issues/14608#issuecomment-1004392537)\nand [A100](https://github.com/huggingface/transformers/issues/15026#issuecomment-1005033957).\n\n## Gradient Checkpointing\n\nSome large models may still face memory issues even when the batch size is set to 1 and gradient accumulation is used. \nThis is because there are other components that also require memory storage.\n\nSaving all activations from the forward pass in order to compute the gradients during the backward pass can result in \nsignificant memory overhead. The alternative approach of discarding the activations and recalculating them when needed \nduring the backward pass, would introduce a considerable computational overhead and slow down the training process.\n\n**Gradient checkpointing** offers a compromise between these two approaches and saves strategically selected activations \nthroughout the computational graph so only a fraction of the activations need to be re-computed for the gradients. For \nan in-depth explanation of gradient checkpointing, refer to [this great article](https://medium.com/tensorflow/fitting-larger-networks-into-memory-583e3c758ff9)."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: b8a2ec4a-d332-4e54-bcf5-59b337eb394c
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_train_gpu_one", "title": "Methods and tools for efficient training on a single GPU", "tokens": 7716, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"b8a2ec4a-d332-4e54-bcf5-59b337eb394c\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"7a488fe5-6358-4f8d-8e94-daa390cebae2\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f4a1199f6734143a23fa61a74b0292b4dc919543135f61bdce1e193e695c4196\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"4fe101b5-f8cd-4ad6-9fb7-19f7457c2ef5\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"14ec32b5c955abd6993caa094cb597e650b576c879fb0afb34b1e001426ce89a\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"a4720a37-8c6e-43fe-99f6-c1b0ebae86ed\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"44d8cb7ee24f612184b3c99d5457da56a579a26848c689859c000e11e87d8ad7\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 8127, \"end_char_idx\": 11768, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "ref_doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "chroma:document": "Consider the following example. Let's say, the `per_device_train_batch_size=4` \nwithout gradient accumulation hits the GPU's limit. If you would like to train with batches of size 64, do not set the \n`per_device_train_batch_size` to 1 and `gradient_accumulation_steps` to 64. Instead, keep `per_device_train_batch_size=4` \nand set `gradient_accumulation_steps=16`. This results in the same effective batch size while making better use of \nthe available GPU resources.\n\nFor additional information, please refer to batch size and gradient accumulation benchmarks for [RTX-3090](https://github.com/huggingface/transformers/issues/14608#issuecomment-1004392537)\nand [A100](https://github.com/huggingface/transformers/issues/15026#issuecomment-1005033957).\n\n## Gradient Checkpointing\n\nSome large models may still face memory issues even when the batch size is set to 1 and gradient accumulation is used. \nThis is because there are other components that also require memory storage.\n\nSaving all activations from the forward pass in order to compute the gradients during the backward pass can result in \nsignificant memory overhead. The alternative approach of discarding the activations and recalculating them when needed \nduring the backward pass, would introduce a considerable computational overhead and slow down the training process.\n\n**Gradient checkpointing** offers a compromise between these two approaches and saves strategically selected activations \nthroughout the computational graph so only a fraction of the activations need to be re-computed for the gradients. For \nan in-depth explanation of gradient checkpointing, refer to [this great article](https://medium.com/tensorflow/fitting-larger-networks-into-memory-583e3c758ff9).\n\nTo enable gradient checkpointing in the [`Trainer`], pass the corresponding a flag to [`TrainingArguments`]:\n\n```py\ntraining_args = TrainingArguments(\n    per_device_train_batch_size=1, gradient_accumulation_steps=4, gradient_checkpointing=True, **default_args\n)\n```\n\nAlternatively, use \ud83e\udd17 Accelerate - find the \ud83e\udd17 Accelerate example [further in this guide](#using--accelerate). \n\n<Tip>\n\nWhile gradient checkpointing may improve memory efficiency, it slows training by approximately 20%.\n\n</Tip>\n\n## Mixed precision training\n\n**Mixed precision training** is a technique that aims to optimize the computational efficiency of training models by \nutilizing lower-precision numerical formats for certain variables. Traditionally, most models use 32-bit floating point \nprecision (fp32 or float32) to represent and process variables. However, not all variables require this high precision \nlevel to achieve accurate results. By reducing the precision of certain variables to lower numerical formats like 16-bit \nfloating point (fp16 or float16), we can speed up the computations. Because in this approach some computations are performed \nin half-precision, while some are still in full precision, the approach is called mixed precision training.\n\nMost commonly mixed precision training is achieved by using fp16 (float16) data types, however, some GPU architectures \n(such as the Ampere architecture) offer bf16 and tf32 (CUDA internal data type) data types. Check \nout the [NVIDIA Blog](https://developer.nvidia.com/blog/accelerating-ai-training-with-tf32-tensor-cores/) to learn more about \nthe differences between these data types.\n\n### fp16\n\nThe main advantage of mixed precision training comes from saving the activations in half precision (fp16). \nAlthough the gradients are also computed in half precision they are converted back to full precision for the optimization \nstep so no memory is saved here."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: a4720a37-8c6e-43fe-99f6-c1b0ebae86ed
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_train_gpu_one", "title": "Methods and tools for efficient training on a single GPU", "tokens": 7716, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"a4720a37-8c6e-43fe-99f6-c1b0ebae86ed\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"7a488fe5-6358-4f8d-8e94-daa390cebae2\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f4a1199f6734143a23fa61a74b0292b4dc919543135f61bdce1e193e695c4196\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"b8a2ec4a-d332-4e54-bcf5-59b337eb394c\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"76ae7d5f524559e6aa10ed38fe45e29e575a30a7a3346896a5587c9cf0c5b447\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"0efd6277-fada-4eb0-8aa2-b6d50b55adb0\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"4b3721e222332d2bf8efbb5456adc6108af4f418d419433dac15209598569963\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 10245, \"end_char_idx\": 13584, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "ref_doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "chroma:document": "<Tip>\n\nWhile gradient checkpointing may improve memory efficiency, it slows training by approximately 20%.\n\n</Tip>\n\n## Mixed precision training\n\n**Mixed precision training** is a technique that aims to optimize the computational efficiency of training models by \nutilizing lower-precision numerical formats for certain variables. Traditionally, most models use 32-bit floating point \nprecision (fp32 or float32) to represent and process variables. However, not all variables require this high precision \nlevel to achieve accurate results. By reducing the precision of certain variables to lower numerical formats like 16-bit \nfloating point (fp16 or float16), we can speed up the computations. Because in this approach some computations are performed \nin half-precision, while some are still in full precision, the approach is called mixed precision training.\n\nMost commonly mixed precision training is achieved by using fp16 (float16) data types, however, some GPU architectures \n(such as the Ampere architecture) offer bf16 and tf32 (CUDA internal data type) data types. Check \nout the [NVIDIA Blog](https://developer.nvidia.com/blog/accelerating-ai-training-with-tf32-tensor-cores/) to learn more about \nthe differences between these data types.\n\n### fp16\n\nThe main advantage of mixed precision training comes from saving the activations in half precision (fp16). \nAlthough the gradients are also computed in half precision they are converted back to full precision for the optimization \nstep so no memory is saved here. \nWhile mixed precision training results in faster computations, it can also lead to more GPU memory being utilized, especially for small batch sizes.\nThis is because the model is now present on the GPU in both 16-bit and 32-bit precision (1.5x the original model on the GPU).\n\nTo enable mixed precision training, set the `fp16` flag to `True`:\n\n```py\ntraining_args = TrainingArguments(per_device_train_batch_size=4, fp16=True, **default_args)\n```\n\nIf you prefer to use \ud83e\udd17 Accelerate, find the \ud83e\udd17 Accelerate example [further in this guide](#using--accelerate). \n\n### BF16\n\nIf you have access to an Ampere or newer hardware you can use bf16 for mixed precision training and evaluation. While \nbf16 has a worse precision than fp16, it has a much bigger dynamic range. In fp16 the biggest number you can have \nis `65535` and any number above that will result in an overflow. A bf16 number can be as large as `3.39e+38` (!) which \nis about the same as fp32 - because both have 8-bits used for the numerical range.\n\nYou can enable BF16 in the \ud83e\udd17 Trainer with:\n\n```python\ntraining_args = TrainingArguments(bf16=True, **default_args)\n```\n\n### TF32\n\nThe Ampere hardware uses a magical data type called tf32. It has the same numerical range as fp32 (8-bits), but instead \nof 23 bits precision it has only 10 bits (same as fp16) and uses only 19 bits in total. It's \"magical\" in the sense that \nyou can use the normal fp32 training and/or inference code and by enabling tf32 support you can get up to 3x throughput \nimprovement. All you need to do is to add the following to your code:\n\n```python\nimport torch\ntorch.backends.cuda.matmul.allow_tf32 = True\ntorch.backends.cudnn.allow_tf32 = True\n```\n\nCUDA will automatically switch to using tf32 instead of fp32 where possible, assuming that the used GPU is from the Ampere series."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 0efd6277-fada-4eb0-8aa2-b6d50b55adb0
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_train_gpu_one", "title": "Methods and tools for efficient training on a single GPU", "tokens": 7716, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"0efd6277-fada-4eb0-8aa2-b6d50b55adb0\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"7a488fe5-6358-4f8d-8e94-daa390cebae2\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f4a1199f6734143a23fa61a74b0292b4dc919543135f61bdce1e193e695c4196\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"a4720a37-8c6e-43fe-99f6-c1b0ebae86ed\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"0d91525d66274f7f2595a19fb84ecb59add85380e23867b615bb5cbebb756536\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"e01ef5fc-a15f-49e7-a8c6-08a97bc3a215\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"81275c55185587f37ff37d2e5261d369d5a345a48d0ba8b2a4a92abb5cee2638\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 12329, \"end_char_idx\": 15435, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "ref_doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "chroma:document": "### BF16\n\nIf you have access to an Ampere or newer hardware you can use bf16 for mixed precision training and evaluation. While \nbf16 has a worse precision than fp16, it has a much bigger dynamic range. In fp16 the biggest number you can have \nis `65535` and any number above that will result in an overflow. A bf16 number can be as large as `3.39e+38` (!) which \nis about the same as fp32 - because both have 8-bits used for the numerical range.\n\nYou can enable BF16 in the \ud83e\udd17 Trainer with:\n\n```python\ntraining_args = TrainingArguments(bf16=True, **default_args)\n```\n\n### TF32\n\nThe Ampere hardware uses a magical data type called tf32. It has the same numerical range as fp32 (8-bits), but instead \nof 23 bits precision it has only 10 bits (same as fp16) and uses only 19 bits in total. It's \"magical\" in the sense that \nyou can use the normal fp32 training and/or inference code and by enabling tf32 support you can get up to 3x throughput \nimprovement. All you need to do is to add the following to your code:\n\n```python\nimport torch\ntorch.backends.cuda.matmul.allow_tf32 = True\ntorch.backends.cudnn.allow_tf32 = True\n```\n\nCUDA will automatically switch to using tf32 instead of fp32 where possible, assuming that the used GPU is from the Ampere series.\n\nAccording to [NVIDIA research](https://developer.nvidia.com/blog/accelerating-ai-training-with-tf32-tensor-cores/), the \nmajority of machine learning training workloads show the same perplexity and convergence with tf32 training as with fp32. \nIf you're already using fp16 or bf16 mixed precision it may help with the throughput as well.\n\nYou can enable this mode in the \ud83e\udd17 Trainer:\n\n```python\nTrainingArguments(tf32=True, **default_args)\n```\n\n<Tip>\n\ntf32 can't be accessed directly via `tensor.to(dtype=torch.tf32)` because it is an internal CUDA data type. You need `torch>=1.7` to use tf32 data types.\n\n</Tip>\n\nFor additional information on tf32 vs other precisions, please refer to the following benchmarks: \n[RTX-3090](https://github.com/huggingface/transformers/issues/14608#issuecomment-1004390803) and\n[A100](https://github.com/huggingface/transformers/issues/15026#issuecomment-1004543189).\n\n## Flash Attention 2\n\nYou can speedup the training throughput by using Flash Attention 2 integration in transformers. Check out the appropriate section in the [single GPU section](./perf_infer_gpu_one#Flash-Attention-2) to learn more about how to load a model with Flash Attention 2 modules. \n\n## Optimizer choice\n\nThe most common optimizer used to train transformer models is Adam or AdamW (Adam with weight decay). Adam achieves \ngood convergence by storing the rolling average of the previous gradients; however, it adds an additional memory \nfootprint of the order of the number of model parameters. To remedy this, you can use an alternative optimizer. \nFor example if you have [NVIDIA/apex](https://github.com/NVIDIA/apex) installed for NVIDIA GPUs, or [ROCmSoftwarePlatform/apex](https://github.com/ROCmSoftwarePlatform/apex) for AMD GPUs, `adamw_apex_fused` will give you the\nfastest training experience among all supported AdamW optimizers."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: e01ef5fc-a15f-49e7-a8c6-08a97bc3a215
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_train_gpu_one", "title": "Methods and tools for efficient training on a single GPU", "tokens": 7716, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"e01ef5fc-a15f-49e7-a8c6-08a97bc3a215\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"7a488fe5-6358-4f8d-8e94-daa390cebae2\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f4a1199f6734143a23fa61a74b0292b4dc919543135f61bdce1e193e695c4196\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"0efd6277-fada-4eb0-8aa2-b6d50b55adb0\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"5e641d90c68823367efcc89bd3e2fe44aba65a5b010c6a7f34ade38706c2d5d9\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"73b9a327-f656-4aa3-a338-0785c16d6b04\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"7ca15e68e49fa56cdac15503edeb2bc9ada2eba13b8c85e1385faa9a67fab7cd\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 13830, \"end_char_idx\": 16652, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "ref_doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "chroma:document": "If you're already using fp16 or bf16 mixed precision it may help with the throughput as well.\n\nYou can enable this mode in the \ud83e\udd17 Trainer:\n\n```python\nTrainingArguments(tf32=True, **default_args)\n```\n\n<Tip>\n\ntf32 can't be accessed directly via `tensor.to(dtype=torch.tf32)` because it is an internal CUDA data type. You need `torch>=1.7` to use tf32 data types.\n\n</Tip>\n\nFor additional information on tf32 vs other precisions, please refer to the following benchmarks: \n[RTX-3090](https://github.com/huggingface/transformers/issues/14608#issuecomment-1004390803) and\n[A100](https://github.com/huggingface/transformers/issues/15026#issuecomment-1004543189).\n\n## Flash Attention 2\n\nYou can speedup the training throughput by using Flash Attention 2 integration in transformers. Check out the appropriate section in the [single GPU section](./perf_infer_gpu_one#Flash-Attention-2) to learn more about how to load a model with Flash Attention 2 modules. \n\n## Optimizer choice\n\nThe most common optimizer used to train transformer models is Adam or AdamW (Adam with weight decay). Adam achieves \ngood convergence by storing the rolling average of the previous gradients; however, it adds an additional memory \nfootprint of the order of the number of model parameters. To remedy this, you can use an alternative optimizer. \nFor example if you have [NVIDIA/apex](https://github.com/NVIDIA/apex) installed for NVIDIA GPUs, or [ROCmSoftwarePlatform/apex](https://github.com/ROCmSoftwarePlatform/apex) for AMD GPUs, `adamw_apex_fused` will give you the\nfastest training experience among all supported AdamW optimizers.\n\n[`Trainer`] integrates a variety of optimizers that can be used out of box: `adamw_hf`, `adamw_torch`, `adamw_torch_fused`, \n`adamw_apex_fused`, `adamw_anyprecision`, `adafactor`, or `adamw_bnb_8bit`. More optimizers can be plugged in via a third-party implementation.\n\nLet's take a closer look at two alternatives to AdamW optimizer:\n1. `adafactor` which is available in [`Trainer`]\n2. `adamw_bnb_8bit` is also available in Trainer, but a third-party integration is provided below for demonstration.\n\nFor comparison, for a 3B-parameter model, like \u201cgoogle-t5/t5-3b\u201d: \n* A standard AdamW optimizer will need 24GB of GPU memory because it uses 8 bytes for each parameter (8*3 => 24GB)\n* Adafactor optimizer will need more than 12GB. It uses slightly more than 4 bytes for each parameter, so 4*3 and then some extra.\n* 8bit BNB quantized optimizer will use only (2*3) 6GB if all optimizer states are quantized.\n\n### Adafactor\n\nAdafactor doesn't store rolling averages for each element in weight matrices. Instead, it keeps aggregated information \n(sums of rolling averages row- and column-wise), significantly reducing its footprint. However, compared to Adam, \nAdafactor may have slower convergence in certain cases."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 73b9a327-f656-4aa3-a338-0785c16d6b04
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_train_gpu_one", "title": "Methods and tools for efficient training on a single GPU", "tokens": 7716, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"73b9a327-f656-4aa3-a338-0785c16d6b04\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"7a488fe5-6358-4f8d-8e94-daa390cebae2\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f4a1199f6734143a23fa61a74b0292b4dc919543135f61bdce1e193e695c4196\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"e01ef5fc-a15f-49e7-a8c6-08a97bc3a215\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"c2f23574e66f817044add77084db00decac9de5c09583df22bd1f5cc5dd6c485\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"cda0c279-85be-4d88-b033-fd035dd08405\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"2b16bfcf163efe9d449daea34e45248b6aec8a573e35473da48374c8fdff8925\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 15145, \"end_char_idx\": 18226, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "ref_doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "chroma:document": "For example if you have [NVIDIA/apex](https://github.com/NVIDIA/apex) installed for NVIDIA GPUs, or [ROCmSoftwarePlatform/apex](https://github.com/ROCmSoftwarePlatform/apex) for AMD GPUs, `adamw_apex_fused` will give you the\nfastest training experience among all supported AdamW optimizers.\n\n[`Trainer`] integrates a variety of optimizers that can be used out of box: `adamw_hf`, `adamw_torch`, `adamw_torch_fused`, \n`adamw_apex_fused`, `adamw_anyprecision`, `adafactor`, or `adamw_bnb_8bit`. More optimizers can be plugged in via a third-party implementation.\n\nLet's take a closer look at two alternatives to AdamW optimizer:\n1. `adafactor` which is available in [`Trainer`]\n2. `adamw_bnb_8bit` is also available in Trainer, but a third-party integration is provided below for demonstration.\n\nFor comparison, for a 3B-parameter model, like \u201cgoogle-t5/t5-3b\u201d: \n* A standard AdamW optimizer will need 24GB of GPU memory because it uses 8 bytes for each parameter (8*3 => 24GB)\n* Adafactor optimizer will need more than 12GB. It uses slightly more than 4 bytes for each parameter, so 4*3 and then some extra.\n* 8bit BNB quantized optimizer will use only (2*3) 6GB if all optimizer states are quantized.\n\n### Adafactor\n\nAdafactor doesn't store rolling averages for each element in weight matrices. Instead, it keeps aggregated information \n(sums of rolling averages row- and column-wise), significantly reducing its footprint. However, compared to Adam, \nAdafactor may have slower convergence in certain cases.\n\nYou can switch to Adafactor by setting `optim=\"adafactor\"` in [`TrainingArguments`]:\n\n```py\ntraining_args = TrainingArguments(per_device_train_batch_size=4, optim=\"adafactor\", **default_args)\n```\n\nCombined with other approaches (gradient accumulation, gradient checkpointing, and mixed precision training) \nyou can notice up to 3x improvement while maintaining the throughput! However, as mentioned before, the convergence of \nAdafactor can be worse than Adam. \n\n### 8-bit Adam\n\nInstead of aggregating optimizer states like Adafactor, 8-bit Adam keeps the full state and quantizes it. Quantization \nmeans that it stores the state with lower precision and dequantizes it only for the optimization. This is similar to the \nidea behind mixed precision training.\n\nTo use `adamw_bnb_8bit`, you simply need to set `optim=\"adamw_bnb_8bit\"` in [`TrainingArguments`]:\n\n```py\ntraining_args = TrainingArguments(per_device_train_batch_size=4, optim=\"adamw_bnb_8bit\", **default_args)\n```\n\nHowever, we can also use a third-party implementation of the 8-bit optimizer for demonstration purposes to see how that can be integrated.\n\nFirst, follow the installation guide in the GitHub [repo](https://github.com/TimDettmers/bitsandbytes) to install the `bitsandbytes` library \nthat implements the 8-bit Adam optimizer.\n\nNext you need to initialize the optimizer. This involves two steps: \n* First, group the model's parameters into two groups - one where weight decay should be applied, and the other one where it should not. Usually, biases and layer norm parameters are not weight decayed."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: cda0c279-85be-4d88-b033-fd035dd08405
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_train_gpu_one", "title": "Methods and tools for efficient training on a single GPU", "tokens": 7716, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"cda0c279-85be-4d88-b033-fd035dd08405\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"7a488fe5-6358-4f8d-8e94-daa390cebae2\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f4a1199f6734143a23fa61a74b0292b4dc919543135f61bdce1e193e695c4196\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"73b9a327-f656-4aa3-a338-0785c16d6b04\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"0de4b966e5ea07a4c6f7b2c193a2e4f31c73ee961f8f264212076c31c2d88f66\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"cfea5b91-344a-4987-9829-48a33babaeee\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"b6819d4428a3491e37fd7e89bffdfcedb3ceda16e2c099ab3eb2d29af1aa8062\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 16569, \"end_char_idx\": 19786, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "ref_doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "chroma:document": "However, compared to Adam, \nAdafactor may have slower convergence in certain cases.\n\nYou can switch to Adafactor by setting `optim=\"adafactor\"` in [`TrainingArguments`]:\n\n```py\ntraining_args = TrainingArguments(per_device_train_batch_size=4, optim=\"adafactor\", **default_args)\n```\n\nCombined with other approaches (gradient accumulation, gradient checkpointing, and mixed precision training) \nyou can notice up to 3x improvement while maintaining the throughput! However, as mentioned before, the convergence of \nAdafactor can be worse than Adam. \n\n### 8-bit Adam\n\nInstead of aggregating optimizer states like Adafactor, 8-bit Adam keeps the full state and quantizes it. Quantization \nmeans that it stores the state with lower precision and dequantizes it only for the optimization. This is similar to the \nidea behind mixed precision training.\n\nTo use `adamw_bnb_8bit`, you simply need to set `optim=\"adamw_bnb_8bit\"` in [`TrainingArguments`]:\n\n```py\ntraining_args = TrainingArguments(per_device_train_batch_size=4, optim=\"adamw_bnb_8bit\", **default_args)\n```\n\nHowever, we can also use a third-party implementation of the 8-bit optimizer for demonstration purposes to see how that can be integrated.\n\nFirst, follow the installation guide in the GitHub [repo](https://github.com/TimDettmers/bitsandbytes) to install the `bitsandbytes` library \nthat implements the 8-bit Adam optimizer.\n\nNext you need to initialize the optimizer. This involves two steps: \n* First, group the model's parameters into two groups - one where weight decay should be applied, and the other one where it should not. Usually, biases and layer norm parameters are not weight decayed. \n* Then do some argument housekeeping to use the same parameters as the previously used AdamW optimizer.\n\n```py\nimport bitsandbytes as bnb\nfrom torch import nn\nfrom transformers.trainer_pt_utils import get_parameter_names\n\ntraining_args = TrainingArguments(per_device_train_batch_size=4, **default_args)\n\ndecay_parameters = get_parameter_names(model, [nn.LayerNorm])\ndecay_parameters = [name for name in decay_parameters if \"bias\" not in name]\noptimizer_grouped_parameters = [\n    {\n        \"params\": [p for n, p in model.named_parameters() if n in decay_parameters],\n        \"weight_decay\": training_args.weight_decay,\n    },\n    {\n        \"params\": [p for n, p in model.named_parameters() if n not in decay_parameters],\n        \"weight_decay\": 0.0,\n    },\n]\n\noptimizer_kwargs = {\n    \"betas\": (training_args.adam_beta1, training_args.adam_beta2),\n    \"eps\": training_args.adam_epsilon,\n}\noptimizer_kwargs[\"lr\"] = training_args.learning_rate\nadam_bnb_optim = bnb.optim.Adam8bit(\n    optimizer_grouped_parameters,\n    betas=(training_args.adam_beta1, training_args.adam_beta2),\n    eps=training_args.adam_epsilon,\n    lr=training_args.learning_rate,\n)\n```\n\nFinally, pass the custom optimizer as an argument to the `Trainer`:\n\n```py\ntrainer = Trainer(model=model, args=training_args, train_dataset=ds, optimizers=(adam_bnb_optim, None))\n```\n\nCombined with other approaches (gradient accumulation, gradient checkpointing, and mixed precision training), \nyou can expect to get about a 3x memory improvement and even slightly higher throughput as using Adafactor."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: cfea5b91-344a-4987-9829-48a33babaeee
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_train_gpu_one", "title": "Methods and tools for efficient training on a single GPU", "tokens": 7716, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"cfea5b91-344a-4987-9829-48a33babaeee\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"7a488fe5-6358-4f8d-8e94-daa390cebae2\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f4a1199f6734143a23fa61a74b0292b4dc919543135f61bdce1e193e695c4196\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"cda0c279-85be-4d88-b033-fd035dd08405\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"867185769a723146e497c74818a853319704e6b0b6fb8de9956f8efebd9330f4\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"39f843f2-a107-4d28-85fe-0a4833775663\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"d2c34d9f7fc4235098958035c9c54c0fd03d75043ca2f9e6a6c3eccbd3d34ad4\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 18161, \"end_char_idx\": 21625, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "ref_doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "chroma:document": "Usually, biases and layer norm parameters are not weight decayed. \n* Then do some argument housekeeping to use the same parameters as the previously used AdamW optimizer.\n\n```py\nimport bitsandbytes as bnb\nfrom torch import nn\nfrom transformers.trainer_pt_utils import get_parameter_names\n\ntraining_args = TrainingArguments(per_device_train_batch_size=4, **default_args)\n\ndecay_parameters = get_parameter_names(model, [nn.LayerNorm])\ndecay_parameters = [name for name in decay_parameters if \"bias\" not in name]\noptimizer_grouped_parameters = [\n    {\n        \"params\": [p for n, p in model.named_parameters() if n in decay_parameters],\n        \"weight_decay\": training_args.weight_decay,\n    },\n    {\n        \"params\": [p for n, p in model.named_parameters() if n not in decay_parameters],\n        \"weight_decay\": 0.0,\n    },\n]\n\noptimizer_kwargs = {\n    \"betas\": (training_args.adam_beta1, training_args.adam_beta2),\n    \"eps\": training_args.adam_epsilon,\n}\noptimizer_kwargs[\"lr\"] = training_args.learning_rate\nadam_bnb_optim = bnb.optim.Adam8bit(\n    optimizer_grouped_parameters,\n    betas=(training_args.adam_beta1, training_args.adam_beta2),\n    eps=training_args.adam_epsilon,\n    lr=training_args.learning_rate,\n)\n```\n\nFinally, pass the custom optimizer as an argument to the `Trainer`:\n\n```py\ntrainer = Trainer(model=model, args=training_args, train_dataset=ds, optimizers=(adam_bnb_optim, None))\n```\n\nCombined with other approaches (gradient accumulation, gradient checkpointing, and mixed precision training), \nyou can expect to get about a 3x memory improvement and even slightly higher throughput as using Adafactor. \n\n### multi_tensor\n\npytorch-nightly introduced `torch.optim._multi_tensor` which should significantly speed up the optimizers for situations \nwith lots of small feature tensors. It should eventually become the default, but if you want to experiment with it sooner, take a look at this GitHub [issue](https://github.com/huggingface/transformers/issues/9965).\n\n## Data preloading\n\nOne of the important requirements to reach great training speed is the ability to feed the GPU at the maximum speed it \ncan handle. By default, everything happens in the main process, and it might not be able to read the data from disk fast \nenough, and thus create a bottleneck, leading to GPU under-utilization. Configure the following arguments to reduce the bottleneck:\n\n- `DataLoader(pin_memory=True, ...)` - ensures the data gets preloaded into the pinned memory on CPU and typically leads to much faster transfers from CPU to GPU memory.\n- `DataLoader(num_workers=4, ...)` - spawn several workers to preload data faster. During training, watch the GPU utilization stats; if it's far from 100%, experiment with increasing the number of workers. Of course, the problem could be elsewhere, so many workers won't necessarily lead to better performance.\n\nWhen using [`Trainer`], the corresponding [`TrainingArguments`] are: `dataloader_pin_memory` (`True` by default), and `dataloader_num_workers` (defaults to `0`).\n\n## DeepSpeed ZeRO\n\nDeepSpeed is an open-source deep learning optimization library that is integrated with \ud83e\udd17 Transformers and \ud83e\udd17 Accelerate.\nIt provides a wide range of features and optimizations designed to improve the efficiency and scalability of large-scale \ndeep learning training.\n\nIf your model fits onto a single GPU and you have enough space to fit a small batch size, you don't need to use DeepSpeed\nas it'll only slow things down."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 39f843f2-a107-4d28-85fe-0a4833775663
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_train_gpu_one", "title": "Methods and tools for efficient training on a single GPU", "tokens": 7716, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"39f843f2-a107-4d28-85fe-0a4833775663\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"7a488fe5-6358-4f8d-8e94-daa390cebae2\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f4a1199f6734143a23fa61a74b0292b4dc919543135f61bdce1e193e695c4196\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"cfea5b91-344a-4987-9829-48a33babaeee\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"0795a2b7a461aef9efd6aa0f189ad4b1b7210a613bcd7cc881f5f75cd427391e\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"58bc6f14-a9fe-47c5-801c-4a42e0be9443\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"ea54760135da62d0f528915ec57b120139cd3e480751c7e3ad3f1c4d67ce63ee\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 19789, \"end_char_idx\": 23266, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "ref_doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "chroma:document": "### multi_tensor\n\npytorch-nightly introduced `torch.optim._multi_tensor` which should significantly speed up the optimizers for situations \nwith lots of small feature tensors. It should eventually become the default, but if you want to experiment with it sooner, take a look at this GitHub [issue](https://github.com/huggingface/transformers/issues/9965).\n\n## Data preloading\n\nOne of the important requirements to reach great training speed is the ability to feed the GPU at the maximum speed it \ncan handle. By default, everything happens in the main process, and it might not be able to read the data from disk fast \nenough, and thus create a bottleneck, leading to GPU under-utilization. Configure the following arguments to reduce the bottleneck:\n\n- `DataLoader(pin_memory=True, ...)` - ensures the data gets preloaded into the pinned memory on CPU and typically leads to much faster transfers from CPU to GPU memory.\n- `DataLoader(num_workers=4, ...)` - spawn several workers to preload data faster. During training, watch the GPU utilization stats; if it's far from 100%, experiment with increasing the number of workers. Of course, the problem could be elsewhere, so many workers won't necessarily lead to better performance.\n\nWhen using [`Trainer`], the corresponding [`TrainingArguments`] are: `dataloader_pin_memory` (`True` by default), and `dataloader_num_workers` (defaults to `0`).\n\n## DeepSpeed ZeRO\n\nDeepSpeed is an open-source deep learning optimization library that is integrated with \ud83e\udd17 Transformers and \ud83e\udd17 Accelerate.\nIt provides a wide range of features and optimizations designed to improve the efficiency and scalability of large-scale \ndeep learning training.\n\nIf your model fits onto a single GPU and you have enough space to fit a small batch size, you don't need to use DeepSpeed\nas it'll only slow things down. However, if the model doesn't fit onto a single GPU or you can't fit a small batch, you can \nleverage DeepSpeed ZeRO + CPU Offload, or NVMe Offload for much larger models. In this case, you need to separately\n[install the library](main_classes/deepspeed#installation), then follow one of the guides to create a configuration file \nand launch DeepSpeed: \n \n* For an in-depth guide on DeepSpeed integration with [`Trainer`], review [the corresponding documentation](main_classes/deepspeed), specifically the \n[section for a single GPU](main_classes/deepspeed#deployment-with-one-gpu). Some adjustments are required to use DeepSpeed in a notebook; please take a look at the [corresponding guide](main_classes/deepspeed#deployment-in-notebooks).\n* If you prefer to use \ud83e\udd17 Accelerate, refer to [\ud83e\udd17 Accelerate DeepSpeed guide](https://huggingface.co/docs/accelerate/en/usage_guides/deepspeed).\n\n## Using torch.compile\n\nPyTorch 2.0 introduced a new compile function that doesn't require any modification to existing PyTorch code but can \noptimize your code by adding a single line of code: `model = torch.compile(model)`.\n\nIf using [`Trainer`], you only need `to` pass the `torch_compile` option in the [`TrainingArguments`]: \n\n```python\ntraining_args = TrainingArguments(torch_compile=True, **default_args)\n```\n\n`torch.compile` uses Python's frame evaluation API to automatically create a graph from existing PyTorch programs. After \ncapturing the graph, different backends can be deployed to lower the graph to an optimized engine. \nYou can find more details and benchmarks in [PyTorch documentation](https://pytorch.org/get-started/pytorch-2.0/)."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 58bc6f14-a9fe-47c5-801c-4a42e0be9443
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_train_gpu_one", "title": "Methods and tools for efficient training on a single GPU", "tokens": 7716, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"58bc6f14-a9fe-47c5-801c-4a42e0be9443\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"7a488fe5-6358-4f8d-8e94-daa390cebae2\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f4a1199f6734143a23fa61a74b0292b4dc919543135f61bdce1e193e695c4196\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"39f843f2-a107-4d28-85fe-0a4833775663\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8bef8b7c7f10c387163f5db918068b2175903a1d23eee374c1a50e218808e586\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"5cc13052-c3bc-4b72-b5f3-0a7e9d302cb6\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"60e50f119917ab4c312c0b4a8936ac35b4b376f68ea1811fd22322a4238cfe77\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 21626, \"end_char_idx\": 24671, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "ref_doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "chroma:document": "However, if the model doesn't fit onto a single GPU or you can't fit a small batch, you can \nleverage DeepSpeed ZeRO + CPU Offload, or NVMe Offload for much larger models. In this case, you need to separately\n[install the library](main_classes/deepspeed#installation), then follow one of the guides to create a configuration file \nand launch DeepSpeed: \n \n* For an in-depth guide on DeepSpeed integration with [`Trainer`], review [the corresponding documentation](main_classes/deepspeed), specifically the \n[section for a single GPU](main_classes/deepspeed#deployment-with-one-gpu). Some adjustments are required to use DeepSpeed in a notebook; please take a look at the [corresponding guide](main_classes/deepspeed#deployment-in-notebooks).\n* If you prefer to use \ud83e\udd17 Accelerate, refer to [\ud83e\udd17 Accelerate DeepSpeed guide](https://huggingface.co/docs/accelerate/en/usage_guides/deepspeed).\n\n## Using torch.compile\n\nPyTorch 2.0 introduced a new compile function that doesn't require any modification to existing PyTorch code but can \noptimize your code by adding a single line of code: `model = torch.compile(model)`.\n\nIf using [`Trainer`], you only need `to` pass the `torch_compile` option in the [`TrainingArguments`]: \n\n```python\ntraining_args = TrainingArguments(torch_compile=True, **default_args)\n```\n\n`torch.compile` uses Python's frame evaluation API to automatically create a graph from existing PyTorch programs. After \ncapturing the graph, different backends can be deployed to lower the graph to an optimized engine. \nYou can find more details and benchmarks in [PyTorch documentation](https://pytorch.org/get-started/pytorch-2.0/).\n\n`torch.compile` has a growing list of backends, which can be found in by calling `torchdynamo.list_backends()`, each of which with its optional dependencies.\n\nChoose which backend to use by specifying it via `torch_compile_backend` in the [`TrainingArguments`].  Some of the most commonly used backends are:\n\n**Debugging backends**:\n* `dynamo.optimize(\"eager\")` - Uses PyTorch to run the extracted GraphModule. This is quite useful in debugging TorchDynamo issues.\n* `dynamo.optimize(\"aot_eager\")` - Uses AotAutograd with no compiler, i.e, just using PyTorch eager for the AotAutograd's extracted forward and backward graphs. This is useful for debugging, and unlikely to give speedups.\n\n**Training & inference backends**:\n* `dynamo.optimize(\"inductor\")` - Uses TorchInductor backend with AotAutograd and cudagraphs by leveraging codegened Triton kernels  [Read more](https://dev-discuss.pytorch.org/t/torchinductor-a-pytorch-native-compiler-with-define-by-run-ir-and-symbolic-shapes/747)\n* `dynamo.optimize(\"nvfuser\")` -  nvFuser with TorchScript. [Read more](https://dev-discuss.pytorch.org/t/tracing-with-primitives-update-1-nvfuser-and-its-primitives/593)\n* `dynamo.optimize(\"aot_nvfuser\")` -  nvFuser with AotAutograd. [Read more](https://dev-discuss.pytorch.org/t/tracing-with-primitives-update-1-nvfuser-and-its-primitives/593)\n* `dynamo.optimize(\"aot_cudagraphs\")` - cudagraphs with AotAutograd."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 5cc13052-c3bc-4b72-b5f3-0a7e9d302cb6
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_train_gpu_one", "title": "Methods and tools for efficient training on a single GPU", "tokens": 7716, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"5cc13052-c3bc-4b72-b5f3-0a7e9d302cb6\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"7a488fe5-6358-4f8d-8e94-daa390cebae2\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f4a1199f6734143a23fa61a74b0292b4dc919543135f61bdce1e193e695c4196\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"58bc6f14-a9fe-47c5-801c-4a42e0be9443\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"20f4a91b07fc6961f2f362b506ea632fed596aa20940a048a35ac6ddc44e84f2\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"16435b1c-08cc-43bd-b2d8-a25a6db89bae\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"29337587d7fc986bff5cb8345aaca667658278785ffe84c1e075a328b736fd5d\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 23268, \"end_char_idx\": 26002, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "ref_doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "chroma:document": "`torch.compile` has a growing list of backends, which can be found in by calling `torchdynamo.list_backends()`, each of which with its optional dependencies.\n\nChoose which backend to use by specifying it via `torch_compile_backend` in the [`TrainingArguments`].  Some of the most commonly used backends are:\n\n**Debugging backends**:\n* `dynamo.optimize(\"eager\")` - Uses PyTorch to run the extracted GraphModule. This is quite useful in debugging TorchDynamo issues.\n* `dynamo.optimize(\"aot_eager\")` - Uses AotAutograd with no compiler, i.e, just using PyTorch eager for the AotAutograd's extracted forward and backward graphs. This is useful for debugging, and unlikely to give speedups.\n\n**Training & inference backends**:\n* `dynamo.optimize(\"inductor\")` - Uses TorchInductor backend with AotAutograd and cudagraphs by leveraging codegened Triton kernels  [Read more](https://dev-discuss.pytorch.org/t/torchinductor-a-pytorch-native-compiler-with-define-by-run-ir-and-symbolic-shapes/747)\n* `dynamo.optimize(\"nvfuser\")` -  nvFuser with TorchScript. [Read more](https://dev-discuss.pytorch.org/t/tracing-with-primitives-update-1-nvfuser-and-its-primitives/593)\n* `dynamo.optimize(\"aot_nvfuser\")` -  nvFuser with AotAutograd. [Read more](https://dev-discuss.pytorch.org/t/tracing-with-primitives-update-1-nvfuser-and-its-primitives/593)\n* `dynamo.optimize(\"aot_cudagraphs\")` - cudagraphs with AotAutograd. [Read more](https://github.com/pytorch/torchdynamo/pull/757)\n\n**Inference-only backend**s:\n* `dynamo.optimize(\"ofi\")` -  Uses Torchscript optimize_for_inference.  [Read more](https://pytorch.org/docs/stable/generated/torch.jit.optimize_for_inference.html)\n* `dynamo.optimize(\"fx2trt\")` -  Uses NVIDIA TensorRT for inference optimizations.  [Read more](https://pytorch.org/TensorRT/tutorials/getting_started_with_fx_path.html)\n* `dynamo.optimize(\"onnxrt\")` -  Uses ONNXRT for inference on CPU/GPU.  [Read more](https://onnxruntime.ai/)\n* `dynamo.optimize(\"ipex\")` -  Uses IPEX for inference on CPU.  [Read more](https://github.com/intel/intel-extension-for-pytorch)\n\nFor an example of using `torch.compile` with \ud83e\udd17 Transformers, check out this [blog post on fine-tuning a BERT model for Text Classification using the newest PyTorch 2.0 features](https://www.philschmid.de/getting-started-pytorch-2-0-transformers)\n\n## Using \ud83e\udd17 PEFT\n\n[Parameter-Efficient Fine Tuning (PEFT)](https://huggingface.co/blog/peft) methods freeze the pretrained model parameters during fine-tuning and add a small number of trainable parameters (the adapters) on top of it.\n\nAs a result the [memory associated to the optimizer states and gradients](https://huggingface.co/docs/transformers/model_memory_anatomy#anatomy-of-models-memory) are greatly reduced."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 16435b1c-08cc-43bd-b2d8-a25a6db89bae
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_train_gpu_one", "title": "Methods and tools for efficient training on a single GPU", "tokens": 7716, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"16435b1c-08cc-43bd-b2d8-a25a6db89bae\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"7a488fe5-6358-4f8d-8e94-daa390cebae2\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f4a1199f6734143a23fa61a74b0292b4dc919543135f61bdce1e193e695c4196\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"5cc13052-c3bc-4b72-b5f3-0a7e9d302cb6\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"c339ce2c6460ee94f2972582b759f9187a8ae72ff7713dd1740ed08a51d5cafe\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"16b62c0b-1b29-4d14-b24b-de8a7ac2bdc5\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"a870ec7023092bed4b349be6dea9e3eaa33de491146a52856b3e2a69fe6efb3f\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 24672, \"end_char_idx\": 27057, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "ref_doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "chroma:document": "[Read more](https://github.com/pytorch/torchdynamo/pull/757)\n\n**Inference-only backend**s:\n* `dynamo.optimize(\"ofi\")` -  Uses Torchscript optimize_for_inference.  [Read more](https://pytorch.org/docs/stable/generated/torch.jit.optimize_for_inference.html)\n* `dynamo.optimize(\"fx2trt\")` -  Uses NVIDIA TensorRT for inference optimizations.  [Read more](https://pytorch.org/TensorRT/tutorials/getting_started_with_fx_path.html)\n* `dynamo.optimize(\"onnxrt\")` -  Uses ONNXRT for inference on CPU/GPU.  [Read more](https://onnxruntime.ai/)\n* `dynamo.optimize(\"ipex\")` -  Uses IPEX for inference on CPU.  [Read more](https://github.com/intel/intel-extension-for-pytorch)\n\nFor an example of using `torch.compile` with \ud83e\udd17 Transformers, check out this [blog post on fine-tuning a BERT model for Text Classification using the newest PyTorch 2.0 features](https://www.philschmid.de/getting-started-pytorch-2-0-transformers)\n\n## Using \ud83e\udd17 PEFT\n\n[Parameter-Efficient Fine Tuning (PEFT)](https://huggingface.co/blog/peft) methods freeze the pretrained model parameters during fine-tuning and add a small number of trainable parameters (the adapters) on top of it.\n\nAs a result the [memory associated to the optimizer states and gradients](https://huggingface.co/docs/transformers/model_memory_anatomy#anatomy-of-models-memory) are greatly reduced.\n\nFor example with a vanilla AdamW, the memory requirement for the optimizer state would be:\n* fp32 copy of parameters: 4 bytes/param\n* Momentum: 4 bytes/param\n* Variance: 4 bytes/param\n\nSuppose a model with 7B parameters and 200 millions parameters injected with [Low Rank Adapters](https://huggingface.co/docs/peft/conceptual_guides/lora).\n\nThe memory requirement for the optimizer state of the plain model would be 12 * 7 = 84 GB (assuming 7B trainable parameters).\n\nAdding Lora increases slightly the memory associated to the model weights and substantially decreases memory requirement for the optimizer state to 12 * 0.2 = 2.4GB.\n\nRead more about PEFT and its detailed usage in [the PEFT documentation](https://huggingface.co/docs/peft/) or [PEFT repository](https://github.com/huggingface/peft).\n\n## Using \ud83e\udd17 Accelerate\n\nWith [\ud83e\udd17 Accelerate](https://huggingface.co/docs/accelerate/index) you can use the above methods while gaining full \ncontrol over the training loop and can essentially write the loop in pure PyTorch with some minor modifications."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 16b62c0b-1b29-4d14-b24b-de8a7ac2bdc5
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_train_gpu_one", "title": "Methods and tools for efficient training on a single GPU", "tokens": 7716, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"16b62c0b-1b29-4d14-b24b-de8a7ac2bdc5\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"7a488fe5-6358-4f8d-8e94-daa390cebae2\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f4a1199f6734143a23fa61a74b0292b4dc919543135f61bdce1e193e695c4196\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"16435b1c-08cc-43bd-b2d8-a25a6db89bae\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"d1a10e175b4b787eebec746b077edd7abc855e8d46ec8ac446c0820ec020c3fe\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"4bea7c0a-e664-4a6d-9768-77680d60a59c\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"ee7f26c7057418433d67e084828b7100097c0bf844c6c1e2ab0e11da48999ed7\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 25820, \"end_char_idx\": 29183, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "ref_doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "chroma:document": "As a result the [memory associated to the optimizer states and gradients](https://huggingface.co/docs/transformers/model_memory_anatomy#anatomy-of-models-memory) are greatly reduced.\n\nFor example with a vanilla AdamW, the memory requirement for the optimizer state would be:\n* fp32 copy of parameters: 4 bytes/param\n* Momentum: 4 bytes/param\n* Variance: 4 bytes/param\n\nSuppose a model with 7B parameters and 200 millions parameters injected with [Low Rank Adapters](https://huggingface.co/docs/peft/conceptual_guides/lora).\n\nThe memory requirement for the optimizer state of the plain model would be 12 * 7 = 84 GB (assuming 7B trainable parameters).\n\nAdding Lora increases slightly the memory associated to the model weights and substantially decreases memory requirement for the optimizer state to 12 * 0.2 = 2.4GB.\n\nRead more about PEFT and its detailed usage in [the PEFT documentation](https://huggingface.co/docs/peft/) or [PEFT repository](https://github.com/huggingface/peft).\n\n## Using \ud83e\udd17 Accelerate\n\nWith [\ud83e\udd17 Accelerate](https://huggingface.co/docs/accelerate/index) you can use the above methods while gaining full \ncontrol over the training loop and can essentially write the loop in pure PyTorch with some minor modifications. \n\nSuppose you have combined the methods in the [`TrainingArguments`] like so:\n\n```py\ntraining_args = TrainingArguments(\n    per_device_train_batch_size=1,\n    gradient_accumulation_steps=4,\n    gradient_checkpointing=True,\n    fp16=True,\n    **default_args,\n)\n```\n\nThe full example training loop with \ud83e\udd17 Accelerate is only a handful of lines of code long:\n\n```py\nfrom accelerate import Accelerator\nfrom torch.utils.data.dataloader import DataLoader\n\ndataloader = DataLoader(ds, batch_size=training_args.per_device_train_batch_size)\n\nif training_args.gradient_checkpointing:\n    model.gradient_checkpointing_enable()\n\naccelerator = Accelerator(fp16=training_args.fp16)\nmodel, optimizer, dataloader = accelerator.prepare(model, adam_bnb_optim, dataloader)\n\nmodel.train()\nfor step, batch in enumerate(dataloader, start=1):\n    loss = model(**batch).loss\n    loss = loss / training_args.gradient_accumulation_steps\n    accelerator.backward(loss)\n    if step % training_args.gradient_accumulation_steps == 0:\n        optimizer.step()\n        optimizer.zero_grad()\n```\n\nFirst we wrap the dataset in a [`DataLoader`](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader). \nThen we can enable gradient checkpointing by calling the model's [`~PreTrainedModel.gradient_checkpointing_enable`] method. \nWhen we initialize the [`Accelerator`](https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator) \nwe can specify if we want to use mixed precision training and it will take care of it for us in the [`prepare`] call. \nDuring the [`prepare`](https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.prepare) \ncall the dataloader will also be distributed across workers should we use multiple GPUs. We use the same [8-bit optimizer](#8-bit-adam) from the earlier example.\n\nFinally, we can add the main training loop. Note that the `backward` call is handled by \ud83e\udd17 Accelerate. We can also see\nhow gradient accumulation works: we normalize the loss, so we get the average at the end of accumulation and once we have \nenough steps we run the optimization."}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: 4bea7c0a-e664-4a6d-9768-77680d60a59c
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_train_gpu_one", "title": "Methods and tools for efficient training on a single GPU", "tokens": 7716, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"4bea7c0a-e664-4a6d-9768-77680d60a59c\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"7a488fe5-6358-4f8d-8e94-daa390cebae2\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f4a1199f6734143a23fa61a74b0292b4dc919543135f61bdce1e193e695c4196\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"16b62c0b-1b29-4d14-b24b-de8a7ac2bdc5\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"ed6ad165a90d4c0e6f7c4c0e96a43ccb6c61e25dfd239cf83095f87cdc1d21de\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"b3d8bd32-c159-4016-b59b-1130b708a9e6\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"6dd543a9bd13a10453af50206de91af489c86ac8bbb09063ef7506921b74210d\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 28240, \"end_char_idx\": 31559, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "ref_doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "chroma:document": "Then we can enable gradient checkpointing by calling the model's [`~PreTrainedModel.gradient_checkpointing_enable`] method. \nWhen we initialize the [`Accelerator`](https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator) \nwe can specify if we want to use mixed precision training and it will take care of it for us in the [`prepare`] call. \nDuring the [`prepare`](https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.prepare) \ncall the dataloader will also be distributed across workers should we use multiple GPUs. We use the same [8-bit optimizer](#8-bit-adam) from the earlier example.\n\nFinally, we can add the main training loop. Note that the `backward` call is handled by \ud83e\udd17 Accelerate. We can also see\nhow gradient accumulation works: we normalize the loss, so we get the average at the end of accumulation and once we have \nenough steps we run the optimization. \n\nImplementing these optimization techniques with \ud83e\udd17 Accelerate only takes a handful of lines of code and comes with the \nbenefit of more flexibility in the training loop. For a full documentation of all features have a look at the \n[Accelerate documentation](https://huggingface.co/docs/accelerate/index).\n\n\n## Efficient Software Prebuilds\n\nPyTorch's [pip and conda builds](https://pytorch.org/get-started/locally/#start-locally) come prebuilt with the cuda toolkit \nwhich is enough to run PyTorch, but it is insufficient if you need to build cuda extensions.\n\nAt times, additional efforts may be required to pre-build some components. For instance, if you're using libraries like `apex` that \ndon't come pre-compiled. In other situations figuring out how to install the right cuda toolkit system-wide can be complicated. \nTo address these scenarios PyTorch and NVIDIA released a new version of NGC docker container which already comes with \neverything prebuilt. You just need to install your programs on it, and it will run out of the box.\n\nThis approach is also useful if you want to tweak the pytorch source and/or make a new customized build.\nTo find the docker image version you want start [with PyTorch release notes](https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/), \nchoose one of the latest monthly releases. Go into the release's notes for the desired release, check that the environment's \ncomponents are matching your needs (including NVIDIA Driver requirements!) and then at the very top of that document go \nto the corresponding NGC page. If for some reason you get lost, here is [the index of all PyTorch NGC images](https://ngc.nvidia.com/catalog/containers/nvidia:pytorch).\n\nNext follow the instructions to download and deploy the docker image.\n\n## Mixture of Experts\n\nSome recent papers reported a 4-5x training speedup and a faster inference by integrating\nMixture of Experts (MoE) into the Transformer models.\n\nSince it has been discovered that more parameters lead to better performance, this technique allows to increase the \nnumber of parameters by an order of magnitude without increasing training costs.\n\nIn this approach every other FFN layer is replaced with a MoE Layer which consists of many experts, with a gated function \nthat trains each expert in a balanced way depending on the input token's position in a sequence.\n\n!"}


created_at: 2024-07-28 18:57:50
topic: persistent://default/default/5523a7e1-1ad4-449b-b059-70d441f3d0d1
id: b3d8bd32-c159-4016-b59b-1130b708a9e6
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_train_gpu_one", "title": "Methods and tools for efficient training on a single GPU", "tokens": 7716, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"b3d8bd32-c159-4016-b59b-1130b708a9e6\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"excluded_embed_metadata_keys\": [\"url\", \"tokens\", \"retrieve_doc\", \"source\"], \"excluded_llm_metadata_keys\": [\"title\", \"tokens\", \"retrieve_doc\", \"source\"], \"relationships\": {\"1\": {\"node_id\": \"7a488fe5-6358-4f8d-8e94-daa390cebae2\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f4a1199f6734143a23fa61a74b0292b4dc919543135f61bdce1e193e695c4196\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"4bea7c0a-e664-4a6d-9768-77680d60a59c\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_gpu_one\", \"title\": \"Methods and tools for efficient training on a single GPU\", \"tokens\": 7716, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"708fa0d836cfa698919509d6eca0915033d63a9ec393c839f584d067cb263011\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"0a1435b5-3b2b-4f13-95ec-97169865710c\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"fad7fc434cf82aed64403587dcfba7a85f85afd4baaf54269dc232e446980511\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 29745, \"end_char_idx\": 32427, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "ref_doc_id": "7a488fe5-6358-4f8d-8e94-daa390cebae2", "chroma:document": "At times, additional efforts may be required to pre-build some components. For instance, if you're using libraries like `apex` that \ndon't come pre-compiled. In other situations figuring out how to install the right cuda toolkit system-wide can be complicated. \nTo address these scenarios PyTorch and NVIDIA released a new version of NGC docker container which already comes with \neverything prebuilt. You just need to install your programs on it, and it will run out of the box.\n\nThis approach is also useful if you want to tweak the pytorch source and/or make a new customized build.\nTo find the docker image version you want start [with PyTorch release notes](https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/), \nchoose one of the latest monthly releases. Go into the release's notes for the desired release, check that the environment's \ncomponents are matching your needs (including NVIDIA Driver requirements!) and then at the very top of that document go \nto the corresponding NGC page. If for some reason you get lost, here is [the index of all PyTorch NGC images](https://ngc.nvidia.com/catalog/containers/nvidia:pytorch).\n\nNext follow the instructions to download and deploy the docker image.\n\n## Mixture of Experts\n\nSome recent papers reported a 4-5x training speedup and a faster inference by integrating\nMixture of Experts (MoE) into the Transformer models.\n\nSince it has been discovered that more parameters lead to better performance, this technique allows to increase the \nnumber of parameters by an order of magnitude without increasing training costs.\n\nIn this approach every other FFN layer is replaced with a MoE Layer which consists of many experts, with a gated function \nthat trains each expert in a balanced way depending on the input token's position in a sequence.\n\n![MoE Transformer 2x block](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/perf-moe-transformer.png)\n\n(source: [GLAM](https://ai.googleblog.com/2021/12/more-efficient-in-context-learning-with.html))\n\nYou can find exhaustive details and comparison tables in the papers listed at the end of this section.\n\nThe main drawback of this approach is that it requires staggering amounts of GPU memory - almost an order of magnitude \nlarger than its dense equivalent. Various distillation and approaches are proposed to how to overcome the much higher memory requirements.\n\nThere is direct trade-off though, you can use just a few experts with a 2-3x smaller base model instead of dozens or \nhundreds experts leading to a 5x smaller model and thus increase the training speed moderately while increasing the \nmemory requirements moderately as well."}


