# embeddings_queue

created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 3183ce95-d2af-4515-9058-db07e6e677f2
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"3183ce95-d2af-4515-9058-db07e6e677f2\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_summary\", \"title\": \"The Transformer model family\", \"tokens\": 4019, \"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\": \"fd6ed4d3-f1ca-498d-9c74-7a5d84385e19\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_summary\", \"title\": \"The Transformer model family\", \"tokens\": 4019, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8cead54d1f52c4d818c9192529c1a4c2c648d344c5ad270063818d92463dd149\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"262865c1-c6bb-4168-b7f5-bbc7d422e62c\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_summary\", \"title\": \"The Transformer model family\", \"tokens\": 4019, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"c0cce0cce87b96069189fba20bfdf7a0a0a3b158989ba883922efe9231b879d3\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"d937da67-2c92-437f-bbe8-f65939cfcb2e\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"f719a4cf576fe33f48ab4b7bfda7364116c1b23a66d7bd24715e3751f0c590b0\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 9018, \"end_char_idx\": 12070, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "fd6ed4d3-f1ca-498d-9c74-7a5d84385e19", "doc_id": "fd6ed4d3-f1ca-498d-9c74-7a5d84385e19", "ref_doc_id": "fd6ed4d3-f1ca-498d-9c74-7a5d84385e19", "chroma:document": "[XLNET](model_doc/xlnet) combines the best of both BERT and GPT-2's pretraining objectives by using a permutation language modeling objective (PLM) that allows it to learn bidirectionally.\n\nAfter GPT-2, language models grew even bigger and are now known as *large language models (LLMs)*. LLMs demonstrate few- or even zero-shot learning if pretrained on a large enough dataset. [GPT-J](model_doc/gptj) is an LLM with 6B parameters and trained on 400B tokens. GPT-J was followed by [OPT](model_doc/opt), a family of decoder-only models, the largest of which is 175B and trained on 180B tokens. [BLOOM](model_doc/bloom) was released around the same time, and the largest model in the family has 176B parameters and is trained on 366B tokens in 46 languages and 13 programming languages.\n\n### Encoder-decoder[[nlp-encoder-decoder]]\n\n[BART](model_doc/bart) keeps the original Transformer architecture, but it modifies the pretraining objective with *text infilling* corruption, where some text spans are replaced with a single `mask` token. The decoder predicts the uncorrupted tokens (future tokens are masked) and uses the encoder's hidden states to help it. [Pegasus](model_doc/pegasus) is similar to BART, but Pegasus masks entire sentences instead of text spans. In addition to masked language modeling, Pegasus is pretrained by gap sentence generation (GSG). The GSG objective masks whole sentences important to a document, replacing them with a `mask` token. The decoder must generate the output from the remaining sentences. [T5](model_doc/t5) is a more unique model that casts all NLP tasks into a text-to-text problem using specific prefixes. For example, the prefix `Summarize:` indicates a summarization task. T5 is pretrained by supervised (GLUE and SuperGLUE) training and self-supervised training (randomly sample and drop out 15% of tokens).\n\n## Audio\n\n<iframe style=\"border: 1px solid rgba(0, 0, 0, 0.1);\" width=\"1000\" height=\"450\" src=\"https://www.figma.com/embed?embed_host=share&url=https%3A%2F%2Fwww.figma.com%2Ffile%2Fvrchl8jDV9YwNVPWu2W0kK%2Fspeech-and-audio-model-timeline%3Fnode-id%3D0%253A1%26t%3DmM4H8pPMuK23rClL-1\" allowfullscreen></iframe>\n\n### Encoder[[audio-encoder]]\n\n[Wav2Vec2](model_doc/wav2vec2) uses a Transformer encoder to learn speech representations directly from raw audio waveforms. It is pretrained with a contrastive task to determine the true speech representation from a set of false ones. [HuBERT](model_doc/hubert) is similar to Wav2Vec2 but has a different training process. Target labels are created by a clustering step in which segments of similar audio are assigned to a cluster which becomes a hidden unit. The hidden unit is mapped to an embedding to make a prediction.\n\n### Encoder-decoder[[audio-encoder-decoder]]\n\n[Speech2Text](model_doc/speech_to_text) is a speech model designed for automatic speech recognition (ASR) and speech translation. The model accepts log mel-filter bank features extracted from the audio waveform and pretrained autoregressively to generate a transcript or translation."}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: d937da67-2c92-437f-bbe8-f65939cfcb2e
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"d937da67-2c92-437f-bbe8-f65939cfcb2e\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_summary\", \"title\": \"The Transformer model family\", \"tokens\": 4019, \"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\": \"fd6ed4d3-f1ca-498d-9c74-7a5d84385e19\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_summary\", \"title\": \"The Transformer model family\", \"tokens\": 4019, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8cead54d1f52c4d818c9192529c1a4c2c648d344c5ad270063818d92463dd149\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"3183ce95-d2af-4515-9058-db07e6e677f2\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_summary\", \"title\": \"The Transformer model family\", \"tokens\": 4019, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"a31a3c0a39c724e2981998c1a7a780fb2dfd53e9e15193fabb94c4963863658b\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"205c83f6-11bd-4b67-b231-dc27dc9f6eba\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"d5ebde93d67712f3bfdeb34e1d16fdedea36108cffd66feb9f6274c797da4022\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 10668, \"end_char_idx\": 13583, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "fd6ed4d3-f1ca-498d-9c74-7a5d84385e19", "doc_id": "fd6ed4d3-f1ca-498d-9c74-7a5d84385e19", "ref_doc_id": "fd6ed4d3-f1ca-498d-9c74-7a5d84385e19", "chroma:document": "For example, the prefix `Summarize:` indicates a summarization task. T5 is pretrained by supervised (GLUE and SuperGLUE) training and self-supervised training (randomly sample and drop out 15% of tokens).\n\n## Audio\n\n<iframe style=\"border: 1px solid rgba(0, 0, 0, 0.1);\" width=\"1000\" height=\"450\" src=\"https://www.figma.com/embed?embed_host=share&url=https%3A%2F%2Fwww.figma.com%2Ffile%2Fvrchl8jDV9YwNVPWu2W0kK%2Fspeech-and-audio-model-timeline%3Fnode-id%3D0%253A1%26t%3DmM4H8pPMuK23rClL-1\" allowfullscreen></iframe>\n\n### Encoder[[audio-encoder]]\n\n[Wav2Vec2](model_doc/wav2vec2) uses a Transformer encoder to learn speech representations directly from raw audio waveforms. It is pretrained with a contrastive task to determine the true speech representation from a set of false ones. [HuBERT](model_doc/hubert) is similar to Wav2Vec2 but has a different training process. Target labels are created by a clustering step in which segments of similar audio are assigned to a cluster which becomes a hidden unit. The hidden unit is mapped to an embedding to make a prediction.\n\n### Encoder-decoder[[audio-encoder-decoder]]\n\n[Speech2Text](model_doc/speech_to_text) is a speech model designed for automatic speech recognition (ASR) and speech translation. The model accepts log mel-filter bank features extracted from the audio waveform and pretrained autoregressively to generate a transcript or translation. [Whisper](model_doc/whisper) is also an ASR model, but unlike many other speech models, it is pretrained on a massive amount of \u2728 labeled \u2728 audio transcription data for zero-shot performance. A large chunk of the dataset also contains non-English languages, meaning Whisper can also be used for low-resource languages. Structurally, Whisper is similar to Speech2Text. The audio signal is converted to a log-mel spectrogram encoded by the encoder. The decoder generates the transcript autoregressively from the encoder's hidden states and the previous tokens.\n\n## Multimodal\n\n<iframe style=\"border: 1px solid rgba(0, 0, 0, 0.1);\" width=\"1000\" height=\"450\" src=\"https://www.figma.com/embed?embed_host=share&url=https%3A%2F%2Fwww.figma.com%2Ffile%2FcX125FQHXJS2gxeICiY93p%2Fmultimodal%3Fnode-id%3D0%253A1%26t%3DhPQwdx3HFPWJWnVf-1\" allowfullscreen></iframe>\n\n### Encoder[[mm-encoder]]\n\n[VisualBERT](model_doc/visual_bert) is a multimodal model for vision-language tasks released shortly after BERT. It combines BERT and a pretrained object detection system to extract image features into visual embeddings, passed alongside text embeddings to BERT. VisualBERT predicts the masked text based on the unmasked text and the visual embeddings, and it also has to predict whether the text is aligned with the image. When ViT was released, [ViLT](model_doc/vilt) adopted ViT in its architecture because it was easier to get the image embeddings this way. The image embeddings are jointly processed with the text embeddings."}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 205c83f6-11bd-4b67-b231-dc27dc9f6eba
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"205c83f6-11bd-4b67-b231-dc27dc9f6eba\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_summary\", \"title\": \"The Transformer model family\", \"tokens\": 4019, \"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\": \"fd6ed4d3-f1ca-498d-9c74-7a5d84385e19\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_summary\", \"title\": \"The Transformer model family\", \"tokens\": 4019, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8cead54d1f52c4d818c9192529c1a4c2c648d344c5ad270063818d92463dd149\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"d937da67-2c92-437f-bbe8-f65939cfcb2e\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_summary\", \"title\": \"The Transformer model family\", \"tokens\": 4019, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"fa6c702bf46bc45dbfd23db38fdade0b4aa487138c200805be43e560071c626d\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"f843c63c-3867-4062-a01f-88e185a3463e\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"55d7f6021f5b22795320384716981b088bd8b5ea976418e4c23e88a80e15cad1\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 12071, \"end_char_idx\": 15267, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "fd6ed4d3-f1ca-498d-9c74-7a5d84385e19", "doc_id": "fd6ed4d3-f1ca-498d-9c74-7a5d84385e19", "ref_doc_id": "fd6ed4d3-f1ca-498d-9c74-7a5d84385e19", "chroma:document": "[Whisper](model_doc/whisper) is also an ASR model, but unlike many other speech models, it is pretrained on a massive amount of \u2728 labeled \u2728 audio transcription data for zero-shot performance. A large chunk of the dataset also contains non-English languages, meaning Whisper can also be used for low-resource languages. Structurally, Whisper is similar to Speech2Text. The audio signal is converted to a log-mel spectrogram encoded by the encoder. The decoder generates the transcript autoregressively from the encoder's hidden states and the previous tokens.\n\n## Multimodal\n\n<iframe style=\"border: 1px solid rgba(0, 0, 0, 0.1);\" width=\"1000\" height=\"450\" src=\"https://www.figma.com/embed?embed_host=share&url=https%3A%2F%2Fwww.figma.com%2Ffile%2FcX125FQHXJS2gxeICiY93p%2Fmultimodal%3Fnode-id%3D0%253A1%26t%3DhPQwdx3HFPWJWnVf-1\" allowfullscreen></iframe>\n\n### Encoder[[mm-encoder]]\n\n[VisualBERT](model_doc/visual_bert) is a multimodal model for vision-language tasks released shortly after BERT. It combines BERT and a pretrained object detection system to extract image features into visual embeddings, passed alongside text embeddings to BERT. VisualBERT predicts the masked text based on the unmasked text and the visual embeddings, and it also has to predict whether the text is aligned with the image. When ViT was released, [ViLT](model_doc/vilt) adopted ViT in its architecture because it was easier to get the image embeddings this way. The image embeddings are jointly processed with the text embeddings. From there, ViLT is pretrained by image text matching, masked language modeling, and whole word masking.\n\n[CLIP](model_doc/clip) takes a different approach and makes a pair prediction of (`image`, `text`) . An image encoder (ViT) and a text encoder (Transformer) are jointly trained on a 400 million (`image`, `text`) pair dataset to maximize the similarity between the image and text embeddings of the (`image`, `text`) pairs. After pretraining, you can use natural language to instruct CLIP to predict the text given an image or vice versa. [OWL-ViT](model_doc/owlvit) builds on top of CLIP by using it as its backbone for zero-shot object detection. After pretraining, an object detection head is added to make a set prediction over the (`class`, `bounding box`) pairs.\n\n### Encoder-decoder[[mm-encoder-decoder]]\n\nOptical character recognition (OCR) is a long-standing text recognition task that typically involves several components to understand the image and generate the text. [TrOCR](model_doc/trocr) simplifies the process using an end-to-end Transformer. The encoder is a ViT-style model for image understanding and processes the image as fixed-size patches. The decoder accepts the encoder's hidden states and autoregressively generates text. [Donut](model_doc/donut) is a more general visual document understanding model that doesn't rely on OCR-based approaches. It uses a Swin Transformer as the encoder and multilingual BART as the decoder. Donut is pretrained to read text by predicting the next word based on the image and text annotations. The decoder generates a token sequence given a prompt. The prompt is represented by a special token for each downstream task."}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: f843c63c-3867-4062-a01f-88e185a3463e
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"f843c63c-3867-4062-a01f-88e185a3463e\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_summary\", \"title\": \"The Transformer model family\", \"tokens\": 4019, \"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\": \"fd6ed4d3-f1ca-498d-9c74-7a5d84385e19\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_summary\", \"title\": \"The Transformer model family\", \"tokens\": 4019, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8cead54d1f52c4d818c9192529c1a4c2c648d344c5ad270063818d92463dd149\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"205c83f6-11bd-4b67-b231-dc27dc9f6eba\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/model_summary\", \"title\": \"The Transformer model family\", \"tokens\": 4019, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"74299f09fc5979aeab98d5bd804c6b4941c61ba12ac7b274e64037863ff1c96a\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 13515, \"end_char_idx\": 16524, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "fd6ed4d3-f1ca-498d-9c74-7a5d84385e19", "doc_id": "fd6ed4d3-f1ca-498d-9c74-7a5d84385e19", "ref_doc_id": "fd6ed4d3-f1ca-498d-9c74-7a5d84385e19", "chroma:document": "The image embeddings are jointly processed with the text embeddings. From there, ViLT is pretrained by image text matching, masked language modeling, and whole word masking.\n\n[CLIP](model_doc/clip) takes a different approach and makes a pair prediction of (`image`, `text`) . An image encoder (ViT) and a text encoder (Transformer) are jointly trained on a 400 million (`image`, `text`) pair dataset to maximize the similarity between the image and text embeddings of the (`image`, `text`) pairs. After pretraining, you can use natural language to instruct CLIP to predict the text given an image or vice versa. [OWL-ViT](model_doc/owlvit) builds on top of CLIP by using it as its backbone for zero-shot object detection. After pretraining, an object detection head is added to make a set prediction over the (`class`, `bounding box`) pairs.\n\n### Encoder-decoder[[mm-encoder-decoder]]\n\nOptical character recognition (OCR) is a long-standing text recognition task that typically involves several components to understand the image and generate the text. [TrOCR](model_doc/trocr) simplifies the process using an end-to-end Transformer. The encoder is a ViT-style model for image understanding and processes the image as fixed-size patches. The decoder accepts the encoder's hidden states and autoregressively generates text. [Donut](model_doc/donut) is a more general visual document understanding model that doesn't rely on OCR-based approaches. It uses a Swin Transformer as the encoder and multilingual BART as the decoder. Donut is pretrained to read text by predicting the next word based on the image and text annotations. The decoder generates a token sequence given a prompt. The prompt is represented by a special token for each downstream task. For example, document parsing has a special `parsing` token that is combined with the encoder hidden states to parse the document into a structured output format (JSON).\n\n## Reinforcement learning\n\n<iframe style=\"border: 1px solid rgba(0, 0, 0, 0.1);\" width=\"1000\" height=\"450\" src=\"https://www.figma.com/embed?embed_host=share&url=https%3A%2F%2Fwww.figma.com%2Ffile%2FiB3Y6RvWYki7ZuKO6tNgZq%2Freinforcement-learning%3Fnode-id%3D0%253A1%26t%3DhPQwdx3HFPWJWnVf-1\" allowfullscreen></iframe>\n\n### Decoder[[rl-decoder]]\n\nThe Decision and Trajectory Transformer casts the state, action, and reward as a sequence modeling problem. The [Decision Transformer](model_doc/decision_transformer) generates a series of actions that lead to a future desired return based on returns-to-go, past states, and actions. For the last *K* timesteps, each of the three modalities are converted into token embeddings and processed by a GPT-like model to predict a future action token. [Trajectory Transformer](model_doc/trajectory_transformer) also tokenizes the states, actions, and rewards and processes them with a GPT architecture. Unlike the Decision Transformer, which is focused on reward conditioning, the Trajectory Transformer generates future actions with beam search."}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 60aa5821-1a7e-4082-9674-200629fd36f2
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_hardware", "title": "Custom hardware for training", "tokens": 1941, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"60aa5821-1a7e-4082-9674-200629fd36f2\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_hardware\", \"title\": \"Custom hardware for training\", \"tokens\": 1941, \"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\": \"ce45066f-bb84-4136-8a15-25e2b289e1db\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_hardware\", \"title\": \"Custom hardware for training\", \"tokens\": 1941, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"e8838a6c78427147c4993990011b8914b4ed1ea4b07c2b4cb49c8e0365b689de\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"41d03d1e-1ecb-49f1-b37e-a05e9aa19211\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"34cee575c4a8d6656ad5e45edec6ab7cced2b101a667d59d84188a5a540f992c\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 0, \"end_char_idx\": 3286, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "ce45066f-bb84-4136-8a15-25e2b289e1db", "doc_id": "ce45066f-bb84-4136-8a15-25e2b289e1db", "ref_doc_id": "ce45066f-bb84-4136-8a15-25e2b289e1db", "chroma:document": "<!---\nCopyright 2022 The HuggingFace Team. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n\u26a0\ufe0f Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be\nrendered properly in your Markdown viewer.\n\n-->\n\n\n# Custom hardware for training\n\nThe hardware you use to run model training and inference can have a big effect on performance. For a deep dive into GPUs make sure to check out Tim Dettmer's excellent [blog post](https://timdettmers.com/2020/09/07/which-gpu-for-deep-learning/).\n\nLet's have a look at some practical advice for GPU setups.\n\n## GPU\nWhen you train bigger models you have essentially three options:\n\n- bigger GPUs\n- more GPUs\n- more CPU and NVMe (offloaded to by [DeepSpeed-Infinity](main_classes/deepspeed#nvme-support))\n\nLet's start at the case where you have a single GPU.\n\n### Power and Cooling\n\nIf you bought an expensive high end GPU make sure you give it the correct power and sufficient cooling.\n\n**Power**:\n\nSome high end consumer GPU cards have 2 and sometimes 3 PCI-E 8-Pin power sockets. Make sure you have as many independent 12V PCI-E 8-Pin cables plugged into the card as there are sockets. Do not use the 2 splits at one end of the same cable (also known as pigtail cable). That is if you have 2 sockets on the GPU, you want 2 PCI-E 8-Pin cables going from your PSU to the card and not one that has 2 PCI-E 8-Pin connectors at the end! You won't get the full performance out of your card otherwise.\n\nEach PCI-E 8-Pin power cable needs to be plugged into a 12V rail on the PSU side and can supply up to 150W of power.\n\nSome other cards may use a PCI-E 12-Pin connectors, and these can deliver up to 500-600W of power.\n\nLow end cards may use 6-Pin connectors, which supply up to 75W of power.\n\nAdditionally you want the high-end PSU that has stable voltage. Some lower quality ones may not give the card the stable voltage it needs to function at its peak.\n\nAnd of course the PSU needs to have enough unused Watts to power the card.\n\n**Cooling**:\n\nWhen a GPU gets overheated it will start throttling down and will not deliver full performance and it can even shutdown if it gets too hot.\n\nIt's hard to tell the exact best temperature to strive for when a GPU is heavily loaded, but probably anything under +80C is good, but lower is better - perhaps 70-75C is an excellent range to be in. The throttling down is likely to start at around 84-90C. But other than throttling performance a prolonged very high temperature is likely to reduce the lifespan of a GPU.\n\nNext let's have a look at one of the most important aspects when having multiple GPUs: connectivity.\n\n### Multi-GPU Connectivity\n\nIf you use multiple GPUs the way cards are inter-connected can have a huge impact on the total training time."}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 41d03d1e-1ecb-49f1-b37e-a05e9aa19211
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_hardware", "title": "Custom hardware for training", "tokens": 1941, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"41d03d1e-1ecb-49f1-b37e-a05e9aa19211\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_hardware\", \"title\": \"Custom hardware for training\", \"tokens\": 1941, \"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\": \"ce45066f-bb84-4136-8a15-25e2b289e1db\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_hardware\", \"title\": \"Custom hardware for training\", \"tokens\": 1941, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"e8838a6c78427147c4993990011b8914b4ed1ea4b07c2b4cb49c8e0365b689de\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"60aa5821-1a7e-4082-9674-200629fd36f2\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_hardware\", \"title\": \"Custom hardware for training\", \"tokens\": 1941, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"fda7bb9e045edb477dbf78dffec491870dc18bee2c6a01730b9c7f4ba793188c\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"bcec998a-b9bf-45a6-ad42-2a67c5f1cf8a\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"54b4d826cda659e6691a587f07df8481d0d3ed69a982fdf112f8ada872f9d2be\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 1677, \"end_char_idx\": 4771, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "ce45066f-bb84-4136-8a15-25e2b289e1db", "doc_id": "ce45066f-bb84-4136-8a15-25e2b289e1db", "ref_doc_id": "ce45066f-bb84-4136-8a15-25e2b289e1db", "chroma:document": "Do not use the 2 splits at one end of the same cable (also known as pigtail cable). That is if you have 2 sockets on the GPU, you want 2 PCI-E 8-Pin cables going from your PSU to the card and not one that has 2 PCI-E 8-Pin connectors at the end! You won't get the full performance out of your card otherwise.\n\nEach PCI-E 8-Pin power cable needs to be plugged into a 12V rail on the PSU side and can supply up to 150W of power.\n\nSome other cards may use a PCI-E 12-Pin connectors, and these can deliver up to 500-600W of power.\n\nLow end cards may use 6-Pin connectors, which supply up to 75W of power.\n\nAdditionally you want the high-end PSU that has stable voltage. Some lower quality ones may not give the card the stable voltage it needs to function at its peak.\n\nAnd of course the PSU needs to have enough unused Watts to power the card.\n\n**Cooling**:\n\nWhen a GPU gets overheated it will start throttling down and will not deliver full performance and it can even shutdown if it gets too hot.\n\nIt's hard to tell the exact best temperature to strive for when a GPU is heavily loaded, but probably anything under +80C is good, but lower is better - perhaps 70-75C is an excellent range to be in. The throttling down is likely to start at around 84-90C. But other than throttling performance a prolonged very high temperature is likely to reduce the lifespan of a GPU.\n\nNext let's have a look at one of the most important aspects when having multiple GPUs: connectivity.\n\n### Multi-GPU Connectivity\n\nIf you use multiple GPUs the way cards are inter-connected can have a huge impact on the total training time. If the GPUs are on the same physical node, you can run:\n\n```bash\nnvidia-smi topo -m\n```\n\nand it will tell you how the GPUs are inter-connected. On a machine with dual-GPU and which are connected with NVLink, you will most likely see something like:\n\n```\n        GPU0    GPU1    CPU Affinity    NUMA Affinity\nGPU0     X      NV2     0-23            N/A\nGPU1    NV2      X      0-23            N/A\n```\n\non a different machine w/o NVLink we may see:\n```\n        GPU0    GPU1    CPU Affinity    NUMA Affinity\nGPU0     X      PHB     0-11            N/A\nGPU1    PHB      X      0-11            N/A\n```\n\nThe report includes this legend:\n\n```\n  X    = Self\n  SYS  = Connection traversing PCIe as well as the SMP interconnect between NUMA nodes (e.g., QPI/UPI)\n  NODE = Connection traversing PCIe as well as the interconnect between PCIe Host Bridges within a NUMA node\n  PHB  = Connection traversing PCIe as well as a PCIe Host Bridge (typically the CPU)\n  PXB  = Connection traversing multiple PCIe bridges (without traversing the PCIe Host Bridge)\n  PIX  = Connection traversing at most a single PCIe bridge\n  NV#  = Connection traversing a bonded set of # NVLinks\n```\n\nSo the first report `NV2` tells us the GPUs are interconnected with 2 NVLinks, and the second report `PHB` we have a typical consumer-level PCIe+Bridge setup.\n\nCheck what type of connectivity you have on your setup. Some of these will make the communication between cards faster (e.g. NVLink), others slower (e.g. PHB)."}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: bcec998a-b9bf-45a6-ad42-2a67c5f1cf8a
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_hardware", "title": "Custom hardware for training", "tokens": 1941, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"bcec998a-b9bf-45a6-ad42-2a67c5f1cf8a\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_hardware\", \"title\": \"Custom hardware for training\", \"tokens\": 1941, \"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\": \"ce45066f-bb84-4136-8a15-25e2b289e1db\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_hardware\", \"title\": \"Custom hardware for training\", \"tokens\": 1941, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"e8838a6c78427147c4993990011b8914b4ed1ea4b07c2b4cb49c8e0365b689de\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"41d03d1e-1ecb-49f1-b37e-a05e9aa19211\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_hardware\", \"title\": \"Custom hardware for training\", \"tokens\": 1941, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"28ed93b03afccfae9a9784493935b1c18c80fe17c2bcebfaf61c6dc9ac806cf1\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"d9e243d3-3d0b-4448-be2b-b8edf916985d\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"892aecf849bcdd19da82ab9ff46d89acb8f7ad231f9549766f70f8555d833814\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 3287, \"end_char_idx\": 6271, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "ce45066f-bb84-4136-8a15-25e2b289e1db", "doc_id": "ce45066f-bb84-4136-8a15-25e2b289e1db", "ref_doc_id": "ce45066f-bb84-4136-8a15-25e2b289e1db", "chroma:document": "If the GPUs are on the same physical node, you can run:\n\n```bash\nnvidia-smi topo -m\n```\n\nand it will tell you how the GPUs are inter-connected. On a machine with dual-GPU and which are connected with NVLink, you will most likely see something like:\n\n```\n        GPU0    GPU1    CPU Affinity    NUMA Affinity\nGPU0     X      NV2     0-23            N/A\nGPU1    NV2      X      0-23            N/A\n```\n\non a different machine w/o NVLink we may see:\n```\n        GPU0    GPU1    CPU Affinity    NUMA Affinity\nGPU0     X      PHB     0-11            N/A\nGPU1    PHB      X      0-11            N/A\n```\n\nThe report includes this legend:\n\n```\n  X    = Self\n  SYS  = Connection traversing PCIe as well as the SMP interconnect between NUMA nodes (e.g., QPI/UPI)\n  NODE = Connection traversing PCIe as well as the interconnect between PCIe Host Bridges within a NUMA node\n  PHB  = Connection traversing PCIe as well as a PCIe Host Bridge (typically the CPU)\n  PXB  = Connection traversing multiple PCIe bridges (without traversing the PCIe Host Bridge)\n  PIX  = Connection traversing at most a single PCIe bridge\n  NV#  = Connection traversing a bonded set of # NVLinks\n```\n\nSo the first report `NV2` tells us the GPUs are interconnected with 2 NVLinks, and the second report `PHB` we have a typical consumer-level PCIe+Bridge setup.\n\nCheck what type of connectivity you have on your setup. Some of these will make the communication between cards faster (e.g. NVLink), others slower (e.g. PHB).\n\nDepending on the type of scalability solution used, the connectivity speed could have a major or a minor impact. If the GPUs need to sync rarely, as in DDP, the impact of a slower connection will be less significant. If the GPUs need to send messages to each other often, as in ZeRO-DP, then faster connectivity becomes super important to achieve faster training.\n\n#### NVlink\n\n[NVLink](https://en.wikipedia.org/wiki/NVLink) is a wire-based serial multi-lane near-range communications link developed by Nvidia.\n\nEach new generation provides a faster bandwidth, e.g. here is a quote from [Nvidia Ampere GA102 GPU Architecture](https://www.nvidia.com/content/dam/en-zz/Solutions/geforce/ampere/pdf/NVIDIA-ampere-GA102-GPU-Architecture-Whitepaper-V1.pdf):\n\n> Third-Generation NVLink\u00ae\n> GA102 GPUs utilize NVIDIA\u2019s third-generation NVLink interface, which includes four x4 links,\n> with each link providing 14.0625 GB/sec bandwidth in each direction between two GPUs. Four\n> links provide 56.25 GB/sec bandwidth in each direction, and 112.5 GB/sec total bandwidth\n> between two GPUs. Two RTX 3090 GPUs can be connected together for SLI using NVLink.\n> (Note that 3-Way and 4-Way SLI configurations are not supported.)\n\nSo the higher `X` you get in the report of `NVX` in the output of `nvidia-smi topo -m` the better. The generation will depend on your GPU architecture.\n\nLet's compare the execution of an openai-community/gpt2 language model training over a small sample of wikitext.\n\nThe results are:"}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: d9e243d3-3d0b-4448-be2b-b8edf916985d
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_hardware", "title": "Custom hardware for training", "tokens": 1941, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"d9e243d3-3d0b-4448-be2b-b8edf916985d\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_hardware\", \"title\": \"Custom hardware for training\", \"tokens\": 1941, \"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\": \"ce45066f-bb84-4136-8a15-25e2b289e1db\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_hardware\", \"title\": \"Custom hardware for training\", \"tokens\": 1941, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"e8838a6c78427147c4993990011b8914b4ed1ea4b07c2b4cb49c8e0365b689de\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"bcec998a-b9bf-45a6-ad42-2a67c5f1cf8a\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_hardware\", \"title\": \"Custom hardware for training\", \"tokens\": 1941, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"1cb08c8f7c50b89722f9f03b0f4ea0a9b585ea4412775711d5c65e5329008fe4\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"33cd143c-d735-4ca2-ba2a-e44183513b5d\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"ded506ad8664380d5638592adb5cd5ec430e6117255272c8ab9dd20070e07e7b\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 4668, \"end_char_idx\": 6345, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "ce45066f-bb84-4136-8a15-25e2b289e1db", "doc_id": "ce45066f-bb84-4136-8a15-25e2b289e1db", "ref_doc_id": "ce45066f-bb84-4136-8a15-25e2b289e1db", "chroma:document": "Some of these will make the communication between cards faster (e.g. NVLink), others slower (e.g. PHB).\n\nDepending on the type of scalability solution used, the connectivity speed could have a major or a minor impact. If the GPUs need to sync rarely, as in DDP, the impact of a slower connection will be less significant. If the GPUs need to send messages to each other often, as in ZeRO-DP, then faster connectivity becomes super important to achieve faster training.\n\n#### NVlink\n\n[NVLink](https://en.wikipedia.org/wiki/NVLink) is a wire-based serial multi-lane near-range communications link developed by Nvidia.\n\nEach new generation provides a faster bandwidth, e.g. here is a quote from [Nvidia Ampere GA102 GPU Architecture](https://www.nvidia.com/content/dam/en-zz/Solutions/geforce/ampere/pdf/NVIDIA-ampere-GA102-GPU-Architecture-Whitepaper-V1.pdf):\n\n> Third-Generation NVLink\u00ae\n> GA102 GPUs utilize NVIDIA\u2019s third-generation NVLink interface, which includes four x4 links,\n> with each link providing 14.0625 GB/sec bandwidth in each direction between two GPUs. Four\n> links provide 56.25 GB/sec bandwidth in each direction, and 112.5 GB/sec total bandwidth\n> between two GPUs. Two RTX 3090 GPUs can be connected together for SLI using NVLink.\n> (Note that 3-Way and 4-Way SLI configurations are not supported.)\n\nSo the higher `X` you get in the report of `NVX` in the output of `nvidia-smi topo -m` the better. The generation will depend on your GPU architecture.\n\nLet's compare the execution of an openai-community/gpt2 language model training over a small sample of wikitext.\n\nThe results are:\n\n\n| NVlink | Time |\n| -----  | ---: |\n| Y      | 101s |\n| N      | 131s |"}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 33cd143c-d735-4ca2-ba2a-e44183513b5d
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_hardware", "title": "Custom hardware for training", "tokens": 1941, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"33cd143c-d735-4ca2-ba2a-e44183513b5d\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_hardware\", \"title\": \"Custom hardware for training\", \"tokens\": 1941, \"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\": \"ce45066f-bb84-4136-8a15-25e2b289e1db\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_hardware\", \"title\": \"Custom hardware for training\", \"tokens\": 1941, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"e8838a6c78427147c4993990011b8914b4ed1ea4b07c2b4cb49c8e0365b689de\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"d9e243d3-3d0b-4448-be2b-b8edf916985d\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_hardware\", \"title\": \"Custom hardware for training\", \"tokens\": 1941, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"2d3fb788533fb2dd41baed8ec634ed9319fd32f536da8710adeca7f63b7e9443\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 4773, \"end_char_idx\": 7566, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "ce45066f-bb84-4136-8a15-25e2b289e1db", "doc_id": "ce45066f-bb84-4136-8a15-25e2b289e1db", "ref_doc_id": "ce45066f-bb84-4136-8a15-25e2b289e1db", "chroma:document": "Depending on the type of scalability solution used, the connectivity speed could have a major or a minor impact. If the GPUs need to sync rarely, as in DDP, the impact of a slower connection will be less significant. If the GPUs need to send messages to each other often, as in ZeRO-DP, then faster connectivity becomes super important to achieve faster training.\n\n#### NVlink\n\n[NVLink](https://en.wikipedia.org/wiki/NVLink) is a wire-based serial multi-lane near-range communications link developed by Nvidia.\n\nEach new generation provides a faster bandwidth, e.g. here is a quote from [Nvidia Ampere GA102 GPU Architecture](https://www.nvidia.com/content/dam/en-zz/Solutions/geforce/ampere/pdf/NVIDIA-ampere-GA102-GPU-Architecture-Whitepaper-V1.pdf):\n\n> Third-Generation NVLink\u00ae\n> GA102 GPUs utilize NVIDIA\u2019s third-generation NVLink interface, which includes four x4 links,\n> with each link providing 14.0625 GB/sec bandwidth in each direction between two GPUs. Four\n> links provide 56.25 GB/sec bandwidth in each direction, and 112.5 GB/sec total bandwidth\n> between two GPUs. Two RTX 3090 GPUs can be connected together for SLI using NVLink.\n> (Note that 3-Way and 4-Way SLI configurations are not supported.)\n\nSo the higher `X` you get in the report of `NVX` in the output of `nvidia-smi topo -m` the better. The generation will depend on your GPU architecture.\n\nLet's compare the execution of an openai-community/gpt2 language model training over a small sample of wikitext.\n\nThe results are:\n\n\n| NVlink | Time |\n| -----  | ---: |\n| Y      | 101s |\n| N      | 131s |\n\n\nYou can see that NVLink completes the training ~23% faster. In the second benchmark we use `NCCL_P2P_DISABLE=1` to tell the GPUs not to use NVLink.\n\nHere is the full benchmark code and outputs:\n\n```bash\n# DDP w/ NVLink\n\nrm -r /tmp/test-clm; CUDA_VISIBLE_DEVICES=0,1 torchrun \\\n--nproc_per_node 2 examples/pytorch/language-modeling/run_clm.py --model_name_or_path openai-community/gpt2 \\\n--dataset_name wikitext --dataset_config_name wikitext-2-raw-v1 --do_train \\\n--output_dir /tmp/test-clm --per_device_train_batch_size 4 --max_steps 200\n\n{'train_runtime': 101.9003, 'train_samples_per_second': 1.963, 'epoch': 0.69}\n\n# DDP w/o NVLink\n\nrm -r /tmp/test-clm; CUDA_VISIBLE_DEVICES=0,1 NCCL_P2P_DISABLE=1 torchrun \\\n--nproc_per_node 2 examples/pytorch/language-modeling/run_clm.py --model_name_or_path openai-community/gpt2 \\\n--dataset_name wikitext --dataset_config_name wikitext-2-raw-v1 --do_train\n--output_dir /tmp/test-clm --per_device_train_batch_size 4 --max_steps 200\n\n{'train_runtime': 131.4367, 'train_samples_per_second': 1.522, 'epoch': 0.69}\n```\n\nHardware: 2x TITAN RTX 24GB each + NVlink with 2 NVLinks (`NV2` in `nvidia-smi topo -m`)\nSoftware: `pytorch-1.8-to-be` + `cuda-11.0` / `transformers==4.3.0.dev0`"}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 0158a30c-859e-47f0-8abf-ddde5d22e068
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/gguf", "title": "GGUF and interaction with Transformers", "tokens": 984, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"0158a30c-859e-47f0-8abf-ddde5d22e068\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/gguf\", \"title\": \"GGUF and interaction with Transformers\", \"tokens\": 984, \"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\": \"63af9d7a-4340-4cbb-9202-513cd71b5282\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/gguf\", \"title\": \"GGUF and interaction with Transformers\", \"tokens\": 984, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"1aba5118f2cd3cdbca993da6d6369eb9cb53f690196a24a74b6e9704122221f0\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"aa2831f6-5b84-468a-bce7-e8bd7a8e367e\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"067c475a9a529ec610dc84b48ff8150b30d8f2a1407c1e4600607487e6f65e24\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 0, \"end_char_idx\": 2969, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "63af9d7a-4340-4cbb-9202-513cd71b5282", "doc_id": "63af9d7a-4340-4cbb-9202-513cd71b5282", "ref_doc_id": "63af9d7a-4340-4cbb-9202-513cd71b5282", "chroma:document": "# GGUF and interaction with Transformers\n\nThe GGUF file format is used to store models for inference with [GGML](https://github.com/ggerganov/ggml) and other \nlibraries that depend on it, like the very popular [llama.cpp](https://github.com/ggerganov/llama.cpp) or \n[whisper.cpp](https://github.com/ggerganov/whisper.cpp).\n\nIt is a file format [supported by the Hugging Face Hub](https://huggingface.co/docs/hub/en/gguf) with features \nallowing for quick inspection of tensors and metadata within the file.\n\nThis file format is designed as a \"single-file-format\" where a single file usually contains both the configuration\nattributes, the tokenizer vocabulary and other attributes, as well as all tensors to be loaded in the model. These\nfiles come in different formats according to the quantization type of the file. We briefly go over some of them\n[here](https://huggingface.co/docs/hub/en/gguf#quantization-types).\n\n## Support within Transformers\n\nWe have added the ability to load `gguf` files within `transformers` in order to offer further training/fine-tuning\ncapabilities to gguf models, before converting back those models to `gguf` to use within the `ggml` ecosystem. When\nloading a model, we first dequantize it to fp32, before loading the weights to be used in PyTorch.\n\n> [!NOTE]\n> The support is still very exploratory and we welcome contributions in order to solidify it across quantization types\n> and model architectures.\n\nFor now, here are the supported model architectures and quantization types:\n\n### Supported quantization types\n\nThe initial supported quantization types are decided according to the popular quantized files that have been shared\non the Hub.\n\n- F32\n- Q2_K\n- Q3_K\n- Q4_0\n- Q4_K\n- Q5_K\n- Q6_K\n- Q8_0\n\nWe take example from the excellent [99991/pygguf](https://github.com/99991/pygguf) Python parser to dequantize the \nweights.\n\n### Supported model architectures\n\nFor now the supported model architectures are the architectures that have been very popular on the Hub, namely:\n\n- LLaMa\n- Mistral\n- Qwen2\n\n## Example usage\n\nIn order to load `gguf` files in `transformers`, you should specify the `gguf_file` argument to the `from_pretrained`\nmethods of both tokenizers and models. Here is how one would load a tokenizer and a model, which can be loaded\nfrom the exact same file:\n\n```py\nfrom transformers import AutoTokenizer, AutoModelForCausalLM\n\nmodel_id = \"TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF\"\nfilename = \"tinyllama-1.1b-chat-v1.0.Q6_K.gguf\"\n\ntokenizer = AutoTokenizer.from_pretrained(model_id, gguf_file=filename)\nmodel = AutoModelForCausalLM.from_pretrained(model_id, gguf_file=filename)\n```\n\nNow you have access to the full, unquantized version of the model in the PyTorch ecosystem, where you can combine it\nwith a plethora of other tools.\n\nIn order to convert back to a `gguf` file, we recommend using the \n[`convert-hf-to-gguf.py` file](https://github.com/ggerganov/llama.cpp/blob/master/convert-hf-to-gguf.py) from llama.cpp."}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: aa2831f6-5b84-468a-bce7-e8bd7a8e367e
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/gguf", "title": "GGUF and interaction with Transformers", "tokens": 984, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"aa2831f6-5b84-468a-bce7-e8bd7a8e367e\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/gguf\", \"title\": \"GGUF and interaction with Transformers\", \"tokens\": 984, \"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\": \"63af9d7a-4340-4cbb-9202-513cd71b5282\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/gguf\", \"title\": \"GGUF and interaction with Transformers\", \"tokens\": 984, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"1aba5118f2cd3cdbca993da6d6369eb9cb53f690196a24a74b6e9704122221f0\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"0158a30c-859e-47f0-8abf-ddde5d22e068\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/gguf\", \"title\": \"GGUF and interaction with Transformers\", \"tokens\": 984, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"08d09dedf6a752d416eb85d376710739eea6970d94f040486bbd0913d0b71202\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 1680, \"end_char_idx\": 3215, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "63af9d7a-4340-4cbb-9202-513cd71b5282", "doc_id": "63af9d7a-4340-4cbb-9202-513cd71b5282", "ref_doc_id": "63af9d7a-4340-4cbb-9202-513cd71b5282", "chroma:document": "- F32\n- Q2_K\n- Q3_K\n- Q4_0\n- Q4_K\n- Q5_K\n- Q6_K\n- Q8_0\n\nWe take example from the excellent [99991/pygguf](https://github.com/99991/pygguf) Python parser to dequantize the \nweights.\n\n### Supported model architectures\n\nFor now the supported model architectures are the architectures that have been very popular on the Hub, namely:\n\n- LLaMa\n- Mistral\n- Qwen2\n\n## Example usage\n\nIn order to load `gguf` files in `transformers`, you should specify the `gguf_file` argument to the `from_pretrained`\nmethods of both tokenizers and models. Here is how one would load a tokenizer and a model, which can be loaded\nfrom the exact same file:\n\n```py\nfrom transformers import AutoTokenizer, AutoModelForCausalLM\n\nmodel_id = \"TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF\"\nfilename = \"tinyllama-1.1b-chat-v1.0.Q6_K.gguf\"\n\ntokenizer = AutoTokenizer.from_pretrained(model_id, gguf_file=filename)\nmodel = AutoModelForCausalLM.from_pretrained(model_id, gguf_file=filename)\n```\n\nNow you have access to the full, unquantized version of the model in the PyTorch ecosystem, where you can combine it\nwith a plethora of other tools.\n\nIn order to convert back to a `gguf` file, we recommend using the \n[`convert-hf-to-gguf.py` file](https://github.com/ggerganov/llama.cpp/blob/master/convert-hf-to-gguf.py) from llama.cpp.\n\nHere's how you would complete the script above to save the model and export it back to `gguf`:\n\n```py\ntokenizer.save_pretrained('directory')\nmodel.save_pretrained('directory')\n\n!python ${path_to_llama_cpp}/convert-hf-to-gguf.py ${directory}\n```"}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 29fa1f44-5f62-4b5c-96d5-dff4f712f6f0
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/attention", "title": "Attention mechanisms", "tokens": 862, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"29fa1f44-5f62-4b5c-96d5-dff4f712f6f0\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/attention\", \"title\": \"Attention mechanisms\", \"tokens\": 862, \"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\": \"c0127d63-dfa8-4c4c-9a21-cbe4211252ad\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/attention\", \"title\": \"Attention mechanisms\", \"tokens\": 862, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"a2f77a27d88eca3804ec54054d070a99e06e4ac4a4127d03a79079e6d8d8a746\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 0, \"end_char_idx\": 2906, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "c0127d63-dfa8-4c4c-9a21-cbe4211252ad", "doc_id": "c0127d63-dfa8-4c4c-9a21-cbe4211252ad", "ref_doc_id": "c0127d63-dfa8-4c4c-9a21-cbe4211252ad", "chroma:document": "# Attention mechanisms\n\nMost transformer models use full attention in the sense that the attention matrix is square. It can be a big\ncomputational bottleneck when you have long texts. Longformer and reformer are models that try to be more efficient and\nuse a sparse version of the attention matrix to speed up training.\n\n## LSH attention\n\n[Reformer](model_doc/reformer) uses LSH attention. In the softmax(QK^t), only the biggest elements (in the softmax\ndimension) of the matrix QK^t are going to give useful contributions. So for each query q in Q, we can consider only\nthe keys k in K that are close to q. A hash function is used to determine if q and k are close. The attention mask is\nmodified to mask the current token (except at the first position), because it will give a query and a key equal (so\nvery similar to each other). Since the hash can be a bit random, several hash functions are used in practice\n(determined by a n_rounds parameter) and then are averaged together.\n\n## Local attention\n\n[Longformer](model_doc/longformer) uses local attention: often, the local context (e.g., what are the two tokens to the\nleft and right?) is enough to take action for a given token. Also, by stacking attention layers that have a small\nwindow, the last layer will have a receptive field of more than just the tokens in the window, allowing them to build a\nrepresentation of the whole sentence.\n\nSome preselected input tokens are also given global attention: for those few tokens, the attention matrix can access\nall tokens and this process is symmetric: all other tokens have access to those specific tokens (on top of the ones in\ntheir local window). This is shown in Figure 2d of the paper, see below for a sample attention mask:\n\n<div class=\"flex justify-center\">\n    <img scale=\"50 %\" align=\"center\" src=\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/local_attention_mask.png\"/>\n</div>\n\nUsing those attention matrices with less parameters then allows the model to have inputs having a bigger sequence\nlength.\n\n## Other tricks\n\n### Axial positional encodings\n\n[Reformer](model_doc/reformer) uses axial positional encodings: in traditional transformer models, the positional encoding\nE is a matrix of size \\\\(l\\\\) by \\\\(d\\\\), \\\\(l\\\\) being the sequence length and \\\\(d\\\\) the dimension of the\nhidden state. If you have very long texts, this matrix can be huge and take way too much space on the GPU. To alleviate\nthat, axial positional encodings consist of factorizing that big matrix E in two smaller matrices E1 and E2, with\ndimensions \\\\(l_{1} \\times d_{1}\\\\) and \\\\(l_{2} \\times d_{2}\\\\), such that \\\\(l_{1} \\times l_{2} = l\\\\) and\n\\\\(d_{1} + d_{2} = d\\\\) (with the product for the lengths, this ends up being way smaller). The embedding for time\nstep \\\\(j\\\\) in E is obtained by concatenating the embeddings for timestep \\\\(j \\% l1\\\\) in E1 and \\\\(j // l1\\\\)\nin E2."}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 267b417b-a993-4662-84bc-14386b5bab1c
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/fast_tokenizers", "title": "Use tokenizers from \ud83e\udd17 Tokenizers", "tokens": 649, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"267b417b-a993-4662-84bc-14386b5bab1c\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/fast_tokenizers\", \"title\": \"Use tokenizers from \\ud83e\\udd17 Tokenizers\", \"tokens\": 649, \"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\": \"738c43a2-7a09-4c2a-9d30-d8aee499bf36\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/fast_tokenizers\", \"title\": \"Use tokenizers from \\ud83e\\udd17 Tokenizers\", \"tokens\": 649, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"32073cdb09c332f609d301597e53983bf339a3a0ce0bae9031cabbf2fb868608\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 0, \"end_char_idx\": 2125, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "738c43a2-7a09-4c2a-9d30-d8aee499bf36", "doc_id": "738c43a2-7a09-4c2a-9d30-d8aee499bf36", "ref_doc_id": "738c43a2-7a09-4c2a-9d30-d8aee499bf36", "chroma:document": "# Use tokenizers from \ud83e\udd17 Tokenizers\n\nThe [`PreTrainedTokenizerFast`] depends on the [\ud83e\udd17 Tokenizers](https://huggingface.co/docs/tokenizers) library. The tokenizers obtained from the \ud83e\udd17 Tokenizers library can be\nloaded very simply into \ud83e\udd17 Transformers.\n\nBefore getting in the specifics, let's first start by creating a dummy tokenizer in a few lines:\n\n```python\n>>> from tokenizers import Tokenizer\n>>> from tokenizers.models import BPE\n>>> from tokenizers.trainers import BpeTrainer\n>>> from tokenizers.pre_tokenizers import Whitespace\n\n>>> tokenizer = Tokenizer(BPE(unk_token=\"[UNK]\"))\n>>> trainer = BpeTrainer(special_tokens=[\"[UNK]\", \"[CLS]\", \"[SEP]\", \"[PAD]\", \"[MASK]\"])\n\n>>> tokenizer.pre_tokenizer = Whitespace()\n>>> files = [...]\n>>> tokenizer.train(files, trainer)\n```\n\nWe now have a tokenizer trained on the files we defined. We can either continue using it in that runtime, or save it to\na JSON file for future re-use.\n\n## Loading directly from the tokenizer object\n\nLet's see how to leverage this tokenizer object in the \ud83e\udd17 Transformers library. The\n[`PreTrainedTokenizerFast`] class allows for easy instantiation, by accepting the instantiated\n*tokenizer* object as an argument:\n\n```python\n>>> from transformers import PreTrainedTokenizerFast\n\n>>> fast_tokenizer = PreTrainedTokenizerFast(tokenizer_object=tokenizer)\n```\n\nThis object can now be used with all the methods shared by the \ud83e\udd17 Transformers tokenizers! Head to [the tokenizer\npage](main_classes/tokenizer) for more information.\n\n## Loading from a JSON file\n\nIn order to load a tokenizer from a JSON file, let's first start by saving our tokenizer:\n\n```python\n>>> tokenizer.save(\"tokenizer.json\")\n```\n\nThe path to which we saved this file can be passed to the [`PreTrainedTokenizerFast`] initialization\nmethod using the `tokenizer_file` parameter:\n\n```python\n>>> from transformers import PreTrainedTokenizerFast\n\n>>> fast_tokenizer = PreTrainedTokenizerFast(tokenizer_file=\"tokenizer.json\")\n```\n\nThis object can now be used with all the methods shared by the \ud83e\udd17 Transformers tokenizers! Head to [the tokenizer\npage](main_classes/tokenizer) for more information."}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 9264c7e0-6d09-468c-ba43-5af0d9a982f7
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"9264c7e0-6d09-468c-ba43-5af0d9a982f7\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/big_models\", \"title\": \"Instantiate a big model\", \"tokens\": 2428, \"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\": \"10f02487-1864-41f9-b5f6-818aa791bbc8\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/big_models\", \"title\": \"Instantiate a big model\", \"tokens\": 2428, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8d9904392ea855d641436a43c66fad3091c67b2543cf997b03e3beee5894fa31\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"8f745796-10a5-4c79-bcf0-010d59f1b059\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"307d834a2551189a814cdbd6d717b996c7187fb473ed33c102e3711946e8b00d\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 0, \"end_char_idx\": 2956, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "doc_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "ref_doc_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "chroma:document": "# Instantiate a big model\n\nA barrier to accessing very large pretrained models is the amount of memory required. When loading a pretrained PyTorch model, you usually:\n\n1. Create a model with random weights.\n2. Load your pretrained weights.\n3. Put those pretrained weights in the model.\n\nThe first two steps both require a full version of the model in memory and if the model weighs several GBs, you may not have enough memory for two copies of it. This problem is amplified in distributed training environments because each process loads a pretrained model and stores two copies in memory.\n\n> [!TIP]\n> The randomly created model is initialized with \"empty\" tensors, which take space in memory without filling it. The random values are whatever was in this chunk of memory at the time. To improve loading speed, the [`_fast_init`](https://github.com/huggingface/transformers/blob/c9f6e5e35156e068b227dd9b15521767f6afd4d2/src/transformers/modeling_utils.py#L2710) parameter is set to `True` by default to skip the random initialization for all weights that are correctly loaded.\n\nThis guide will show you how Transformers can help you load large pretrained models despite their memory requirements.\n\n## Sharded checkpoints\n\nFrom Transformers v4.18.0, a checkpoint larger than 10GB is automatically sharded by the [`~PreTrainedModel.save_pretrained`] method. It is split into several smaller partial checkpoints and creates an index file that maps parameter names to the files they're stored in.\n\nThe maximum shard size is controlled with the `max_shard_size` parameter, but by default it is 5GB, because it is easier to run on free-tier GPU instances without running out of memory.\n\nFor example, let's shard [BioMistral/BioMistral-7B](https://hf.co/BioMistral/BioMistral-7B).\n\n```py\n>>> with tempfile.TemporaryDirectory() as tmp_dir:\n...     model.save_pretrained(tmp_dir, max_shard_size=\"5GB\")\n...     print(sorted(os.listdir(tmp_dir)))\n['config.json', 'generation_config.json', 'model-00001-of-00006.safetensors', 'model-00002-of-00006.safetensors', 'model-00003-of-00006.safetensors', 'model-00004-of-00006.safetensors', 'model-00005-of-00006.safetensors', 'model-00006-of-00006.safetensors', 'model.safetensors.index.json']\n```\n\nThe sharded checkpoint is reloaded with the [`~PreTrainedModel.from_pretrained`] method.\n\n```py\n>>> with tempfile.TemporaryDirectory() as tmp_dir:\n...     model.save_pretrained(tmp_dir, max_shard_size=\"5GB\")\n...     new_model = AutoModel.from_pretrained(tmp_dir)\n```\n\nThe main advantage of sharded checkpoints for big models is that each shard is loaded after the previous one, which caps the memory usage to only the model size and the largest shard size.\n\nYou could also directly load a sharded checkpoint inside a model without the [`~PreTrainedModel.from_pretrained`] method (similar to PyTorch's `load_state_dict()` method for a full checkpoint). In this case, use the [`~modeling_utils.load_sharded_checkpoint`] method."}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 8f745796-10a5-4c79-bcf0-010d59f1b059
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"8f745796-10a5-4c79-bcf0-010d59f1b059\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/big_models\", \"title\": \"Instantiate a big model\", \"tokens\": 2428, \"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\": \"10f02487-1864-41f9-b5f6-818aa791bbc8\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/big_models\", \"title\": \"Instantiate a big model\", \"tokens\": 2428, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8d9904392ea855d641436a43c66fad3091c67b2543cf997b03e3beee5894fa31\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"9264c7e0-6d09-468c-ba43-5af0d9a982f7\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/big_models\", \"title\": \"Instantiate a big model\", \"tokens\": 2428, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"22a9f5907fc411a57b3d242e019c98a899ac357a8ca84dbd03994cfbfda78096\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"34211feb-17b4-4dee-a867-43f3cbf807e5\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"3a83534e416ea52104dd70d7214752cef93e554a1527984be51ca4347cdd1d23\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 1494, \"end_char_idx\": 4410, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "doc_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "ref_doc_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "chroma:document": "The maximum shard size is controlled with the `max_shard_size` parameter, but by default it is 5GB, because it is easier to run on free-tier GPU instances without running out of memory.\n\nFor example, let's shard [BioMistral/BioMistral-7B](https://hf.co/BioMistral/BioMistral-7B).\n\n```py\n>>> with tempfile.TemporaryDirectory() as tmp_dir:\n...     model.save_pretrained(tmp_dir, max_shard_size=\"5GB\")\n...     print(sorted(os.listdir(tmp_dir)))\n['config.json', 'generation_config.json', 'model-00001-of-00006.safetensors', 'model-00002-of-00006.safetensors', 'model-00003-of-00006.safetensors', 'model-00004-of-00006.safetensors', 'model-00005-of-00006.safetensors', 'model-00006-of-00006.safetensors', 'model.safetensors.index.json']\n```\n\nThe sharded checkpoint is reloaded with the [`~PreTrainedModel.from_pretrained`] method.\n\n```py\n>>> with tempfile.TemporaryDirectory() as tmp_dir:\n...     model.save_pretrained(tmp_dir, max_shard_size=\"5GB\")\n...     new_model = AutoModel.from_pretrained(tmp_dir)\n```\n\nThe main advantage of sharded checkpoints for big models is that each shard is loaded after the previous one, which caps the memory usage to only the model size and the largest shard size.\n\nYou could also directly load a sharded checkpoint inside a model without the [`~PreTrainedModel.from_pretrained`] method (similar to PyTorch's `load_state_dict()` method for a full checkpoint). In this case, use the [`~modeling_utils.load_sharded_checkpoint`] method.\n\n```py\n>>> from transformers.modeling_utils import load_sharded_checkpoint\n\n>>> with tempfile.TemporaryDirectory() as tmp_dir:\n...     model.save_pretrained(tmp_dir, max_shard_size=\"5GB\")\n...     load_sharded_checkpoint(model, tmp_dir)\n```\n\n### Shard metadata\n\nThe index file determines which keys are in the checkpoint and where the corresponding weights are stored. This file is loaded like any other JSON file and you can get a dictionary from it.\n\n```py\n>>> import json\n\n>>> with tempfile.TemporaryDirectory() as tmp_dir:\n...     model.save_pretrained(tmp_dir, max_shard_size=\"5GB\")\n...     with open(os.path.join(tmp_dir, \"model.safetensors.index.json\"), \"r\") as f:\n...         index = json.load(f)\n\n>>> print(index.keys())\ndict_keys(['metadata', 'weight_map'])\n```\n\nThe `metadata` key provides the total model size.\n\n```py\n>>> index[\"metadata\"]\n{'total_size': 28966928384}\n```\n\nThe `weight_map` key maps each parameter name (typically `state_dict` in a PyTorch model) to the shard it's stored in.\n\n```py\n>>> index[\"weight_map\"]\n{'lm_head.weight': 'model-00006-of-00006.safetensors',\n 'model.embed_tokens.weight': 'model-00001-of-00006.safetensors',\n 'model.layers.0.input_layernorm.weight': 'model-00001-of-00006.safetensors',\n 'model.layers.0.mlp.down_proj.weight': 'model-00001-of-00006.safetensors',\n ...\n}\n```\n\n## Accelerate's Big Model Inference\n\n> [!TIP]\n> Make sure you have Accelerate v0.9.0 or later and PyTorch v1.9.0 or later installed."}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 34211feb-17b4-4dee-a867-43f3cbf807e5
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"34211feb-17b4-4dee-a867-43f3cbf807e5\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/big_models\", \"title\": \"Instantiate a big model\", \"tokens\": 2428, \"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\": \"10f02487-1864-41f9-b5f6-818aa791bbc8\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/big_models\", \"title\": \"Instantiate a big model\", \"tokens\": 2428, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8d9904392ea855d641436a43c66fad3091c67b2543cf997b03e3beee5894fa31\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"8f745796-10a5-4c79-bcf0-010d59f1b059\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/big_models\", \"title\": \"Instantiate a big model\", \"tokens\": 2428, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"48589f229627e9e3811a3f518270a0f07aa898a46be83288517016da0e7328ed\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"0a559470-7f75-4483-8eaf-acd5158fa436\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"33428185ec02dabeda4bcdc84534e35aa8e4d0b97ff1099c0d9b757f8f1890c9\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 2958, \"end_char_idx\": 5778, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "doc_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "ref_doc_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "chroma:document": "```py\n>>> from transformers.modeling_utils import load_sharded_checkpoint\n\n>>> with tempfile.TemporaryDirectory() as tmp_dir:\n...     model.save_pretrained(tmp_dir, max_shard_size=\"5GB\")\n...     load_sharded_checkpoint(model, tmp_dir)\n```\n\n### Shard metadata\n\nThe index file determines which keys are in the checkpoint and where the corresponding weights are stored. This file is loaded like any other JSON file and you can get a dictionary from it.\n\n```py\n>>> import json\n\n>>> with tempfile.TemporaryDirectory() as tmp_dir:\n...     model.save_pretrained(tmp_dir, max_shard_size=\"5GB\")\n...     with open(os.path.join(tmp_dir, \"model.safetensors.index.json\"), \"r\") as f:\n...         index = json.load(f)\n\n>>> print(index.keys())\ndict_keys(['metadata', 'weight_map'])\n```\n\nThe `metadata` key provides the total model size.\n\n```py\n>>> index[\"metadata\"]\n{'total_size': 28966928384}\n```\n\nThe `weight_map` key maps each parameter name (typically `state_dict` in a PyTorch model) to the shard it's stored in.\n\n```py\n>>> index[\"weight_map\"]\n{'lm_head.weight': 'model-00006-of-00006.safetensors',\n 'model.embed_tokens.weight': 'model-00001-of-00006.safetensors',\n 'model.layers.0.input_layernorm.weight': 'model-00001-of-00006.safetensors',\n 'model.layers.0.mlp.down_proj.weight': 'model-00001-of-00006.safetensors',\n ...\n}\n```\n\n## Accelerate's Big Model Inference\n\n> [!TIP]\n> Make sure you have Accelerate v0.9.0 or later and PyTorch v1.9.0 or later installed.\n\nFrom Transformers v4.20.0, the [`~PreTrainedModel.from_pretrained`] method is supercharged with Accelerate's [Big Model Inference](https://hf.co/docs/accelerate/usage_guides/big_modeling) feature to efficiently handle really big models! Big Model Inference creates a *model skeleton* on PyTorch's [**meta**](https://pytorch.org/docs/main/meta.html) device. The randomly initialized parameters are only created when the pretrained weights are loaded. This way, you aren't keeping two copies of the model in memory at the same time (one for the randomly initialized model and one for the pretrained weights), and the maximum memory consumed is only the full model size.\n\nTo enable Big Model Inference in Transformers, set `low_cpu_mem_usage=True` in the [`~PreTrainedModel.from_pretrained`] method.\n\n```py\nfrom transformers import AutoModelForCausalLM\n\ngemma = AutoModelForCausalLM.from_pretrained(\"google/gemma-7b\", low_cpu_mem_usage=True)\n```\n\nAccelerate automatically dispatches the model weights across all available devices, starting with the fastest device (GPU) first and then offloading to the slower devices (CPU and even hard drive). This is enabled by setting `device_map=\"auto\"` in the [`~PreTrainedModel.from_pretrained`] method. When you pass the `device_map` parameter, `low_cpu_mem_usage` is automatically set to `True` so you don't need to specify it."}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 0a559470-7f75-4483-8eaf-acd5158fa436
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"0a559470-7f75-4483-8eaf-acd5158fa436\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/big_models\", \"title\": \"Instantiate a big model\", \"tokens\": 2428, \"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\": \"10f02487-1864-41f9-b5f6-818aa791bbc8\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/big_models\", \"title\": \"Instantiate a big model\", \"tokens\": 2428, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8d9904392ea855d641436a43c66fad3091c67b2543cf997b03e3beee5894fa31\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"34211feb-17b4-4dee-a867-43f3cbf807e5\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/big_models\", \"title\": \"Instantiate a big model\", \"tokens\": 2428, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"19eebd188b7e991ad0c0f9d954a9538c01d2e4c821bb475f94653c88f6f05ab9\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"31304479-5185-48d3-8395-d3591f147ff5\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"5da71eacd2b6a2616650ae373dac289f24dc94f7af3d268e1be91c94d3279eb5\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 4412, \"end_char_idx\": 6506, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "doc_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "ref_doc_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "chroma:document": "From Transformers v4.20.0, the [`~PreTrainedModel.from_pretrained`] method is supercharged with Accelerate's [Big Model Inference](https://hf.co/docs/accelerate/usage_guides/big_modeling) feature to efficiently handle really big models! Big Model Inference creates a *model skeleton* on PyTorch's [**meta**](https://pytorch.org/docs/main/meta.html) device. The randomly initialized parameters are only created when the pretrained weights are loaded. This way, you aren't keeping two copies of the model in memory at the same time (one for the randomly initialized model and one for the pretrained weights), and the maximum memory consumed is only the full model size.\n\nTo enable Big Model Inference in Transformers, set `low_cpu_mem_usage=True` in the [`~PreTrainedModel.from_pretrained`] method.\n\n```py\nfrom transformers import AutoModelForCausalLM\n\ngemma = AutoModelForCausalLM.from_pretrained(\"google/gemma-7b\", low_cpu_mem_usage=True)\n```\n\nAccelerate automatically dispatches the model weights across all available devices, starting with the fastest device (GPU) first and then offloading to the slower devices (CPU and even hard drive). This is enabled by setting `device_map=\"auto\"` in the [`~PreTrainedModel.from_pretrained`] method. When you pass the `device_map` parameter, `low_cpu_mem_usage` is automatically set to `True` so you don't need to specify it.\n\n```py\nfrom transformers import AutoModelForCausalLM\n\n# these loading methods are equivalent\ngemma = AutoModelForCausalLM.from_pretrained(\"google/gemma-7b\", device_map=\"auto\")\ngemma = AutoModelForCausalLM.from_pretrained(\"google/gemma-7b\", device_map=\"auto\", low_cpu_mem_usage=True)\n```\n\nYou can also write your own `device_map` by mapping each layer to a device. It should map all model parameters to a device, but you don't have to detail where all the submodules of a layer go if the entire layer is on the same device.\n\n```python\ndevice_map = {\"model.layers.1\": 0, \"model.layers.14\": 1, \"model.layers.31\": \"cpu\", \"lm_head\": \"disk\"}\n```\n\nAccess `hf_device_map` attribute to see how Accelerate split the model across devices."}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 31304479-5185-48d3-8395-d3591f147ff5
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"31304479-5185-48d3-8395-d3591f147ff5\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/big_models\", \"title\": \"Instantiate a big model\", \"tokens\": 2428, \"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\": \"10f02487-1864-41f9-b5f6-818aa791bbc8\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/big_models\", \"title\": \"Instantiate a big model\", \"tokens\": 2428, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8d9904392ea855d641436a43c66fad3091c67b2543cf997b03e3beee5894fa31\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"0a559470-7f75-4483-8eaf-acd5158fa436\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/big_models\", \"title\": \"Instantiate a big model\", \"tokens\": 2428, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"ed2cdd7e290a6aa2ff78e7380cc943772fba81db34d44fbe304944844df3e195\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"17eec031-e2cf-46fb-b62b-60d1de755063\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"a8288b8681e15a15a19a1909ab7e17ee67ae5d8f12a50bf84afe5d9cb4c21651\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 5081, \"end_char_idx\": 7740, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "doc_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "ref_doc_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "chroma:document": "To enable Big Model Inference in Transformers, set `low_cpu_mem_usage=True` in the [`~PreTrainedModel.from_pretrained`] method.\n\n```py\nfrom transformers import AutoModelForCausalLM\n\ngemma = AutoModelForCausalLM.from_pretrained(\"google/gemma-7b\", low_cpu_mem_usage=True)\n```\n\nAccelerate automatically dispatches the model weights across all available devices, starting with the fastest device (GPU) first and then offloading to the slower devices (CPU and even hard drive). This is enabled by setting `device_map=\"auto\"` in the [`~PreTrainedModel.from_pretrained`] method. When you pass the `device_map` parameter, `low_cpu_mem_usage` is automatically set to `True` so you don't need to specify it.\n\n```py\nfrom transformers import AutoModelForCausalLM\n\n# these loading methods are equivalent\ngemma = AutoModelForCausalLM.from_pretrained(\"google/gemma-7b\", device_map=\"auto\")\ngemma = AutoModelForCausalLM.from_pretrained(\"google/gemma-7b\", device_map=\"auto\", low_cpu_mem_usage=True)\n```\n\nYou can also write your own `device_map` by mapping each layer to a device. It should map all model parameters to a device, but you don't have to detail where all the submodules of a layer go if the entire layer is on the same device.\n\n```python\ndevice_map = {\"model.layers.1\": 0, \"model.layers.14\": 1, \"model.layers.31\": \"cpu\", \"lm_head\": \"disk\"}\n```\n\nAccess `hf_device_map` attribute to see how Accelerate split the model across devices.\n\n```py\ngemma.hf_device_map\n```\n\n```python out\n{'model.embed_tokens': 0,\n 'model.layers.0': 0,\n 'model.layers.1': 0,\n 'model.layers.2': 0,\n 'model.layers.3': 0,\n 'model.layers.4': 0,\n 'model.layers.5': 0,\n 'model.layers.6': 0,\n 'model.layers.7': 0,\n 'model.layers.8': 0,\n 'model.layers.9': 0,\n 'model.layers.10': 0,\n 'model.layers.11': 0,\n 'model.layers.12': 0,\n 'model.layers.13': 0,\n 'model.layers.14': 'cpu',\n 'model.layers.15': 'cpu',\n 'model.layers.16': 'cpu',\n 'model.layers.17': 'cpu',\n 'model.layers.18': 'cpu',\n 'model.layers.19': 'cpu',\n 'model.layers.20': 'cpu',\n 'model.layers.21': 'cpu',\n 'model.layers.22': 'cpu',\n 'model.layers.23': 'cpu',\n 'model.layers.24': 'cpu',\n 'model.layers.25': 'cpu',\n 'model.layers.26': 'cpu',\n 'model.layers.27': 'cpu',\n 'model.layers.28': 'cpu',\n 'model.layers.29': 'cpu',\n 'model.layers.30': 'cpu',\n 'model.layers.31': 'cpu',\n 'model.norm': 'cpu',\n 'lm_head': 'cpu'}\n```\n\n## Model data type\n\nPyTorch model weights are normally instantiated as torch.float32 and it can be an issue if you try to load a model as a different data type. For example, you'd need twice as much memory to load the weights in torch.float32 and then again to load them in your desired data type, like torch.float16."}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 17eec031-e2cf-46fb-b62b-60d1de755063
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"17eec031-e2cf-46fb-b62b-60d1de755063\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/big_models\", \"title\": \"Instantiate a big model\", \"tokens\": 2428, \"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\": \"10f02487-1864-41f9-b5f6-818aa791bbc8\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/big_models\", \"title\": \"Instantiate a big model\", \"tokens\": 2428, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8d9904392ea855d641436a43c66fad3091c67b2543cf997b03e3beee5894fa31\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"31304479-5185-48d3-8395-d3591f147ff5\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/big_models\", \"title\": \"Instantiate a big model\", \"tokens\": 2428, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"3d6fdc9576a13e90b25a43491ae4a3337ad2661c76e5844202948b585638c79e\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 6508, \"end_char_idx\": 8796, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "doc_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "ref_doc_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "chroma:document": "```py\ngemma.hf_device_map\n```\n\n```python out\n{'model.embed_tokens': 0,\n 'model.layers.0': 0,\n 'model.layers.1': 0,\n 'model.layers.2': 0,\n 'model.layers.3': 0,\n 'model.layers.4': 0,\n 'model.layers.5': 0,\n 'model.layers.6': 0,\n 'model.layers.7': 0,\n 'model.layers.8': 0,\n 'model.layers.9': 0,\n 'model.layers.10': 0,\n 'model.layers.11': 0,\n 'model.layers.12': 0,\n 'model.layers.13': 0,\n 'model.layers.14': 'cpu',\n 'model.layers.15': 'cpu',\n 'model.layers.16': 'cpu',\n 'model.layers.17': 'cpu',\n 'model.layers.18': 'cpu',\n 'model.layers.19': 'cpu',\n 'model.layers.20': 'cpu',\n 'model.layers.21': 'cpu',\n 'model.layers.22': 'cpu',\n 'model.layers.23': 'cpu',\n 'model.layers.24': 'cpu',\n 'model.layers.25': 'cpu',\n 'model.layers.26': 'cpu',\n 'model.layers.27': 'cpu',\n 'model.layers.28': 'cpu',\n 'model.layers.29': 'cpu',\n 'model.layers.30': 'cpu',\n 'model.layers.31': 'cpu',\n 'model.norm': 'cpu',\n 'lm_head': 'cpu'}\n```\n\n## Model data type\n\nPyTorch model weights are normally instantiated as torch.float32 and it can be an issue if you try to load a model as a different data type. For example, you'd need twice as much memory to load the weights in torch.float32 and then again to load them in your desired data type, like torch.float16.\n\n> [!WARNING]\n> Due to how PyTorch is designed, the `torch_dtype` parameter only supports floating data types.\n\nTo avoid wasting memory like this, explicitly set the `torch_dtype` parameter to the desired data type or set `torch_dtype=\"auto\"` to load the weights with the most optimal memory pattern (the data type is automatically derived from the model weights).\n\n<hfoptions id=\"dtype\">\n<hfoption id=\"specific dtype\">\n\n```py\nfrom transformers import AutoModelForCausalLM\n\ngemma = AutoModelForCausalLM.from_pretrained(\"google/gemma-7b\", torch_dtype=torch.float16)\n```\n\n</hfoption>\n<hfoption id=\"auto dtype\">\n\n```py\nfrom transformers import AutoModelForCausalLM\n\ngemma = AutoModelForCausalLM.from_pretrained(\"google/gemma-7b\", torch_dtype=\"auto\")\n```\n\n</hfoption>\n</hfoptions>\n\nYou can also set the data type to use for models instantiated from scratch.\n\n```python\nimport torch\nfrom transformers import AutoConfig, AutoModel\n\nmy_config = AutoConfig.from_pretrained(\"google/gemma-2b\", torch_dtype=torch.float16)\nmodel = AutoModel.from_config(my_config)\n```"}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 61e72a16-0e60-4bc1-9c51-1b566904b648
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_train_cpu", "title": "Efficient Training on CPU", "tokens": 1030, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"61e72a16-0e60-4bc1-9c51-1b566904b648\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_cpu\", \"title\": \"Efficient Training on CPU\", \"tokens\": 1030, \"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\": \"83e838eb-4ed0-48c1-8501-ad259f18be43\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_cpu\", \"title\": \"Efficient Training on CPU\", \"tokens\": 1030, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"9cf35ef5d0afabfdc2fa3de693087687937c1bc83ce588496b4164d3d9eacf44\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"c83e1978-6631-4da0-b37d-0e899232cf60\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"d7817ae648cddb6ceaf938eb071ecf9a363d0b06bb37ba59678f7b7702b75219\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 0, \"end_char_idx\": 2416, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "83e838eb-4ed0-48c1-8501-ad259f18be43", "doc_id": "83e838eb-4ed0-48c1-8501-ad259f18be43", "ref_doc_id": "83e838eb-4ed0-48c1-8501-ad259f18be43", "chroma:document": "# Efficient Training on CPU\n\nThis guide focuses on training large models efficiently on CPU.\n\n## Mixed precision with IPEX\nMixed precision uses single (fp32) and half-precision (bf16/fp16) data types in a model to accelerate training or inference while still preserving much of the single-precision accuracy. Modern CPUs such as 3rd and 4th Gen Intel\u00ae Xeon\u00ae Scalable processors natively support bf16, so you should get more performance out of the box by enabling mixed precision training with bf16.\n\nTo further maximize training performance, you can use Intel\u00ae Extension for PyTorch (IPEX), which is a library built on PyTorch and adds additional CPU instruction level architecture (ISA) level support such as Intel\u00ae Advanced Vector Extensions 512 Vector Neural Network Instructions (Intel\u00ae AVX512-VNNI), and Intel\u00ae Advanced Matrix Extensions (Intel\u00ae AMX) for an extra performance boost on Intel CPUs. However, CPUs with only AVX2 (e.g., AMD or older Intel CPUs) are not guaranteed to have better performance under IPEX.\n\nAuto Mixed Precision (AMP) for CPU backends has been enabled since PyTorch 1.10. AMP support for bf16 on CPUs and bf16 operator optimization is also supported in IPEX and partially upstreamed to the main PyTorch branch. You can get better performance and user experience with IPEX AMP.\n\nCheck more detailed information for [Auto Mixed Precision](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/features/amp.html).\n\n### IPEX installation:\n\nIPEX release is following PyTorch, to install via pip:\n\n| PyTorch Version   | IPEX version   |\n| :---------------: | :----------:   |\n| 2.1.x             |  2.1.100+cpu   |\n| 2.0.x             |  2.0.100+cpu   |\n| 1.13              |  1.13.0+cpu    |\n| 1.12              |  1.12.300+cpu  |\n\nPlease run `pip list | grep torch` to get your `pytorch_version`, so you can get the `IPEX version_name`.\n```bash\npip install intel_extension_for_pytorch==<version_name> -f https://developer.intel.com/ipex-whl-stable-cpu\n```\nYou can check the latest versions in [ipex-whl-stable-cpu](https://developer.intel.com/ipex-whl-stable-cpu) if needed.\n\nCheck more approaches for [IPEX installation](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/installation.html).\n\n### Usage in Trainer\nTo enable auto mixed precision with IPEX in Trainer, users should add `use_ipex`, `bf16` and `no_cuda` in training command arguments."}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: c83e1978-6631-4da0-b37d-0e899232cf60
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/perf_train_cpu", "title": "Efficient Training on CPU", "tokens": 1030, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"c83e1978-6631-4da0-b37d-0e899232cf60\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_cpu\", \"title\": \"Efficient Training on CPU\", \"tokens\": 1030, \"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\": \"83e838eb-4ed0-48c1-8501-ad259f18be43\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_cpu\", \"title\": \"Efficient Training on CPU\", \"tokens\": 1030, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"9cf35ef5d0afabfdc2fa3de693087687937c1bc83ce588496b4164d3d9eacf44\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"61e72a16-0e60-4bc1-9c51-1b566904b648\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/perf_train_cpu\", \"title\": \"Efficient Training on CPU\", \"tokens\": 1030, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"8aea4a1488679e7f887a1bcf49c8790691cb526bed67f05da813f7f2de6be12e\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 1022, \"end_char_idx\": 3388, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "83e838eb-4ed0-48c1-8501-ad259f18be43", "doc_id": "83e838eb-4ed0-48c1-8501-ad259f18be43", "ref_doc_id": "83e838eb-4ed0-48c1-8501-ad259f18be43", "chroma:document": "Auto Mixed Precision (AMP) for CPU backends has been enabled since PyTorch 1.10. AMP support for bf16 on CPUs and bf16 operator optimization is also supported in IPEX and partially upstreamed to the main PyTorch branch. You can get better performance and user experience with IPEX AMP.\n\nCheck more detailed information for [Auto Mixed Precision](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/features/amp.html).\n\n### IPEX installation:\n\nIPEX release is following PyTorch, to install via pip:\n\n| PyTorch Version   | IPEX version   |\n| :---------------: | :----------:   |\n| 2.1.x             |  2.1.100+cpu   |\n| 2.0.x             |  2.0.100+cpu   |\n| 1.13              |  1.13.0+cpu    |\n| 1.12              |  1.12.300+cpu  |\n\nPlease run `pip list | grep torch` to get your `pytorch_version`, so you can get the `IPEX version_name`.\n```bash\npip install intel_extension_for_pytorch==<version_name> -f https://developer.intel.com/ipex-whl-stable-cpu\n```\nYou can check the latest versions in [ipex-whl-stable-cpu](https://developer.intel.com/ipex-whl-stable-cpu) if needed.\n\nCheck more approaches for [IPEX installation](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/installation.html).\n\n### Usage in Trainer\nTo enable auto mixed precision with IPEX in Trainer, users should add `use_ipex`, `bf16` and `no_cuda` in training command arguments.\n\nTake an example of the use cases on [Transformers question-answering](https://github.com/huggingface/transformers/tree/main/examples/pytorch/question-answering)\n\n- Training with IPEX using BF16 auto mixed precision on CPU:\n<pre> python run_qa.py \\\n--model_name_or_path google-bert/bert-base-uncased \\\n--dataset_name squad \\\n--do_train \\\n--do_eval \\\n--per_device_train_batch_size 12 \\\n--learning_rate 3e-5 \\\n--num_train_epochs 2 \\\n--max_seq_length 384 \\\n--doc_stride 128 \\\n--output_dir /tmp/debug_squad/ \\\n<b>--use_ipex</b> \\\n<b>--bf16</b> \\\n<b>--use_cpu</b></pre> \n\nIf you want to enable `use_ipex` and `bf16` in your script, add these parameters to `TrainingArguments` like this:\n```diff\ntraining_args = TrainingArguments(\n    output_dir=args.output_path,\n+   bf16=True,\n+   use_ipex=True,\n+   use_cpu=True,\n    **kwargs\n)\n```\n\n### Practice example\n\nBlog: [Accelerating PyTorch Transformers with Intel Sapphire Rapids](https://huggingface.co/blog/intel-sapphire-rapids)"}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: e91e6d86-7506-4c36-9881-b2e58ae53de6
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_\": \"e91e6d86-7506-4c36-9881-b2e58ae53de6\", \"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\": \"5c302e90-7ccc-4394-ae4b-e45a8a5f2785\", \"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\"}, \"3\": {\"node_id\": \"559c77c7-bef3-4470-bf35-e21753f5b5c4\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"a845e3149d86d83647d66043ab64e895bc7b5431910b689f480a7f7a2811a68e\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 0, \"end_char_idx\": 3120, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "5c302e90-7ccc-4394-ae4b-e45a8a5f2785", "doc_id": "5c302e90-7ccc-4394-ae4b-e45a8a5f2785", "ref_doc_id": "5c302e90-7ccc-4394-ae4b-e45a8a5f2785", "chroma:document": "<!---\nCopyright 2023 The HuggingFace Team. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n-->\n\n# Model training anatomy\n\nTo understand performance optimization techniques that one can apply to improve efficiency of model training \nspeed and memory utilization, it's helpful to get familiar with how GPU is utilized during training, and how compute \nintensity varies depending on an operation performed.\n\nLet's start by exploring a motivating example of GPU utilization and the training run of a model. For the demonstration, \nwe'll need to install a few libraries: \n\n```bash\npip install transformers datasets accelerate nvidia-ml-py3\n```\n\nThe `nvidia-ml-py3` library allows us to monitor the memory usage of the models from within Python. You might be familiar \nwith the `nvidia-smi` command in the terminal - this library allows to access the same information in Python directly.\n\nThen, we create some dummy data: random token IDs between 100 and 30000 and binary labels for a classifier. \nIn total, we get 512 sequences each with length 512 and store them in a [`~datasets.Dataset`] with PyTorch format.\n\n\n```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"}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 559c77c7-bef3-4470-bf35-e21753f5b5c4
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_\": \"559c77c7-bef3-4470-bf35-e21753f5b5c4\", \"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\": \"5c302e90-7ccc-4394-ae4b-e45a8a5f2785\", \"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\": \"e91e6d86-7506-4c36-9881-b2e58ae53de6\", \"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\": \"3acb1b8d-9a71-4ad1-825a-6c0ced816492\", \"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": "5c302e90-7ccc-4394-ae4b-e45a8a5f2785", "doc_id": "5c302e90-7ccc-4394-ae4b-e45a8a5f2785", "ref_doc_id": "5c302e90-7ccc-4394-ae4b-e45a8a5f2785", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 3acb1b8d-9a71-4ad1-825a-6c0ced816492
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_\": \"3acb1b8d-9a71-4ad1-825a-6c0ced816492\", \"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\": \"5c302e90-7ccc-4394-ae4b-e45a8a5f2785\", \"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\": \"559c77c7-bef3-4470-bf35-e21753f5b5c4\", \"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\": \"338acab8-60cd-457d-bc01-185581232dd6\", \"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": "5c302e90-7ccc-4394-ae4b-e45a8a5f2785", "doc_id": "5c302e90-7ccc-4394-ae4b-e45a8a5f2785", "ref_doc_id": "5c302e90-7ccc-4394-ae4b-e45a8a5f2785", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 338acab8-60cd-457d-bc01-185581232dd6
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_\": \"338acab8-60cd-457d-bc01-185581232dd6\", \"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\": \"5c302e90-7ccc-4394-ae4b-e45a8a5f2785\", \"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\": \"3acb1b8d-9a71-4ad1-825a-6c0ced816492\", \"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\": \"178a5c53-2265-477f-84d6-53cc417e6127\", \"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": "5c302e90-7ccc-4394-ae4b-e45a8a5f2785", "doc_id": "5c302e90-7ccc-4394-ae4b-e45a8a5f2785", "ref_doc_id": "5c302e90-7ccc-4394-ae4b-e45a8a5f2785", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 178a5c53-2265-477f-84d6-53cc417e6127
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_\": \"178a5c53-2265-477f-84d6-53cc417e6127\", \"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\": \"5c302e90-7ccc-4394-ae4b-e45a8a5f2785\", \"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\": \"338acab8-60cd-457d-bc01-185581232dd6\", \"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": "5c302e90-7ccc-4394-ae4b-e45a8a5f2785", "doc_id": "5c302e90-7ccc-4394-ae4b-e45a8a5f2785", "ref_doc_id": "5c302e90-7ccc-4394-ae4b-e45a8a5f2785", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 102b47df-d842-4013-a864-448c2c043a01
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_\": \"102b47df-d842-4013-a864-448c2c043a01\", \"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\": \"720d90e9-5e84-405a-be21-75132ee4bc56\", \"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\": \"1938e98c-6bb0-4906-ba57-e7e1b726535a\", \"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": "720d90e9-5e84-405a-be21-75132ee4bc56", "doc_id": "720d90e9-5e84-405a-be21-75132ee4bc56", "ref_doc_id": "720d90e9-5e84-405a-be21-75132ee4bc56", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 1938e98c-6bb0-4906-ba57-e7e1b726535a
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_\": \"1938e98c-6bb0-4906-ba57-e7e1b726535a\", \"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\": \"720d90e9-5e84-405a-be21-75132ee4bc56\", \"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\": \"102b47df-d842-4013-a864-448c2c043a01\", \"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\": \"1e36de2d-48dd-4bc3-83e0-5905ac608d04\", \"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": "720d90e9-5e84-405a-be21-75132ee4bc56", "doc_id": "720d90e9-5e84-405a-be21-75132ee4bc56", "ref_doc_id": "720d90e9-5e84-405a-be21-75132ee4bc56", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 1e36de2d-48dd-4bc3-83e0-5905ac608d04
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_\": \"1e36de2d-48dd-4bc3-83e0-5905ac608d04\", \"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\": \"720d90e9-5e84-405a-be21-75132ee4bc56\", \"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\": \"1938e98c-6bb0-4906-ba57-e7e1b726535a\", \"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\": \"b673b162-c667-4e47-b76f-f3cfb79b495c\", \"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": "720d90e9-5e84-405a-be21-75132ee4bc56", "doc_id": "720d90e9-5e84-405a-be21-75132ee4bc56", "ref_doc_id": "720d90e9-5e84-405a-be21-75132ee4bc56", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: b673b162-c667-4e47-b76f-f3cfb79b495c
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_\": \"b673b162-c667-4e47-b76f-f3cfb79b495c\", \"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\": \"720d90e9-5e84-405a-be21-75132ee4bc56\", \"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\": \"1e36de2d-48dd-4bc3-83e0-5905ac608d04\", \"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": "720d90e9-5e84-405a-be21-75132ee4bc56", "doc_id": "720d90e9-5e84-405a-be21-75132ee4bc56", "ref_doc_id": "720d90e9-5e84-405a-be21-75132ee4bc56", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: fa85588b-bfcd-4b5f-865f-23c34bc25726
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"fa85588b-bfcd-4b5f-865f-23c34bc25726\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"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\": \"1c0c2e70-0214-4869-b53f-874503acf230\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"d23e43e0-6b77-4c19-98f5-3ddae52e1897\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"501f5bb903ee0f797ed242e6f91fe24835c84f21825d678f28893455bf41fbe6\", \"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": "1c0c2e70-0214-4869-b53f-874503acf230", "doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "ref_doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: d23e43e0-6b77-4c19-98f5-3ddae52e1897
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"d23e43e0-6b77-4c19-98f5-3ddae52e1897\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"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\": \"1c0c2e70-0214-4869-b53f-874503acf230\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"fa85588b-bfcd-4b5f-865f-23c34bc25726\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"350fb663e3d59c953674aaf34977431129496cdfcf69353276fe3e667b9f4fce\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"3db0f83d-aeb3-48bc-bce8-85f1d3d7cad7\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"2665a91562ceb5f74c6f081d64e3da8eb37ba50b53239841fe798c73792b73c8\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 1755, \"end_char_idx\": 4973, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "1c0c2e70-0214-4869-b53f-874503acf230", "doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "ref_doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "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.\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) (`List[Dict[str, str]]`) for its input `messages`, and it returns a `str`."}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 3db0f83d-aeb3-48bc-bce8-85f1d3d7cad7
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"3db0f83d-aeb3-48bc-bce8-85f1d3d7cad7\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"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\": \"1c0c2e70-0214-4869-b53f-874503acf230\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"d23e43e0-6b77-4c19-98f5-3ddae52e1897\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"9095a397bca2e06c2ea753cc46da092253cd7551672de8d185e161621c271371\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"b0064cc7-889a-451a-bc9c-71728a948d8b\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"1f4d16157609a2784bc904746ce358e2e02a167e259da37dec98eda9fd80bdef\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 3422, \"end_char_idx\": 6641, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "1c0c2e70-0214-4869-b53f-874503acf230", "doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "ref_doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "chroma:document": "To 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) (`List[Dict[str, str]]`) for its input `messages`, and it returns a `str`.\n2. it stops generating outputs at the sequences passed in the argument `stop_sequences`\n\nAdditionally, `llm_engine` can also take a `grammar` argument. In the case where you specify a `grammar` upon agent initialization, this argument will be passed to the calls to llm_engine, with the `grammar` that you defined upon initialization, to allow [constrained generation](https://huggingface.co/docs/text-generation-inference/conceptual/guidance) in order to force properly-formatted agent outputs.\n\nYou will also need a `tools` argument which accepts a list of `Tools` - it can be an empty list. You can also add the default toolbox on top of your `tools` list by defining 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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: b0064cc7-889a-451a-bc9c-71728a948d8b
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"b0064cc7-889a-451a-bc9c-71728a948d8b\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"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\": \"1c0c2e70-0214-4869-b53f-874503acf230\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"3db0f83d-aeb3-48bc-bce8-85f1d3d7cad7\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"b36da4476d107ddc43db237a7316a36f42f04449ca3abfb0076665f1f5090f54\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"8a847532-70b6-4909-a1bc-be7eb392374d\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"ed4f3cb2d18dc78fcd419774d2907c39000d939a6208ac94a01e4f19ec9cdd07\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 5126, \"end_char_idx\": 8202, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "1c0c2e70-0214-4869-b53f-874503acf230", "doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "ref_doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "chroma:document": "In the case where you specify a `grammar` upon agent initialization, this argument will be passed to the calls to llm_engine, with the `grammar` that you defined upon initialization, to allow [constrained generation](https://huggingface.co/docs/text-generation-inference/conceptual/guidance) in order to force properly-formatted agent outputs.\n\nYou will also need a `tools` argument which accepts a list of `Tools` - it can be an empty list. You can also add the default toolbox on top of your `tools` list by defining 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."}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 8a847532-70b6-4909-a1bc-be7eb392374d
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"8a847532-70b6-4909-a1bc-be7eb392374d\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"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\": \"1c0c2e70-0214-4869-b53f-874503acf230\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"b0064cc7-889a-451a-bc9c-71728a948d8b\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"5603cb6d0030f020f8412288b9661ed8adff63ea6703f1938481e63876cec82c\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"b581a76a-4bff-4704-b88e-38fa917e4148\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"8b2519f77ed1939868b536fb51ca8364083a7303e4e72aefed805c062ba4f6b4\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 6390, \"end_char_idx\": 9884, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "1c0c2e70-0214-4869-b53f-874503acf230", "doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "ref_doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "chroma:document": "```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!\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."}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: b581a76a-4bff-4704-b88e-38fa917e4148
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"b581a76a-4bff-4704-b88e-38fa917e4148\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"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\": \"1c0c2e70-0214-4869-b53f-874503acf230\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"8a847532-70b6-4909-a1bc-be7eb392374d\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"65830ef04850d82e02fb5fcbbff46676fff5c0c1849c835587ca59bdf1e075cd\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"54377bb2-7927-4b50-8f22-8bd7528f7c52\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"1597e91ac735ab511aae250004f9ecdecaef8ffb28aeb16142116aed2af5f0f9\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 8063, \"end_char_idx\": 11554, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "1c0c2e70-0214-4869-b53f-874503acf230", "doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "ref_doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "chroma:document": "The 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!\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."}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 54377bb2-7927-4b50-8f22-8bd7528f7c52
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"54377bb2-7927-4b50-8f22-8bd7528f7c52\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"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\": \"1c0c2e70-0214-4869-b53f-874503acf230\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"b581a76a-4bff-4704-b88e-38fa917e4148\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"350706ddccf45944cfff22f9942b25a5c72bc5f119d437a75fc4fdc9c009455e\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"e147e675-05de-4855-9b53-33e4a95cba77\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"910a6b9dabc332606eed91decb9a5bb857238f301fb1013279bc3652aa737a24\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 9719, \"end_char_idx\": 11911, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "1c0c2e70-0214-4869-b53f-874503acf230", "doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "ref_doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "chroma:document": "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: e147e675-05de-4855-9b53-33e4a95cba77
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"e147e675-05de-4855-9b53-33e4a95cba77\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"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\": \"1c0c2e70-0214-4869-b53f-874503acf230\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"54377bb2-7927-4b50-8f22-8bd7528f7c52\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"c9694a8fe95d473ace400c2c6164356df1c166d13fb60291a5b2154963993df5\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"befcdcbc-cd6a-4870-9fda-d0795ede876d\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"529c68a103c37035bd58003dba137a840a96e7af9fc865412e7a0b90fdfc313e\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 10090, \"end_char_idx\": 14127, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "1c0c2e70-0214-4869-b53f-874503acf230", "doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "ref_doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: befcdcbc-cd6a-4870-9fda-d0795ede876d
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"befcdcbc-cd6a-4870-9fda-d0795ede876d\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"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\": \"1c0c2e70-0214-4869-b53f-874503acf230\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"e147e675-05de-4855-9b53-33e4a95cba77\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"46f4e8a1057b233d3b6725b9caa7f1e6ac4055f5d0f6ced502145eab486ac70d\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"bf70c751-eaf1-461d-a6d3-4ce22611aff7\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"88476ff75c52c41a13390e4d1645b6bf50bc75b63a8097f11c4754d11ced2406\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 14130, \"end_char_idx\": 16343, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "1c0c2e70-0214-4869-b53f-874503acf230", "doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "ref_doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: bf70c751-eaf1-461d-a6d3-4ce22611aff7
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"bf70c751-eaf1-461d-a6d3-4ce22611aff7\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"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\": \"1c0c2e70-0214-4869-b53f-874503acf230\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"befcdcbc-cd6a-4870-9fda-d0795ede876d\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"f57a82eb2944acac28d7c71b3c68d70c2909913440b35d01e27a51193bd19aaa\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"d46cb6b6-acf3-4f1e-982b-d370ecbc06f8\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"b135bc356bee18b528c1d4046da4f95d0702bda3910087f66f1b092548c14379\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 14876, \"end_char_idx\": 17635, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "1c0c2e70-0214-4869-b53f-874503acf230", "doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "ref_doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: d46cb6b6-acf3-4f1e-982b-d370ecbc06f8
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"d46cb6b6-acf3-4f1e-982b-d370ecbc06f8\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"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\": \"1c0c2e70-0214-4869-b53f-874503acf230\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"bf70c751-eaf1-461d-a6d3-4ce22611aff7\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"65211203ec8a8007c69de014253072d3562478c05246889783bec97b9c8bbfd2\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"e161650d-62d7-4802-a049-e42baf3b9a35\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"2c8c16a8a1470e35526a92a91bcbb35c86b892c3738273e1aecd3a7ec652c881\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 16346, \"end_char_idx\": 19459, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "1c0c2e70-0214-4869-b53f-874503acf230", "doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "ref_doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: e161650d-62d7-4802-a049-e42baf3b9a35
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"e161650d-62d7-4802-a049-e42baf3b9a35\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"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\": \"1c0c2e70-0214-4869-b53f-874503acf230\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"d46cb6b6-acf3-4f1e-982b-d370ecbc06f8\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"7cb9230d0a21e7ae1d8c1d64b041b11d2ad87a71ab60e71728b226cbf8cea4dc\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"5c03b3ca-989d-404f-af61-51d97529e407\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"b62fb82e1bdbd6ed7f0ddd97846387ecc4e088ee0ea82873ccaf71b598459f8e\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 17638, \"end_char_idx\": 20232, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "1c0c2e70-0214-4869-b53f-874503acf230", "doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "ref_doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 5c03b3ca-989d-404f-af61-51d97529e407
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"5c03b3ca-989d-404f-af61-51d97529e407\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"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\": \"1c0c2e70-0214-4869-b53f-874503acf230\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"e161650d-62d7-4802-a049-e42baf3b9a35\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"ebaf60a29b68f89d9b47de7cadad67bce49b22bf1743eef4bdef5180791ca0a2\", \"class_name\": \"RelatedNodeInfo\"}, \"3\": {\"node_id\": \"a719172d-8d54-423c-9146-e8d835007b9c\", \"node_type\": \"1\", \"metadata\": {}, \"hash\": \"c52582f0ab502898913258573e0d52cfa28289fd6acbedd3444c6874bc0e9e46\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 18403, \"end_char_idx\": 22217, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "1c0c2e70-0214-4869-b53f-874503acf230", "doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "ref_doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: a719172d-8d54-423c-9146-e8d835007b9c
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"a719172d-8d54-423c-9146-e8d835007b9c\", \"embedding\": null, \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"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\": \"1c0c2e70-0214-4869-b53f-874503acf230\", \"node_type\": \"4\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050\", \"class_name\": \"RelatedNodeInfo\"}, \"2\": {\"node_id\": \"5c03b3ca-989d-404f-af61-51d97529e407\", \"node_type\": \"1\", \"metadata\": {\"url\": \"https://huggingface.co/docs/transformers/agents\", \"title\": \"Agents and tools\", \"tokens\": 5612, \"retrieve_doc\": true, \"source\": \"transformers\"}, \"hash\": \"dddbe7e9f4a3fe4987110aa5b1e8254a8a4284bfd03754981ae869fad4dd525a\", \"class_name\": \"RelatedNodeInfo\"}}, \"text\": \"\", \"mimetype\": \"text/plain\", \"start_char_idx\": 22220, \"end_char_idx\": 24452, \"text_template\": \"{metadata_str}\\n\\n{content}\", \"metadata_template\": \"{key}: {value}\", \"metadata_seperator\": \"\\n\", \"class_name\": \"TextNode\"}", "_node_type": "TextNode", "document_id": "1c0c2e70-0214-4869-b53f-874503acf230", "doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "ref_doc_id": "1c0c2e70-0214-4869-b53f-874503acf230", "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```\n\n## Gradio interface\n\nYou can leverage `gradio.Chatbot`to display your agent's thoughts using `stream_to_gradio`, here is an example:\n\n```py\nimport gradio as gr\nfrom transformers import (\n    load_tool,\n    ReactCodeAgent,\n    HfEngine,\n    stream_to_gradio,\n)\n\n# Import tool from Hub\nimage_generation_tool = load_tool(\"m-ric/text-to-image\")\n\nllm_engine = HfEngine(\"meta-llama/Meta-Llama-3-70B-Instruct\")\n\n# Initialize the agent with the image generation tool\nagent = ReactCodeAgent(tools=[image_generation_tool], llm_engine=llm_engine)\n\n\ndef interact_with_agent(task):\n    messages = []\n    messages.append(gr.ChatMessage(role=\"user\", content=task))\n    yield messages\n    for msg in stream_to_gradio(agent, task):\n        messages.append(msg)\n        yield messages + [\n            gr.ChatMessage(role=\"assistant\", content=\"\u23f3 Task not finished yet!\")\n        ]\n    yield messages\n\n\nwith gr.Blocks() as demo:\n    text_input = gr.Textbox(lines=1, label=\"Chat Message\", value=\"Make me a picture of the Statue of Liberty.\")\n    submit = gr.Button(\"Run illustrator agent!\")\n    chatbot = gr.Chatbot(\n        label=\"Agent\",\n        type=\"messages\",\n        avatar_images=(\n            None,\n            \"https://em-content.zobj.net/source/twitter/53/robot-face_1f916.png\",\n        ),\n    )\n    submit.click(interact_with_agent, [text_input], [chatbot])\n\nif __name__ == \"__main__\":\n    demo.launch()\n```"}


created_at: 2024-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 911e88e9-7449-4da9-b721-8eb3ac97debd
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/philosophy", "title": "Philosophy", "tokens": 1289, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"911e88e9-7449-4da9-b721-8eb3ac97debd\", \"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\": \"69bbd021-3897-49b6-960b-126ed07d82f5\", \"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\": \"724d0800-7a7d-47ba-8548-3fb6ffc5fbc1\", \"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": "69bbd021-3897-49b6-960b-126ed07d82f5", "doc_id": "69bbd021-3897-49b6-960b-126ed07d82f5", "ref_doc_id": "69bbd021-3897-49b6-960b-126ed07d82f5", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 724d0800-7a7d-47ba-8548-3fb6ffc5fbc1
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/philosophy", "title": "Philosophy", "tokens": 1289, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"724d0800-7a7d-47ba-8548-3fb6ffc5fbc1\", \"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\": \"69bbd021-3897-49b6-960b-126ed07d82f5\", \"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\": \"911e88e9-7449-4da9-b721-8eb3ac97debd\", \"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\": \"e59aabf3-4d74-4b41-8299-6af54d91eab0\", \"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": "69bbd021-3897-49b6-960b-126ed07d82f5", "doc_id": "69bbd021-3897-49b6-960b-126ed07d82f5", "ref_doc_id": "69bbd021-3897-49b6-960b-126ed07d82f5", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: e59aabf3-4d74-4b41-8299-6af54d91eab0
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/philosophy", "title": "Philosophy", "tokens": 1289, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"e59aabf3-4d74-4b41-8299-6af54d91eab0\", \"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\": \"69bbd021-3897-49b6-960b-126ed07d82f5\", \"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\": \"724d0800-7a7d-47ba-8548-3fb6ffc5fbc1\", \"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": "69bbd021-3897-49b6-960b-126ed07d82f5", "doc_id": "69bbd021-3897-49b6-960b-126ed07d82f5", "ref_doc_id": "69bbd021-3897-49b6-960b-126ed07d82f5", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 3a69fa31-c1f5-4b84-990d-de400039520e
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_\": \"3a69fa31-c1f5-4b84-990d-de400039520e\", \"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\": \"12eaf971-4b8a-42e8-a00c-b9efcc38a687\", \"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\": \"eb8869e4-62d6-44e1-966a-1cf715e6d530\", \"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": "12eaf971-4b8a-42e8-a00c-b9efcc38a687", "doc_id": "12eaf971-4b8a-42e8-a00c-b9efcc38a687", "ref_doc_id": "12eaf971-4b8a-42e8-a00c-b9efcc38a687", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: eb8869e4-62d6-44e1-966a-1cf715e6d530
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_\": \"eb8869e4-62d6-44e1-966a-1cf715e6d530\", \"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\": \"12eaf971-4b8a-42e8-a00c-b9efcc38a687\", \"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\": \"3a69fa31-c1f5-4b84-990d-de400039520e\", \"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\": \"30426ae9-fe62-43ff-979f-df5d592a3253\", \"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": "12eaf971-4b8a-42e8-a00c-b9efcc38a687", "doc_id": "12eaf971-4b8a-42e8-a00c-b9efcc38a687", "ref_doc_id": "12eaf971-4b8a-42e8-a00c-b9efcc38a687", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 30426ae9-fe62-43ff-979f-df5d592a3253
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_\": \"30426ae9-fe62-43ff-979f-df5d592a3253\", \"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\": \"12eaf971-4b8a-42e8-a00c-b9efcc38a687\", \"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\": \"eb8869e4-62d6-44e1-966a-1cf715e6d530\", \"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\": \"64fed5eb-7799-4f92-8aaa-5c9bcba8e73e\", \"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": "12eaf971-4b8a-42e8-a00c-b9efcc38a687", "doc_id": "12eaf971-4b8a-42e8-a00c-b9efcc38a687", "ref_doc_id": "12eaf971-4b8a-42e8-a00c-b9efcc38a687", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 64fed5eb-7799-4f92-8aaa-5c9bcba8e73e
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_\": \"64fed5eb-7799-4f92-8aaa-5c9bcba8e73e\", \"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\": \"12eaf971-4b8a-42e8-a00c-b9efcc38a687\", \"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\": \"30426ae9-fe62-43ff-979f-df5d592a3253\", \"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\": \"13b0f9dd-82e7-4700-8633-7a81aa876e01\", \"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": "12eaf971-4b8a-42e8-a00c-b9efcc38a687", "doc_id": "12eaf971-4b8a-42e8-a00c-b9efcc38a687", "ref_doc_id": "12eaf971-4b8a-42e8-a00c-b9efcc38a687", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 13b0f9dd-82e7-4700-8633-7a81aa876e01
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_\": \"13b0f9dd-82e7-4700-8633-7a81aa876e01\", \"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\": \"12eaf971-4b8a-42e8-a00c-b9efcc38a687\", \"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\": \"64fed5eb-7799-4f92-8aaa-5c9bcba8e73e\", \"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": "12eaf971-4b8a-42e8-a00c-b9efcc38a687", "doc_id": "12eaf971-4b8a-42e8-a00c-b9efcc38a687", "ref_doc_id": "12eaf971-4b8a-42e8-a00c-b9efcc38a687", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 3bd6c9dd-1b49-4528-9aac-6867fe011133
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_\": \"3bd6c9dd-1b49-4528-9aac-6867fe011133\", \"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\": \"7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef\", \"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\": \"84dda9bd-af68-45ef-9c66-8aa184ae269f\", \"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": "7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef", "doc_id": "7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef", "ref_doc_id": "7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 84dda9bd-af68-45ef-9c66-8aa184ae269f
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_\": \"84dda9bd-af68-45ef-9c66-8aa184ae269f\", \"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\": \"7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef\", \"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\": \"3bd6c9dd-1b49-4528-9aac-6867fe011133\", \"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\": \"0d9aee63-b27b-4d28-83e7-97ca97b403c5\", \"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": "7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef", "doc_id": "7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef", "ref_doc_id": "7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 0d9aee63-b27b-4d28-83e7-97ca97b403c5
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_\": \"0d9aee63-b27b-4d28-83e7-97ca97b403c5\", \"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\": \"7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef\", \"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\": \"84dda9bd-af68-45ef-9c66-8aa184ae269f\", \"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\": \"dabf0ce9-9eea-45d5-aefd-a02b8c3b3f80\", \"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": "7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef", "doc_id": "7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef", "ref_doc_id": "7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: dabf0ce9-9eea-45d5-aefd-a02b8c3b3f80
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_\": \"dabf0ce9-9eea-45d5-aefd-a02b8c3b3f80\", \"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\": \"7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef\", \"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\": \"0d9aee63-b27b-4d28-83e7-97ca97b403c5\", \"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\": \"439b225d-1a32-4d80-ac79-281f6295275d\", \"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": "7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef", "doc_id": "7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef", "ref_doc_id": "7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 439b225d-1a32-4d80-ac79-281f6295275d
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_\": \"439b225d-1a32-4d80-ac79-281f6295275d\", \"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\": \"7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef\", \"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\": \"dabf0ce9-9eea-45d5-aefd-a02b8c3b3f80\", \"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": "7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef", "doc_id": "7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef", "ref_doc_id": "7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: c9115fe3-7966-4f47-b3ba-9e386ee594e3
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"c9115fe3-7966-4f47-b3ba-9e386ee594e3\", \"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\": \"3afbb714-b9f6-4e67-bda1-c03b779c2b6b\", \"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\": \"7e64ae86-0f43-4fbc-9271-87f72fa2028b\", \"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": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "doc_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "ref_doc_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 7e64ae86-0f43-4fbc-9271-87f72fa2028b
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"7e64ae86-0f43-4fbc-9271-87f72fa2028b\", \"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\": \"3afbb714-b9f6-4e67-bda1-c03b779c2b6b\", \"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\": \"c9115fe3-7966-4f47-b3ba-9e386ee594e3\", \"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\": \"20931e00-4a96-445d-8e64-3824571ccd32\", \"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": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "doc_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "ref_doc_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 20931e00-4a96-445d-8e64-3824571ccd32
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"20931e00-4a96-445d-8e64-3824571ccd32\", \"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\": \"3afbb714-b9f6-4e67-bda1-c03b779c2b6b\", \"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\": \"7e64ae86-0f43-4fbc-9271-87f72fa2028b\", \"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\": \"6d3b3556-806a-472a-b73c-5acda84308e3\", \"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": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "doc_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "ref_doc_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 6d3b3556-806a-472a-b73c-5acda84308e3
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"6d3b3556-806a-472a-b73c-5acda84308e3\", \"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\": \"3afbb714-b9f6-4e67-bda1-c03b779c2b6b\", \"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\": \"20931e00-4a96-445d-8e64-3824571ccd32\", \"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\": \"6e244fcc-b022-4785-a207-046a934bfcb5\", \"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": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "doc_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "ref_doc_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 6e244fcc-b022-4785-a207-046a934bfcb5
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"6e244fcc-b022-4785-a207-046a934bfcb5\", \"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\": \"3afbb714-b9f6-4e67-bda1-c03b779c2b6b\", \"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\": \"6d3b3556-806a-472a-b73c-5acda84308e3\", \"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\": \"5e8b61f8-cf98-47e4-9d6b-d22bcd6b3935\", \"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": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "doc_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "ref_doc_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 5e8b61f8-cf98-47e4-9d6b-d22bcd6b3935
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"5e8b61f8-cf98-47e4-9d6b-d22bcd6b3935\", \"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\": \"3afbb714-b9f6-4e67-bda1-c03b779c2b6b\", \"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\": \"6e244fcc-b022-4785-a207-046a934bfcb5\", \"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\": \"18643554-c12e-4d74-85c7-9d3095612781\", \"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": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "doc_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "ref_doc_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 18643554-c12e-4d74-85c7-9d3095612781
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"18643554-c12e-4d74-85c7-9d3095612781\", \"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\": \"3afbb714-b9f6-4e67-bda1-c03b779c2b6b\", \"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\": \"5e8b61f8-cf98-47e4-9d6b-d22bcd6b3935\", \"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\": \"cc77445e-3136-42b5-ae77-6862a253c84e\", \"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": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "doc_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "ref_doc_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: cc77445e-3136-42b5-ae77-6862a253c84e
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"cc77445e-3136-42b5-ae77-6862a253c84e\", \"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\": \"3afbb714-b9f6-4e67-bda1-c03b779c2b6b\", \"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\": \"18643554-c12e-4d74-85c7-9d3095612781\", \"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\": \"755af5b4-1ba6-48f8-a798-322d3124bc34\", \"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": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "doc_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "ref_doc_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 755af5b4-1ba6-48f8-a798-322d3124bc34
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"755af5b4-1ba6-48f8-a798-322d3124bc34\", \"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\": \"3afbb714-b9f6-4e67-bda1-c03b779c2b6b\", \"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\": \"cc77445e-3136-42b5-ae77-6862a253c84e\", \"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\": \"9b843449-0ca2-4683-88f9-b2c07d508372\", \"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": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "doc_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "ref_doc_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 9b843449-0ca2-4683-88f9-b2c07d508372
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"9b843449-0ca2-4683-88f9-b2c07d508372\", \"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\": \"3afbb714-b9f6-4e67-bda1-c03b779c2b6b\", \"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\": \"755af5b4-1ba6-48f8-a798-322d3124bc34\", \"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\": \"be2da9de-bb08-48f3-8342-41d413700c3d\", \"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": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "doc_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "ref_doc_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: be2da9de-bb08-48f3-8342-41d413700c3d
encoding: FLOAT32
metadata:
{"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers", "_node_content": "{\"id_\": \"be2da9de-bb08-48f3-8342-41d413700c3d\", \"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\": \"3afbb714-b9f6-4e67-bda1-c03b779c2b6b\", \"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\": \"9b843449-0ca2-4683-88f9-b2c07d508372\", \"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": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "doc_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "ref_doc_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: bf38e92a-7e04-42ce-8d71-af5d2f8c8c40
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_\": \"bf38e92a-7e04-42ce-8d71-af5d2f8c8c40\", \"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\": \"e9ad52a7-418f-4f38-80d8-afeca381c91e\", \"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\": \"6c088b50-0765-44ef-8ffe-bd591d218b75\", \"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": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "doc_id": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "ref_doc_id": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 6c088b50-0765-44ef-8ffe-bd591d218b75
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_\": \"6c088b50-0765-44ef-8ffe-bd591d218b75\", \"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\": \"e9ad52a7-418f-4f38-80d8-afeca381c91e\", \"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\": \"bf38e92a-7e04-42ce-8d71-af5d2f8c8c40\", \"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\": \"39c64eb3-7b8c-4799-9764-b09e830cce67\", \"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": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "doc_id": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "ref_doc_id": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 39c64eb3-7b8c-4799-9764-b09e830cce67
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_\": \"39c64eb3-7b8c-4799-9764-b09e830cce67\", \"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\": \"e9ad52a7-418f-4f38-80d8-afeca381c91e\", \"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\": \"6c088b50-0765-44ef-8ffe-bd591d218b75\", \"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\": \"968749c8-1181-483f-99c8-2f91f5054c7e\", \"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": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "doc_id": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "ref_doc_id": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 968749c8-1181-483f-99c8-2f91f5054c7e
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_\": \"968749c8-1181-483f-99c8-2f91f5054c7e\", \"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\": \"e9ad52a7-418f-4f38-80d8-afeca381c91e\", \"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\": \"39c64eb3-7b8c-4799-9764-b09e830cce67\", \"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\": \"0e3dee86-3378-4b1d-88b5-c3ccff3fd452\", \"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": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "doc_id": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "ref_doc_id": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 0e3dee86-3378-4b1d-88b5-c3ccff3fd452
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_\": \"0e3dee86-3378-4b1d-88b5-c3ccff3fd452\", \"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\": \"e9ad52a7-418f-4f38-80d8-afeca381c91e\", \"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\": \"968749c8-1181-483f-99c8-2f91f5054c7e\", \"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\": \"ef3e53a7-ab5f-42c2-8557-ef37d1f111da\", \"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": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "doc_id": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "ref_doc_id": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: ef3e53a7-ab5f-42c2-8557-ef37d1f111da
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_\": \"ef3e53a7-ab5f-42c2-8557-ef37d1f111da\", \"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\": \"e9ad52a7-418f-4f38-80d8-afeca381c91e\", \"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\": \"0e3dee86-3378-4b1d-88b5-c3ccff3fd452\", \"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\": \"5ac806bd-c2c7-414e-9eb5-b4cd84abf805\", \"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": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "doc_id": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "ref_doc_id": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 5ac806bd-c2c7-414e-9eb5-b4cd84abf805
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_\": \"5ac806bd-c2c7-414e-9eb5-b4cd84abf805\", \"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\": \"e9ad52a7-418f-4f38-80d8-afeca381c91e\", \"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\": \"ef3e53a7-ab5f-42c2-8557-ef37d1f111da\", \"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\": \"ad17cc37-17ef-499a-ab3f-10f9432b7c07\", \"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": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "doc_id": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "ref_doc_id": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: ad17cc37-17ef-499a-ab3f-10f9432b7c07
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_\": \"ad17cc37-17ef-499a-ab3f-10f9432b7c07\", \"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\": \"e9ad52a7-418f-4f38-80d8-afeca381c91e\", \"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\": \"5ac806bd-c2c7-414e-9eb5-b4cd84abf805\", \"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\": \"dbc1477e-d7a4-4d8b-bb01-283a85a29e57\", \"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": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "doc_id": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "ref_doc_id": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: dbc1477e-d7a4-4d8b-bb01-283a85a29e57
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_\": \"dbc1477e-d7a4-4d8b-bb01-283a85a29e57\", \"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\": \"e9ad52a7-418f-4f38-80d8-afeca381c91e\", \"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\": \"ad17cc37-17ef-499a-ab3f-10f9432b7c07\", \"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\": \"4cf01dee-cd3d-4d97-add9-7e6aab05da6b\", \"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": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "doc_id": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "ref_doc_id": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "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-08-26 20:30:03
topic: persistent://default/default/621deaf2-9359-4ac4-ada0-047176703e13
id: 4cf01dee-cd3d-4d97-add9-7e6aab05da6b
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_\": \"4cf01dee-cd3d-4d97-add9-7e6aab05da6b\", \"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\": \"e9ad52a7-418f-4f38-80d8-afeca381c91e\", \"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\": \"dbc1477e-d7a4-4d8b-bb01-283a85a29e57\", \"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\": \"083305f2-b579-4fab-af4e-5cdbfb33d2ba\", \"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": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "doc_id": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "ref_doc_id": "e9ad52a7-418f-4f38-80d8-afeca381c91e", "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."}


