# embedding_metadata

key: chroma:document
string_value:
|       ✅        |         ✅         |      ✅      |
|                       [RT-DETR](model_doc/rt_detr)                       |       ✅        |         ❌         |      ❌      |
|                [RT-DETR-ResNet](model_doc/rt_detr_resnet)                |       ✅        |         ❌         |      ❌      |
|                          [RWKV](model_doc/rwkv)                          |       ✅        |         ❌         |      ❌      |
|                           [SAM](model_doc/sam)                           |       ✅        |         ✅         |      ❌      |
|                  [SeamlessM4T](model_doc/seamless_m4t)                   |       ✅        |         ❌         |      ❌      |
|                [SeamlessM4Tv2](model_doc/seamless_m4t_v2)                |       ✅        |         ❌         |      ❌      |
|                     [SegFormer](model_doc/segformer)                     |       ✅        |         ✅         |


key: _node_content
string_value:
{"id_": "7e87fedc-7f90-4667-a031-b18bc40fa905", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "9c47a502-28d3-4d7d-bd15-0343edd9a594", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "0657e38179307c4ffaf3d8f76a7bcba8f390a8412d0ae9e78b26dd4462d78c08", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c6503c20-a638-4eb9-9fce-ed12acc1cfad", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "fadc7c745ee416e76ee2379d096564dc17659e53911f02240f68652da38bd0ed", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6f7c2edb-22be-4c82-b111-302fad1fe493", "node_type": "1", "metadata": {}, "hash": "1f66a74ea92352679378b4f0e093f9c88608075b412d419c7082d4f5e343c953", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 30699, "end_char_idx": 31618, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
[SAM](model_doc/sam)                           |       ✅        |         ✅         |      ❌      |
|                  [SeamlessM4T](model_doc/seamless_m4t)                   |       ✅        |         ❌         |      ❌      |
|                [SeamlessM4Tv2](model_doc/seamless_m4t_v2)                |       ✅        |         ❌         |      ❌      |
|                     [SegFormer](model_doc/segformer)                     |       ✅        |         ✅         |      ❌      |
|                        [SegGPT](model_doc/seggpt)                        |       ✅        |         ❌         |      ❌      |
|                           [SEW](model_doc/sew)                           |       ✅        |         ❌         |      ❌      |
|                         [SEW-D](model_doc/sew-d)                         |       ✅        |         ❌         |      ❌      |
|                        [SigLIP](model_doc/siglip)


key: _node_content
string_value:
{"id_": "6f7c2edb-22be-4c82-b111-302fad1fe493", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "9c47a502-28d3-4d7d-bd15-0343edd9a594", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "0657e38179307c4ffaf3d8f76a7bcba8f390a8412d0ae9e78b26dd4462d78c08", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7e87fedc-7f90-4667-a031-b18bc40fa905", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "f99d1cddb2d6ed0864e01e727dbb000e9ca444828d9001654f403d0eadf5c74e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5a4323e2-fe95-48fb-8507-47b171f8d780", "node_type": "1", "metadata": {}, "hash": "233fee8187c23928c756479e0513845d29c1e1ddb128828a3c5c70baea7202c8", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 31167, "end_char_idx": 32155, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
|      ❌      |
|                        [SegGPT](model_doc/seggpt)                        |       ✅        |         ❌         |      ❌      |
|                           [SEW](model_doc/sew)                           |       ✅        |         ❌         |      ❌      |
|                         [SEW-D](model_doc/sew-d)                         |       ✅        |         ❌         |      ❌      |
|                        [SigLIP](model_doc/siglip)                        |       ✅        |         ❌         |      ❌      |
|        [Speech Encoder decoder](model_doc/speech-encoder-decoder)        |       ✅        |         ❌         |      ✅      |
|                 [Speech2Text](model_doc/speech_to_text)                  |       ✅        |         ✅         |      ❌      |
|                      [SpeechT5](model_doc/speecht5)                      |       ✅        |         ❌         |      ❌      |
|                      [Splinter](model_doc/splinter)                      |


key: _node_content
string_value:
{"id_": "5a4323e2-fe95-48fb-8507-47b171f8d780", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "9c47a502-28d3-4d7d-bd15-0343edd9a594", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "0657e38179307c4ffaf3d8f76a7bcba8f390a8412d0ae9e78b26dd4462d78c08", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6f7c2edb-22be-4c82-b111-302fad1fe493", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "7a692ea7051d5eb438322581779171b4a8261d5a5f5fd480062ba96e6bda8470", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "55d278c2-b1b5-4417-83ac-f8bc6f8afb8f", "node_type": "1", "metadata": {}, "hash": "f826e9dd3ae7035d6dbf87ba1da1eb1174560488bfd9bb7e0206f01badb86d6e", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 31642, "end_char_idx": 32646, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
|       ✅        |         ❌         |      ❌      |
|        [Speech Encoder decoder](model_doc/speech-encoder-decoder)        |       ✅        |         ❌         |      ✅      |
|                 [Speech2Text](model_doc/speech_to_text)                  |       ✅        |         ✅         |      ❌      |
|                      [SpeechT5](model_doc/speecht5)                      |       ✅        |         ❌         |      ❌      |
|                      [Splinter](model_doc/splinter)                      |       ✅        |         ❌         |      ❌      |
|                   [SqueezeBERT](model_doc/squeezebert)                   |       ✅        |         ❌         |      ❌      |
|                      [StableLm](model_doc/stablelm)                      |       ✅        |         ❌         |      ❌      |
|                    [Starcoder2](model_doc/starcoder2)                    |       ✅        |         ❌         |      ❌      |
|                    [SuperPoint](model_doc/superpoint)


key: _node_content
string_value:
{"id_": "55d278c2-b1b5-4417-83ac-f8bc6f8afb8f", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "9c47a502-28d3-4d7d-bd15-0343edd9a594", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "0657e38179307c4ffaf3d8f76a7bcba8f390a8412d0ae9e78b26dd4462d78c08", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5a4323e2-fe95-48fb-8507-47b171f8d780", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "00e8344a50879940d4a7fd823926ff249cd6c653a90b12753ad0fba8eaa3c496", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "cebfa45b-967f-4122-9837-e93ab57c823d", "node_type": "1", "metadata": {}, "hash": "21fc973b87fc2a3ed29c64efd6195d70197bacbffa392639008db971f38f636f", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 32154, "end_char_idx": 33155, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
|       ✅        |         ❌         |      ❌      |
|                   [SqueezeBERT](model_doc/squeezebert)                   |       ✅        |         ❌         |      ❌      |
|                      [StableLm](model_doc/stablelm)                      |       ✅        |         ❌         |      ❌      |
|                    [Starcoder2](model_doc/starcoder2)                    |       ✅        |         ❌         |      ❌      |
|                    [SuperPoint](model_doc/superpoint)                    |       ✅        |         ❌         |      ❌      |
|                   [SwiftFormer](model_doc/swiftformer)                   |       ✅        |         ✅         |      ❌      |
|                    [Swin Transformer](model_doc/swin)                    |       ✅        |         ✅         |      ❌      |
|                 [Swin Transformer V2](model_doc/swinv2)                  |       ✅        |         ❌         |      ❌      |
|                       [Swin2SR](model_doc/swin2sr)


key: _node_content
string_value:
{"id_": "cebfa45b-967f-4122-9837-e93ab57c823d", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "9c47a502-28d3-4d7d-bd15-0343edd9a594", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "0657e38179307c4ffaf3d8f76a7bcba8f390a8412d0ae9e78b26dd4462d78c08", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "55d278c2-b1b5-4417-83ac-f8bc6f8afb8f", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "43d93fb11d9e90d49290a094856f976c30608e1b838d8f9095674f53472dbc1b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "675128e4-78bc-43e0-8b66-0544d2957576", "node_type": "1", "metadata": {}, "hash": "545f9bc5839a811346d220451e4be1090d9e4024c3161a37e20e9a08ab4f4994", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 32666, "end_char_idx": 33616, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
|       ✅        |         ❌         |      ❌      |
|                   [SwiftFormer](model_doc/swiftformer)                   |       ✅        |         ✅         |      ❌      |
|                    [Swin Transformer](model_doc/swin)                    |       ✅        |         ✅         |      ❌      |
|                 [Swin Transformer V2](model_doc/swinv2)                  |       ✅        |         ❌         |      ❌      |
|                       [Swin2SR](model_doc/swin2sr)                       |       ✅        |         ❌         |      ❌      |
|           [SwitchTransformers](model_doc/switch_transformers)            |       ✅        |         ❌         |      ❌      |
|                            [T5](model_doc/t5)                            |       ✅        |         ✅         |      ✅      |
|                        [T5v1.1](model_doc/t5v1.1)                        |       ✅        |         ✅         |      ✅      |
|


key: _node_content
string_value:
{"id_": "675128e4-78bc-43e0-8b66-0544d2957576", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "9c47a502-28d3-4d7d-bd15-0343edd9a594", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "0657e38179307c4ffaf3d8f76a7bcba8f390a8412d0ae9e78b26dd4462d78c08", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "cebfa45b-967f-4122-9837-e93ab57c823d", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "6000a77e68336f04e756f5bb96faa3e7240095a3e9ad892ba65fc489ed25d027", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "0d39ce21-ecf0-4ae0-83bb-2563edd732fd", "node_type": "1", "metadata": {}, "hash": "d239d01aa8d2bf1cb7dfb9eb8edd72f019c89f62713a5f4bce6b599288d47435", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 33178, "end_char_idx": 34183, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
|       ✅        |         ❌         |      ❌      |
|           [SwitchTransformers](model_doc/switch_transformers)            |       ✅        |         ❌         |      ❌      |
|                            [T5](model_doc/t5)                            |       ✅        |         ✅         |      ✅      |
|                        [T5v1.1](model_doc/t5v1.1)                        |       ✅        |         ✅         |      ✅      |
|             [Table Transformer](model_doc/table-transformer)             |       ✅        |         ❌         |      ❌      |
|                         [TAPAS](model_doc/tapas)                         |       ✅        |         ✅         |      ❌      |
|                         [TAPEX](model_doc/tapex)                         |       ✅        |         ✅         |      ✅      |
|       [Time Series Transformer](model_doc/time_series_transformer)       |       ✅        |         ❌         |      ❌      |
|                   [TimeSformer](model_doc/timesformer)


key: _node_content
string_value:
{"id_": "0d39ce21-ecf0-4ae0-83bb-2563edd732fd", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "9c47a502-28d3-4d7d-bd15-0343edd9a594", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "0657e38179307c4ffaf3d8f76a7bcba8f390a8412d0ae9e78b26dd4462d78c08", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "675128e4-78bc-43e0-8b66-0544d2957576", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "83a90ab031786ca36518cfb389dd3719dca2e7dd9f774e69cd610d1db1a88963", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "546f74e0-b07e-455e-8e28-8cbd048b7c09", "node_type": "1", "metadata": {}, "hash": "4e3ce60960c9e68aefce783c5034c9e26e475aa0b7e6e18d15aeda2acb60283f", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 33629, "end_char_idx": 34688, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
[Table Transformer](model_doc/table-transformer)             |       ✅        |         ❌         |      ❌      |
|                         [TAPAS](model_doc/tapas)                         |       ✅        |         ✅         |      ❌      |
|                         [TAPEX](model_doc/tapex)                         |       ✅        |         ✅         |      ✅      |
|       [Time Series Transformer](model_doc/time_series_transformer)       |       ✅        |         ❌         |      ❌      |
|                   [TimeSformer](model_doc/timesformer)                   |       ✅        |         ❌         |      ❌      |
|        [Trajectory Transformer](model_doc/trajectory_transformer)        |       ✅        |         ❌         |      ❌      |
|                  [Transformer-XL](model_doc/transfo-xl)                  |       ✅        |         ✅         |      ❌      |
|                         [TrOCR](model_doc/trocr)                         |       ✅        |         ❌         |      ❌      |
|                          [TVLT](model_doc/tvlt)


key: _node_content
string_value:
{"id_": "546f74e0-b07e-455e-8e28-8cbd048b7c09", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "9c47a502-28d3-4d7d-bd15-0343edd9a594", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "0657e38179307c4ffaf3d8f76a7bcba8f390a8412d0ae9e78b26dd4462d78c08", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0d39ce21-ecf0-4ae0-83bb-2563edd732fd", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "d4a80c2cc88bbf84121ba2ba4da3337b91a35f7e894b93de15be0cbbc4d7ef09", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "cea5d72e-c5c0-4511-acbf-98a2ebc029bb", "node_type": "1", "metadata": {}, "hash": "091d20496d4e915b856fe8444147585c8a53c8260e606b669c07b16369343175", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 34147, "end_char_idx": 35136, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
[TimeSformer](model_doc/timesformer)                   |       ✅        |         ❌         |      ❌      |
|        [Trajectory Transformer](model_doc/trajectory_transformer)        |       ✅        |         ❌         |      ❌      |
|                  [Transformer-XL](model_doc/transfo-xl)                  |       ✅        |         ✅         |      ❌      |
|                         [TrOCR](model_doc/trocr)                         |       ✅        |         ❌         |      ❌      |
|                          [TVLT](model_doc/tvlt)                          |       ✅        |         ❌         |      ❌      |
|                           [TVP](model_doc/tvp)                           |       ✅        |         ❌         |      ❌      |
|                          [UDOP](model_doc/udop)                          |       ✅        |         ❌         |      ❌      |
|                           [UL2](model_doc/ul2)                           |       ✅        |         ✅         |


key: _node_content
string_value:
{"id_": "cea5d72e-c5c0-4511-acbf-98a2ebc029bb", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "9c47a502-28d3-4d7d-bd15-0343edd9a594", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "0657e38179307c4ffaf3d8f76a7bcba8f390a8412d0ae9e78b26dd4462d78c08", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "546f74e0-b07e-455e-8e28-8cbd048b7c09", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "6aee29fa9bf331f649bed834ad4171df14b54ab66712842be892dc5ffb5501d9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "70144d80-4dac-49c7-b40b-e90ee24c16b9", "node_type": "1", "metadata": {}, "hash": "52cddb4701c5384fce2d2503201f2fd0a850f251eef927971e4c17a24315fc38", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 34714, "end_char_idx": 35619, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
|       ✅        |         ❌         |      ❌      |
|                           [TVP](model_doc/tvp)                           |       ✅        |         ❌         |      ❌      |
|                          [UDOP](model_doc/udop)                          |       ✅        |         ❌         |      ❌      |
|                           [UL2](model_doc/ul2)                           |       ✅        |         ✅         |      ✅      |
|                          [UMT5](model_doc/umt5)                          |       ✅        |         ❌         |      ❌      |
|                     [UniSpeech](model_doc/unispeech)                     |       ✅        |         ❌         |      ❌      |
|                 [UniSpeechSat](model_doc/unispeech-sat)                  |       ✅        |         ❌         |      ❌      |
|                       [UnivNet](model_doc/univnet)                       |       ✅


key: _node_content
string_value:
{"id_": "70144d80-4dac-49c7-b40b-e90ee24c16b9", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "9c47a502-28d3-4d7d-bd15-0343edd9a594", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "0657e38179307c4ffaf3d8f76a7bcba8f390a8412d0ae9e78b26dd4462d78c08", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "cea5d72e-c5c0-4511-acbf-98a2ebc029bb", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "8f3e193ba09cb8ee03e0b601699228d1d6dc7eac21173050870459c68c1a52c5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9a4e7940-b80b-4042-a4a6-07fe51cc36e8", "node_type": "1", "metadata": {}, "hash": "6fc9a46d6032d035b2d7815743f12d53f00bcd24a73b17cfd86586d9580b6fb6", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 35135, "end_char_idx": 36100, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
|      ✅      |
|                          [UMT5](model_doc/umt5)                          |       ✅        |         ❌         |      ❌      |
|                     [UniSpeech](model_doc/unispeech)                     |       ✅        |         ❌         |      ❌      |
|                 [UniSpeechSat](model_doc/unispeech-sat)                  |       ✅        |         ❌         |      ❌      |
|                       [UnivNet](model_doc/univnet)                       |       ✅        |         ❌         |      ❌      |
|                       [UPerNet](model_doc/upernet)                       |       ✅        |         ❌         |      ❌      |
|                           [VAN](model_doc/van)                           |       ✅        |         ❌         |      ❌      |
|                   [VideoLlava](model_doc/video_llava)                    |       ✅        |         ❌         |      ❌      |
|                      [VideoMAE](model_doc/videomae)


key: _node_content
string_value:
{"id_": "9a4e7940-b80b-4042-a4a6-07fe51cc36e8", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "9c47a502-28d3-4d7d-bd15-0343edd9a594", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "0657e38179307c4ffaf3d8f76a7bcba8f390a8412d0ae9e78b26dd4462d78c08", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "70144d80-4dac-49c7-b40b-e90ee24c16b9", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "dc36ef8c13e5bdd89a511caef8721faeffeb049663d80bbf2062e39d3ef06d01", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "191f4a60-ef5f-475e-9427-e95f4f000483", "node_type": "1", "metadata": {}, "hash": "9b9f196628f1786e855e5545033ce5d805003092903ce3fe5bf8b9920d2da7f1", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 35618, "end_char_idx": 36626, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
✅        |         ❌         |      ❌      |
|                       [UPerNet](model_doc/upernet)                       |       ✅        |         ❌         |      ❌      |
|                           [VAN](model_doc/van)                           |       ✅        |         ❌         |      ❌      |
|                   [VideoLlava](model_doc/video_llava)                    |       ✅        |         ❌         |      ❌      |
|                      [VideoMAE](model_doc/videomae)                      |       ✅        |         ❌         |      ❌      |
|                          [ViLT](model_doc/vilt)                          |       ✅        |         ❌         |      ❌      |
|                      [VipLlava](model_doc/vipllava)                      |       ✅        |         ❌         |      ❌      |
|        [Vision Encoder decoder](model_doc/vision-encoder-decoder)        |       ✅        |         ✅         |      ✅      |
|       [VisionTextDualEncoder](model_doc/vision-text-dual-encoder)


key: _node_content
string_value:
{"id_": "191f4a60-ef5f-475e-9427-e95f4f000483", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "9c47a502-28d3-4d7d-bd15-0343edd9a594", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "0657e38179307c4ffaf3d8f76a7bcba8f390a8412d0ae9e78b26dd4462d78c08", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9a4e7940-b80b-4042-a4a6-07fe51cc36e8", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "ef465d372d3050298cfee8c6db3c32f188459f923fbdddb44d40205c47d7e9ca", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "053d0ac3-38d4-42a8-9610-0a44fe5d221b", "node_type": "1", "metadata": {}, "hash": "0315be330e41090fdd4793e677eebec8429746cfa2c847f298dc7dcb0b51950f", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 36122, "end_char_idx": 37122, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
|       ✅        |         ❌         |      ❌      |
|                          [ViLT](model_doc/vilt)                          |       ✅        |         ❌         |      ❌      |
|                      [VipLlava](model_doc/vipllava)                      |       ✅        |         ❌         |      ❌      |
|        [Vision Encoder decoder](model_doc/vision-encoder-decoder)        |       ✅        |         ✅         |      ✅      |
|       [VisionTextDualEncoder](model_doc/vision-text-dual-encoder)        |       ✅        |         ✅         |      ✅      |
|                   [VisualBERT](model_doc/visual_bert)                    |       ✅        |         ❌         |      ❌      |
|                           [ViT](model_doc/vit)                           |       ✅        |         ✅         |      ✅      |
|                    [ViT Hybrid](model_doc/vit_hybrid)                    |       ✅        |         ❌         |      ❌      |
|                        [VitDet](model_doc/vitdet)


key: _node_content
string_value:
{"id_": "053d0ac3-38d4-42a8-9610-0a44fe5d221b", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "9c47a502-28d3-4d7d-bd15-0343edd9a594", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "0657e38179307c4ffaf3d8f76a7bcba8f390a8412d0ae9e78b26dd4462d78c08", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "191f4a60-ef5f-475e-9427-e95f4f000483", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "e899aa5c00a1c47cffe5ec7eff4fa7d6d47602fcfcad5ec7ebc7c2cd9789e97c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "54ea3273-d6b4-4c52-a6ad-4f107e2ec5d5", "node_type": "1", "metadata": {}, "hash": "96dfd78f2867baa1ad1eb2a8f2b01c2d30d63479c42a577836d484e10a34f48e", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 36634, "end_char_idx": 37575, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
|       ✅        |         ✅         |      ✅      |
|                   [VisualBERT](model_doc/visual_bert)                    |       ✅        |         ❌         |      ❌      |
|                           [ViT](model_doc/vit)                           |       ✅        |         ✅         |      ✅      |
|                    [ViT Hybrid](model_doc/vit_hybrid)                    |       ✅        |         ❌         |      ❌      |
|                        [VitDet](model_doc/vitdet)                        |       ✅        |         ❌         |      ❌      |
|                       [ViTMAE](model_doc/vit_mae)                        |       ✅        |         ✅         |      ❌      |
|                      [ViTMatte](model_doc/vitmatte)                      |       ✅        |         ❌         |      ❌      |
|                       [ViTMSN](model_doc/vit_msn)                        |       ✅        |         ❌         |      ❌


key: _node_content
string_value:
{"id_": "54ea3273-d6b4-4c52-a6ad-4f107e2ec5d5", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "9c47a502-28d3-4d7d-bd15-0343edd9a594", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "0657e38179307c4ffaf3d8f76a7bcba8f390a8412d0ae9e78b26dd4462d78c08", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "053d0ac3-38d4-42a8-9610-0a44fe5d221b", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "63cc93e232e22d46cf8e377cd3be66b58b67e01b90001316b3f710fb7ed375ff", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d2ef19ff-a580-44ec-b93b-ad07a58fc429", "node_type": "1", "metadata": {}, "hash": "24eb4ceb4c771b88bfb7a8801af33b78f31822959f74ef107dbe5d6396d16bad", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 37096, "end_char_idx": 38043, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
[VitDet](model_doc/vitdet)                        |       ✅        |         ❌         |      ❌      |
|                       [ViTMAE](model_doc/vit_mae)                        |       ✅        |         ✅         |      ❌      |
|                      [ViTMatte](model_doc/vitmatte)                      |       ✅        |         ❌         |      ❌      |
|                       [ViTMSN](model_doc/vit_msn)                        |       ✅        |         ❌         |      ❌      |
|                          [VITS](model_doc/vits)                          |       ✅        |         ❌         |      ❌      |
|                         [ViViT](model_doc/vivit)                         |       ✅        |         ❌         |      ❌      |
|                      [Wav2Vec2](model_doc/wav2vec2)                      |       ✅        |         ✅         |      ✅      |
|                 [Wav2Vec2-BERT](model_doc/wav2vec2-bert)                 |


key: _node_content
string_value:
{"id_": "d2ef19ff-a580-44ec-b93b-ad07a58fc429", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "9c47a502-28d3-4d7d-bd15-0343edd9a594", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "0657e38179307c4ffaf3d8f76a7bcba8f390a8412d0ae9e78b26dd4462d78c08", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "54ea3273-d6b4-4c52-a6ad-4f107e2ec5d5", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "f591b8e0112f13d2086e4aee50bca5fad4e7c82cdd76e38cdbc0f9e32959c3d9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "53ad7a66-efff-4bdc-a6ee-7516274a59b1", "node_type": "1", "metadata": {}, "hash": "c3c3d70c33266a664cc8c5d7fefb0096a1a46029ad2f361f1a419f51433d55b0", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 37567, "end_char_idx": 38531, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
|      ❌      |
|                          [VITS](model_doc/vits)                          |       ✅        |         ❌         |      ❌      |
|                         [ViViT](model_doc/vivit)                         |       ✅        |         ❌         |      ❌      |
|                      [Wav2Vec2](model_doc/wav2vec2)                      |       ✅        |         ✅         |      ✅      |
|                 [Wav2Vec2-BERT](model_doc/wav2vec2-bert)                 |       ✅        |         ❌         |      ❌      |
|            [Wav2Vec2-Conformer](model_doc/wav2vec2-conformer)            |       ✅        |         ❌         |      ❌      |
|              [Wav2Vec2Phoneme](model_doc/wav2vec2_phoneme)               |       ✅        |         ✅         |      ✅      |
|                         [WavLM](model_doc/wavlm)                         |       ✅        |         ❌         |      ❌      |
|                       [Whisper](model_doc/whisper)


key: _node_content
string_value:
{"id_": "53ad7a66-efff-4bdc-a6ee-7516274a59b1", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "9c47a502-28d3-4d7d-bd15-0343edd9a594", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "0657e38179307c4ffaf3d8f76a7bcba8f390a8412d0ae9e78b26dd4462d78c08", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d2ef19ff-a580-44ec-b93b-ad07a58fc429", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "8466853bebf983736a703caf5f06c430224d25137251dcd3b7625985a92e9128", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "596df911-d813-40fb-b870-0343ee880449", "node_type": "1", "metadata": {}, "hash": "76c8e13f1396599a9befb13eb6a7b0259e1ddcc8494a4c0df8de8397a58a8e87", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 38042, "end_char_idx": 38992, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
|       ✅        |         ❌         |      ❌      |
|            [Wav2Vec2-Conformer](model_doc/wav2vec2-conformer)            |       ✅        |         ❌         |      ❌      |
|              [Wav2Vec2Phoneme](model_doc/wav2vec2_phoneme)               |       ✅        |         ✅         |      ✅      |
|                         [WavLM](model_doc/wavlm)                         |       ✅        |         ❌         |      ❌      |
|                       [Whisper](model_doc/whisper)                       |       ✅        |         ✅         |      ✅      |
|                        [X-CLIP](model_doc/xclip)                         |       ✅        |         ❌         |      ❌      |
|                         [X-MOD](model_doc/xmod)                          |       ✅        |         ❌         |      ❌      |
|                          [XGLM](model_doc/xglm)                          |       ✅        |         ✅         |      ✅      |
|


key: _node_content
string_value:
{"id_": "596df911-d813-40fb-b870-0343ee880449", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "9c47a502-28d3-4d7d-bd15-0343edd9a594", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "0657e38179307c4ffaf3d8f76a7bcba8f390a8412d0ae9e78b26dd4462d78c08", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "53ad7a66-efff-4bdc-a6ee-7516274a59b1", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "098229425b7e7d045ee1991943fc7b4b0d9f3b99d001c455fa269ab16d7df115", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f09b4c16-b7e5-4574-ad15-f5467bc85602", "node_type": "1", "metadata": {}, "hash": "287891c6b8b027bfa5723390d3766eba2c29d248d68cd09d71393c68a3873434", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 38554, "end_char_idx": 39478, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
|       ✅        |         ✅         |      ✅      |
|                        [X-CLIP](model_doc/xclip)                         |       ✅        |         ❌         |      ❌      |
|                         [X-MOD](model_doc/xmod)                          |       ✅        |         ❌         |      ❌      |
|                          [XGLM](model_doc/xglm)                          |       ✅        |         ✅         |      ✅      |
|                           [XLM](model_doc/xlm)                           |       ✅        |         ✅         |      ❌      |
|                [XLM-ProphetNet](model_doc/xlm-prophetnet)                |       ✅        |         ❌         |      ❌      |
|                   [XLM-RoBERTa](model_doc/xlm-roberta)                   |       ✅        |         ✅         |      ✅      |
|                [XLM-RoBERTa-XL](model_doc/xlm-roberta-xl)                |       ✅        |         ❌


key: _node_content
string_value:
{"id_": "f09b4c16-b7e5-4574-ad15-f5467bc85602", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "9c47a502-28d3-4d7d-bd15-0343edd9a594", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "0657e38179307c4ffaf3d8f76a7bcba8f390a8412d0ae9e78b26dd4462d78c08", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "596df911-d813-40fb-b870-0343ee880449", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "ed031f10af536955d642ab78b2bab2f26cc0ce13879153f3b0b6e7d869a9a7ce", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "986ad22c-7980-4c5c-941d-652eff5a4471", "node_type": "1", "metadata": {}, "hash": "cce28a8bbfa5279cd20bd3cbedb977a91b2c35c8343b338b9d10a5d2d7c2da0e", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 38982, "end_char_idx": 39945, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
✅      |
|                           [XLM](model_doc/xlm)                           |       ✅        |         ✅         |      ❌      |
|                [XLM-ProphetNet](model_doc/xlm-prophetnet)                |       ✅        |         ❌         |      ❌      |
|                   [XLM-RoBERTa](model_doc/xlm-roberta)                   |       ✅        |         ✅         |      ✅      |
|                [XLM-RoBERTa-XL](model_doc/xlm-roberta-xl)                |       ✅        |         ❌         |      ❌      |
|                         [XLM-V](model_doc/xlm-v)                         |       ✅        |         ✅         |      ✅      |
|                         [XLNet](model_doc/xlnet)                         |       ✅        |         ✅         |      ❌      |
|                         [XLS-R](model_doc/xls_r)                         |       ✅        |         ✅         |      ✅      |
|                 [XLSR-Wav2Vec2](model_doc/xlsr_wav2vec2)


key: _node_content
string_value:
{"id_": "986ad22c-7980-4c5c-941d-652eff5a4471", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "9c47a502-28d3-4d7d-bd15-0343edd9a594", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "0657e38179307c4ffaf3d8f76a7bcba8f390a8412d0ae9e78b26dd4462d78c08", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f09b4c16-b7e5-4574-ad15-f5467bc85602", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/index", "title": "\ud83e\udd17 Transformers", "tokens": 9691, "retrieve_doc": false, "source": "transformers"}, "hash": "bb903fdfe9c8a89c01c5e1fc6439591d7e2ed4570d9d9b1c50d0f962adac4544", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 39477, "end_char_idx": 40417, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
❌         |      ❌      |
|                         [XLM-V](model_doc/xlm-v)                         |       ✅        |         ✅         |      ✅      |
|                         [XLNet](model_doc/xlnet)                         |       ✅        |         ✅         |      ❌      |
|                         [XLS-R](model_doc/xls_r)                         |       ✅        |         ✅         |      ✅      |
|                 [XLSR-Wav2Vec2](model_doc/xlsr_wav2vec2)                 |       ✅        |         ✅         |      ✅      |
|                         [YOLOS](model_doc/yolos)                         |       ✅        |         ❌         |      ❌      |
|                          [YOSO](model_doc/yoso)                          |       ✅        |         ❌         |      ❌      |
|                      [ZoeDepth](model_doc/zoedepth)                      |       ✅        |         ❌         |      ❌      |

<!-- End table-->


key: _node_content
string_value:
{"id_": "34287eac-68c8-4631-9ab9-bb505cf40fa2", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "bf771131-01ee-4a9c-84c9-df0464368357", "node_type": "1", "metadata": {}, "hash": "18ceb50f5c015cfd9900fa1d273897dd22119d0eff75c60692928bbf7bd0485b", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3282, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Optimizing LLMs for Speed and Memory

[[open-in-colab]]

Large Language Models (LLMs) such as GPT3/4, [Falcon](https://huggingface.co/tiiuae/falcon-40b), and [Llama](https://huggingface.co/meta-llama/Llama-2-70b-hf) are rapidly advancing in their ability to tackle human-centric tasks, establishing themselves as essential tools in modern knowledge-based industries.
Deploying these models in real-world tasks remains challenging, however:

-   To exhibit near-human text understanding and generation capabilities, LLMs currently require to be composed of billions of parameters (see [Kaplan et al](https://arxiv.org/abs/2001.08361), [Wei et. al](https://arxiv.org/abs/2206.07682)). This consequently amplifies the memory demands for inference.
-   In many real-world tasks, LLMs need to be given extensive contextual information. This necessitates the model's capability to manage very long input sequences during inference.

The crux of these challenges lies in augmenting the computational and memory capabilities of LLMs, especially when handling expansive input sequences.

In this guide, we will go over the effective techniques for efficient LLM deployment:

1.  **Lower Precision:** Research has shown that operating at reduced numerical precision, namely [8-bit and 4-bit](./main_classes/quantization.md) can achieve computational advantages without a considerable decline in model performance.

2.  **Flash Attention:** Flash Attention is a variation of the attention algorithm that not only provides a more memory-efficient approach but also realizes increased efficiency due to optimized GPU memory utilization.

3.  **Architectural Innovations:** Considering that LLMs are always deployed in the same way during inference, namely autoregressive text generation with a long input context, specialized model architectures have been proposed that allow for more efficient inference. The most important advancement in model architectures hereby are [Alibi](https://arxiv.org/abs/2108.12409), [Rotary embeddings](https://arxiv.org/abs/2104.09864), [Multi-Query Attention (MQA)](https://arxiv.org/abs/1911.02150) and [Grouped-Query-Attention (GQA)]((https://arxiv.org/abs/2305.13245)).

Throughout this guide, we will offer an analysis of auto-regressive generation from a tensor's perspective. We delve into the pros and cons of adopting lower precision, provide a comprehensive exploration of the latest attention algorithms, and discuss improved LLM architectures. While doing so, we run practical examples showcasing each of the feature improvements.

## 1. Lower Precision

Memory requirements of LLMs can be best understood by seeing the LLM as a set of weight matrices and vectors and the text inputs as a sequence of vectors. In the following, the definition *weights* will be used to signify all model weight matrices and vectors.

At the time of writing this guide, LLMs consist of at least a couple billion parameters. Each parameter thereby is made of a decimal number, e.g. `4.5689` which is usually stored in either [float32](https://en.wikipedia.org/wiki/Single-precision_floating-point_format), [bfloat16](https://en.wikipedia.org/wiki/Bfloat16_floating-point_format), or [float16](https://en.wikipedia.org/wiki/Half-precision_floating-point_format) format.


key: _node_content
string_value:
{"id_": "bf771131-01ee-4a9c-84c9-df0464368357", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "34287eac-68c8-4631-9ab9-bb505cf40fa2", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "750b233959dd68b6e6cd300e2af360ac5516198f8be18e6c24ded286f9c2516b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a99c1ecb-6042-47e7-b5bc-3820d0723b38", "node_type": "1", "metadata": {}, "hash": "ab1e062eedb3764ab287b71744c2fd9be9cb264aa71d1bca465816832d1ce640", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1627, "end_char_idx": 4102, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
3.  **Architectural Innovations:** Considering that LLMs are always deployed in the same way during inference, namely autoregressive text generation with a long input context, specialized model architectures have been proposed that allow for more efficient inference. The most important advancement in model architectures hereby are [Alibi](https://arxiv.org/abs/2108.12409), [Rotary embeddings](https://arxiv.org/abs/2104.09864), [Multi-Query Attention (MQA)](https://arxiv.org/abs/1911.02150) and [Grouped-Query-Attention (GQA)]((https://arxiv.org/abs/2305.13245)).

Throughout this guide, we will offer an analysis of auto-regressive generation from a tensor's perspective. We delve into the pros and cons of adopting lower precision, provide a comprehensive exploration of the latest attention algorithms, and discuss improved LLM architectures. While doing so, we run practical examples showcasing each of the feature improvements.

## 1. Lower Precision

Memory requirements of LLMs can be best understood by seeing the LLM as a set of weight matrices and vectors and the text inputs as a sequence of vectors. In the following, the definition *weights* will be used to signify all model weight matrices and vectors.

At the time of writing this guide, LLMs consist of at least a couple billion parameters. Each parameter thereby is made of a decimal number, e.g. `4.5689` which is usually stored in either [float32](https://en.wikipedia.org/wiki/Single-precision_floating-point_format), [bfloat16](https://en.wikipedia.org/wiki/Bfloat16_floating-point_format), or [float16](https://en.wikipedia.org/wiki/Half-precision_floating-point_format) format. This allows us to easily compute the memory requirement to load the LLM into memory:

> *Loading the weights of a model having X billion parameters requires roughly 4 * X GB of VRAM in float32 precision*

Nowadays, models are however rarely trained in full float32 precision, but usually in bfloat16 precision or less frequently in float16 precision. Therefore the rule of thumb becomes:

> *Loading the weights of a model having X billion parameters requires roughly 2 * X GB of VRAM in bfloat16/float16 precision*

For shorter text inputs (less than 1024 tokens), the memory requirement for inference is very much dominated by the memory requirement to load the weights. Therefore, for now, let's assume that the memory requirement for inference is equal to the memory requirement to load the model into the GPU VRAM.


key: _node_content
string_value:
{"id_": "a99c1ecb-6042-47e7-b5bc-3820d0723b38", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "bf771131-01ee-4a9c-84c9-df0464368357", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "3bd7fb37b2fd755752ef715ffa3716bf6c22bb61cfa7c7323fc3374c65f9b22f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7fd6e0cd-5c5a-4102-abbe-25c17fb9ac20", "node_type": "1", "metadata": {}, "hash": "637e4164204c1370b39310c7856a390417c23a41d1275c376ef9cddb0ab3bc0f", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2304, "end_char_idx": 5217, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
We delve into the pros and cons of adopting lower precision, provide a comprehensive exploration of the latest attention algorithms, and discuss improved LLM architectures. While doing so, we run practical examples showcasing each of the feature improvements.

## 1. Lower Precision

Memory requirements of LLMs can be best understood by seeing the LLM as a set of weight matrices and vectors and the text inputs as a sequence of vectors. In the following, the definition *weights* will be used to signify all model weight matrices and vectors.

At the time of writing this guide, LLMs consist of at least a couple billion parameters. Each parameter thereby is made of a decimal number, e.g. `4.5689` which is usually stored in either [float32](https://en.wikipedia.org/wiki/Single-precision_floating-point_format), [bfloat16](https://en.wikipedia.org/wiki/Bfloat16_floating-point_format), or [float16](https://en.wikipedia.org/wiki/Half-precision_floating-point_format) format. This allows us to easily compute the memory requirement to load the LLM into memory:

> *Loading the weights of a model having X billion parameters requires roughly 4 * X GB of VRAM in float32 precision*

Nowadays, models are however rarely trained in full float32 precision, but usually in bfloat16 precision or less frequently in float16 precision. Therefore the rule of thumb becomes:

> *Loading the weights of a model having X billion parameters requires roughly 2 * X GB of VRAM in bfloat16/float16 precision*

For shorter text inputs (less than 1024 tokens), the memory requirement for inference is very much dominated by the memory requirement to load the weights. Therefore, for now, let's assume that the memory requirement for inference is equal to the memory requirement to load the model into the GPU VRAM.

To give some examples of how much VRAM it roughly takes to load a model in bfloat16:

-   **GPT3** requires 2 \* 175 GB = **350 GB** VRAM
-   [**Bloom**](https://huggingface.co/bigscience/bloom) requires 2 \* 176 GB = **352 GB** VRAM
-   [**Llama-2-70b**](https://huggingface.co/meta-llama/Llama-2-70b-hf) requires 2 \* 70 GB = **140 GB** VRAM
-   [**Falcon-40b**](https://huggingface.co/tiiuae/falcon-40b) requires 2 \* 40 GB = **80 GB** VRAM
-   [**MPT-30b**](https://huggingface.co/mosaicml/mpt-30b) requires 2 \* 30 GB = **60 GB** VRAM
-   [**bigcode/starcoder**](https://huggingface.co/bigcode/starcoder) requires 2 \* 15.5 = **31 GB** VRAM

As of writing this document, the largest GPU chip on the market is the A100 & H100 offering 80GB of VRAM. Most of the models listed before require more than 80GB just to be loaded and therefore necessarily require [tensor parallelism](https://huggingface.co/docs/transformers/perf_train_gpu_many#tensor-parallelism) and/or [pipeline parallelism](https://huggingface.co/docs/transformers/perf_train_gpu_many#naive-model-parallelism-vertical-and-pipeline-parallelism).


key: _node_content
string_value:
{"id_": "7fd6e0cd-5c5a-4102-abbe-25c17fb9ac20", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a99c1ecb-6042-47e7-b5bc-3820d0723b38", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "3d35e9d9fe259ceebabe636c5237008d91cd27a4d9b8af703d0a11154cacd4ca", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "0c9bb564-0567-46a1-b2dc-a1f87c6f4de8", "node_type": "1", "metadata": {}, "hash": "1787cf67b4e0c1f5f3ee54a0676f2ba0477b425237ca7298383638711980af20", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3956, "end_char_idx": 6790, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Therefore, for now, let's assume that the memory requirement for inference is equal to the memory requirement to load the model into the GPU VRAM.

To give some examples of how much VRAM it roughly takes to load a model in bfloat16:

-   **GPT3** requires 2 \* 175 GB = **350 GB** VRAM
-   [**Bloom**](https://huggingface.co/bigscience/bloom) requires 2 \* 176 GB = **352 GB** VRAM
-   [**Llama-2-70b**](https://huggingface.co/meta-llama/Llama-2-70b-hf) requires 2 \* 70 GB = **140 GB** VRAM
-   [**Falcon-40b**](https://huggingface.co/tiiuae/falcon-40b) requires 2 \* 40 GB = **80 GB** VRAM
-   [**MPT-30b**](https://huggingface.co/mosaicml/mpt-30b) requires 2 \* 30 GB = **60 GB** VRAM
-   [**bigcode/starcoder**](https://huggingface.co/bigcode/starcoder) requires 2 \* 15.5 = **31 GB** VRAM

As of writing this document, the largest GPU chip on the market is the A100 & H100 offering 80GB of VRAM. Most of the models listed before require more than 80GB just to be loaded and therefore necessarily require [tensor parallelism](https://huggingface.co/docs/transformers/perf_train_gpu_many#tensor-parallelism) and/or [pipeline parallelism](https://huggingface.co/docs/transformers/perf_train_gpu_many#naive-model-parallelism-vertical-and-pipeline-parallelism).

🤗 Transformers does not support tensor parallelism out of the box as it requires the model architecture to be written in a specific way. If you're interested in writing models in a tensor-parallelism-friendly way, feel free to have a look at [the text-generation-inference library](https://github.com/huggingface/text-generation-inference/tree/main/server/text_generation_server/models/custom_modeling).

Naive pipeline parallelism is supported out of the box. For this, simply load the model with `device="auto"` which will automatically place the different layers on the available GPUs as explained [here](https://huggingface.co/docs/accelerate/v0.22.0/en/concept_guides/big_model_inference).
Note, however that while very effective, this naive pipeline parallelism does not tackle the issues of GPU idling. For this more advanced pipeline parallelism is required as explained [here](https://huggingface.co/docs/transformers/en/perf_train_gpu_many#naive-model-parallelism-vertical-and-pipeline-parallelism).

If you have access to an 8 x 80GB A100 node, you could load BLOOM as follows

```bash
!pip install transformers accelerate bitsandbytes optimum
```
```python
from transformers import AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained("bigscience/bloom", device_map="auto", pad_token_id=0)
```

By using `device_map="auto"` the attention layers would be equally distributed over all available GPUs.

In this guide, we will use [bigcode/octocoder](https://huggingface.co/bigcode/octocoder) as it can be run on a single 40 GB A100 GPU device chip.


key: _node_content
string_value:
{"id_": "0c9bb564-0567-46a1-b2dc-a1f87c6f4de8", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7fd6e0cd-5c5a-4102-abbe-25c17fb9ac20", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "5dd063ca12cf983af568f6fe7055aec40114375d9cd3b4c430dd2d6374ea0cc3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e4d0b9b9-04c7-431c-974d-b9def265c24e", "node_type": "1", "metadata": {}, "hash": "57697e8a545df8252585b85773501f9e061a33f3ba241660a58753937517cee3", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5219, "end_char_idx": 8410, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
🤗 Transformers does not support tensor parallelism out of the box as it requires the model architecture to be written in a specific way. If you're interested in writing models in a tensor-parallelism-friendly way, feel free to have a look at [the text-generation-inference library](https://github.com/huggingface/text-generation-inference/tree/main/server/text_generation_server/models/custom_modeling).

Naive pipeline parallelism is supported out of the box. For this, simply load the model with `device="auto"` which will automatically place the different layers on the available GPUs as explained [here](https://huggingface.co/docs/accelerate/v0.22.0/en/concept_guides/big_model_inference).
Note, however that while very effective, this naive pipeline parallelism does not tackle the issues of GPU idling. For this more advanced pipeline parallelism is required as explained [here](https://huggingface.co/docs/transformers/en/perf_train_gpu_many#naive-model-parallelism-vertical-and-pipeline-parallelism).

If you have access to an 8 x 80GB A100 node, you could load BLOOM as follows

```bash
!pip install transformers accelerate bitsandbytes optimum
```
```python
from transformers import AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained("bigscience/bloom", device_map="auto", pad_token_id=0)
```

By using `device_map="auto"` the attention layers would be equally distributed over all available GPUs.

In this guide, we will use [bigcode/octocoder](https://huggingface.co/bigcode/octocoder) as it can be run on a single 40 GB A100 GPU device chip. Note that all memory and speed optimizations that we will apply going forward, are equally applicable to models that require model or tensor parallelism.

Since the model is loaded in bfloat16 precision, using our rule of thumb above, we would expect the memory requirement to run inference with `bigcode/octocoder` to be around 31 GB VRAM. Let's give it a try.

We first load the model and tokenizer and then pass both to Transformers' [pipeline](https://huggingface.co/docs/transformers/main_classes/pipelines) object.

```python
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
import torch

model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", torch_dtype=torch.bfloat16, device_map="auto", pad_token_id=0)
tokenizer = AutoTokenizer.from_pretrained("bigcode/octocoder")

pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)
```

```python
prompt = "Question: Please write a function in Python that transforms bytes to Giga bytes.\n\nAnswer:"

result = pipe(prompt, max_new_tokens=60)[0]["generated_text"][len(prompt):]
result
```

**Output**:
```
Here is a Python function that transforms bytes to Giga bytes:\n\n```python\ndef bytes_to_giga_bytes(bytes):\n    return bytes / 1024 / 1024 / 1024\n```\n\nThis function takes a single
```

Nice, we can now directly use the result to convert bytes into Gigabytes.

```python
def bytes_to_giga_bytes(bytes):
  return bytes / 1024 / 1024 / 1024
```

Let's call [`torch.cuda.max_memory_allocated`](https://pytorch.org/docs/stable/generated/torch.cuda.max_memory_allocated.html) to measure the peak GPU memory allocation.


key: _node_content
string_value:
{"id_": "e4d0b9b9-04c7-431c-974d-b9def265c24e", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0c9bb564-0567-46a1-b2dc-a1f87c6f4de8", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "4194f31cb28ee16c87609b4c3b86218cff423d8551c816443049ef8ed94726b2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d80c402f-5d73-4512-a836-812798f408a7", "node_type": "1", "metadata": {}, "hash": "43e5700112c8da992cf7535e6b834d154270f07660268e9926241bcb0928af88", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 6791, "end_char_idx": 9901, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Note that all memory and speed optimizations that we will apply going forward, are equally applicable to models that require model or tensor parallelism.

Since the model is loaded in bfloat16 precision, using our rule of thumb above, we would expect the memory requirement to run inference with `bigcode/octocoder` to be around 31 GB VRAM. Let's give it a try.

We first load the model and tokenizer and then pass both to Transformers' [pipeline](https://huggingface.co/docs/transformers/main_classes/pipelines) object.

```python
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
import torch

model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", torch_dtype=torch.bfloat16, device_map="auto", pad_token_id=0)
tokenizer = AutoTokenizer.from_pretrained("bigcode/octocoder")

pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)
```

```python
prompt = "Question: Please write a function in Python that transforms bytes to Giga bytes.\n\nAnswer:"

result = pipe(prompt, max_new_tokens=60)[0]["generated_text"][len(prompt):]
result
```

**Output**:
```
Here is a Python function that transforms bytes to Giga bytes:\n\n```python\ndef bytes_to_giga_bytes(bytes):\n    return bytes / 1024 / 1024 / 1024\n```\n\nThis function takes a single
```

Nice, we can now directly use the result to convert bytes into Gigabytes.

```python
def bytes_to_giga_bytes(bytes):
  return bytes / 1024 / 1024 / 1024
```

Let's call [`torch.cuda.max_memory_allocated`](https://pytorch.org/docs/stable/generated/torch.cuda.max_memory_allocated.html) to measure the peak GPU memory allocation.

```python
bytes_to_giga_bytes(torch.cuda.max_memory_allocated())
```

**Output**:
```bash
29.0260648727417
```

Close enough to our back-of-the-envelope computation! We can see the number is not exactly correct as going from bytes to kilobytes requires a multiplication of 1024 instead of 1000. Therefore the back-of-the-envelope formula can also be understood as an "at most X GB" computation.
Note that if we had tried to run the model in full float32 precision, a whopping 64 GB of VRAM would have been required.

> Almost all models are trained in bfloat16 nowadays, there is no reason to run the model in full float32 precision if [your GPU supports bfloat16](https://discuss.pytorch.org/t/bfloat16-native-support/117155/5). Float32 won't give better inference results than the precision that was used to train the model.

If you are unsure in which format the model weights are stored on the Hub, you can always look into the checkpoint's config under `"torch_dtype"`, *e.g.* [here](https://huggingface.co/meta-llama/Llama-2-7b-hf/blob/6fdf2e60f86ff2481f2241aaee459f85b5b0bbb9/config.json#L21). It is recommended to set the model to the same precision type as written in the config when loading with `from_pretrained(..., torch_dtype=...)` except when the original type is float32 in which case one can use both `float16` or `bfloat16` for inference.


Let's define a `flush(...)` function to free all allocated memory so that we can accurately measure the peak allocated GPU memory.


key: _node_content
string_value:
{"id_": "d80c402f-5d73-4512-a836-812798f408a7", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e4d0b9b9-04c7-431c-974d-b9def265c24e", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "35bb99dc3ae88cc831d4a2a9758311c6b7f960a9c6f1fc36d4a7e33d79a218d7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6a11ff58-2570-4e27-b185-8b6b8d641a9d", "node_type": "1", "metadata": {}, "hash": "a00581045b45484befbe08bca38772d4c8c0ca1d032bc477874c6ef0a12216d0", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 8412, "end_char_idx": 11493, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
bytes_to_giga_bytes(torch.cuda.max_memory_allocated())
```

**Output**:
```bash
29.0260648727417
```

Close enough to our back-of-the-envelope computation! We can see the number is not exactly correct as going from bytes to kilobytes requires a multiplication of 1024 instead of 1000. Therefore the back-of-the-envelope formula can also be understood as an "at most X GB" computation.
Note that if we had tried to run the model in full float32 precision, a whopping 64 GB of VRAM would have been required.

> Almost all models are trained in bfloat16 nowadays, there is no reason to run the model in full float32 precision if [your GPU supports bfloat16](https://discuss.pytorch.org/t/bfloat16-native-support/117155/5). Float32 won't give better inference results than the precision that was used to train the model.

If you are unsure in which format the model weights are stored on the Hub, you can always look into the checkpoint's config under `"torch_dtype"`, *e.g.* [here](https://huggingface.co/meta-llama/Llama-2-7b-hf/blob/6fdf2e60f86ff2481f2241aaee459f85b5b0bbb9/config.json#L21). It is recommended to set the model to the same precision type as written in the config when loading with `from_pretrained(..., torch_dtype=...)` except when the original type is float32 in which case one can use both `float16` or `bfloat16` for inference.


Let's define a `flush(...)` function to free all allocated memory so that we can accurately measure the peak allocated GPU memory.

```python
del pipe
del model

import gc
import torch

def flush():
  gc.collect()
  torch.cuda.empty_cache()
  torch.cuda.reset_peak_memory_stats()
```

Let's call it now for the next experiment.

```python
flush()
```
In the recent version of the accelerate library, you can also use a utility method called `release_memory()`

```python
from accelerate.utils import release_memory
# ...

release_memory(model)
```

Now what if your GPU does not have 32 GB of VRAM? It has been found that model weights can be quantized to 8-bit or 4-bits without a significant loss in performance (see [Dettmers et al.](https://arxiv.org/abs/2208.07339)).
Model can be quantized to even 3 or 2 bits with an acceptable loss in performance as shown in the recent [GPTQ paper](https://arxiv.org/abs/2210.17323) 🤯.

Without going into too many details, quantization schemes aim at reducing the precision of weights while trying to keep the model's inference results as accurate as possible (*a.k.a* as close as possible to bfloat16).
Note that quantization works especially well for text generation since all we care about is choosing the *set of most likely next tokens* and don't really care about the exact values of the next token *logit* distribution.
All that matters is that the next token *logit* distribution stays roughly the same so that an `argmax` or `topk` operation gives the same results.

There are various quantization techniques, which we won't discuss in detail here, but in general, all quantization techniques work as follows:

-   1.  Quantize all weights to the target precision
-   2.


key: _node_content
string_value:
{"id_": "6a11ff58-2570-4e27-b185-8b6b8d641a9d", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d80c402f-5d73-4512-a836-812798f408a7", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "9c9cddc3d0e15a0f081499f8383301c5672eae164622a6e1286b53b7ee4b0553", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b55ebf8c-87e9-4ea6-8e94-721750480d3f", "node_type": "1", "metadata": {}, "hash": "d47e75e1347e6f704d3fa7fbec990d7cfadca43f436a05fe4534ed088a686baf", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 9903, "end_char_idx": 12742, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
del pipe
del model

import gc
import torch

def flush():
  gc.collect()
  torch.cuda.empty_cache()
  torch.cuda.reset_peak_memory_stats()
```

Let's call it now for the next experiment.

```python
flush()
```
In the recent version of the accelerate library, you can also use a utility method called `release_memory()`

```python
from accelerate.utils import release_memory
# ...

release_memory(model)
```

Now what if your GPU does not have 32 GB of VRAM? It has been found that model weights can be quantized to 8-bit or 4-bits without a significant loss in performance (see [Dettmers et al.](https://arxiv.org/abs/2208.07339)).
Model can be quantized to even 3 or 2 bits with an acceptable loss in performance as shown in the recent [GPTQ paper](https://arxiv.org/abs/2210.17323) 🤯.

Without going into too many details, quantization schemes aim at reducing the precision of weights while trying to keep the model's inference results as accurate as possible (*a.k.a* as close as possible to bfloat16).
Note that quantization works especially well for text generation since all we care about is choosing the *set of most likely next tokens* and don't really care about the exact values of the next token *logit* distribution.
All that matters is that the next token *logit* distribution stays roughly the same so that an `argmax` or `topk` operation gives the same results.

There are various quantization techniques, which we won't discuss in detail here, but in general, all quantization techniques work as follows:

-   1.  Quantize all weights to the target precision
-   2.  Load the quantized weights, and pass the input sequence of vectors in bfloat16 precision
-   3.  Dynamically dequantize weights to bfloat16 to perform the computation with their input vectors in bfloat16 precision

In a nutshell, this means that *inputs-weight matrix* multiplications, with \\( X \\) being the *inputs*, \\( W \\) being a weight matrix and \\( Y \\) being the output:

$$ Y = X * W $$

are changed to

$$ Y = X * \text{dequantize}(W) $$

for every matrix multiplication. Dequantization and re-quantization is performed sequentially for all weight matrices as the inputs run through the network graph.

Therefore, inference time is often **not** reduced when using quantized weights, but rather increases.
Enough theory, let's give it a try! To quantize the weights with Transformers, you need to make sure that
the [`bitsandbytes`](https://github.com/TimDettmers/bitsandbytes) library is installed.

```bash
!pip install bitsandbytes
```

We can then load models in 8-bit quantization by simply adding a `load_in_8bit=True` flag to `from_pretrained`.

```python
model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", load_in_8bit=True, pad_token_id=0)
```

Now, let's run our example again and measure the memory usage.


key: _node_content
string_value:
{"id_": "b55ebf8c-87e9-4ea6-8e94-721750480d3f", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6a11ff58-2570-4e27-b185-8b6b8d641a9d", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "f0c796e46edb85f2c38d6577a68436d8056ff4063bdcee9274a1696beac27a3f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ca13b411-c559-43be-ba3c-1bab28a3231e", "node_type": "1", "metadata": {}, "hash": "bb9222685e59f39a7662ae5f59923f59ca4c6175c8cf66bcbe0c912178ebdbea", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 11141, "end_char_idx": 13966, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
All that matters is that the next token *logit* distribution stays roughly the same so that an `argmax` or `topk` operation gives the same results.

There are various quantization techniques, which we won't discuss in detail here, but in general, all quantization techniques work as follows:

-   1.  Quantize all weights to the target precision
-   2.  Load the quantized weights, and pass the input sequence of vectors in bfloat16 precision
-   3.  Dynamically dequantize weights to bfloat16 to perform the computation with their input vectors in bfloat16 precision

In a nutshell, this means that *inputs-weight matrix* multiplications, with \\( X \\) being the *inputs*, \\( W \\) being a weight matrix and \\( Y \\) being the output:

$$ Y = X * W $$

are changed to

$$ Y = X * \text{dequantize}(W) $$

for every matrix multiplication. Dequantization and re-quantization is performed sequentially for all weight matrices as the inputs run through the network graph.

Therefore, inference time is often **not** reduced when using quantized weights, but rather increases.
Enough theory, let's give it a try! To quantize the weights with Transformers, you need to make sure that
the [`bitsandbytes`](https://github.com/TimDettmers/bitsandbytes) library is installed.

```bash
!pip install bitsandbytes
```

We can then load models in 8-bit quantization by simply adding a `load_in_8bit=True` flag to `from_pretrained`.

```python
model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", load_in_8bit=True, pad_token_id=0)
```

Now, let's run our example again and measure the memory usage.

```python
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)

result = pipe(prompt, max_new_tokens=60)[0]["generated_text"][len(prompt):]
result
```

**Output**:
```
Here is a Python function that transforms bytes to Giga bytes:\n\n```python\ndef bytes_to_giga_bytes(bytes):\n    return bytes / 1024 / 1024 / 1024\n```\n\nThis function takes a single
```

Nice, we're getting the same result as before, so no loss in accuracy! Let's look at how much memory was used this time.

```python
bytes_to_giga_bytes(torch.cuda.max_memory_allocated())
```

**Output**:
```
15.219234466552734
```

Significantly less! We're down to just a bit over 15 GBs and could therefore run this model on consumer GPUs like the 4090.
We're seeing a very nice gain in memory efficiency and more or less no degradation to the model's output. However, we can also notice a slight slow-down during inference.


We delete the models and flush the memory again.
```python
del model
del pipe
```

```python
flush()
```

Let's see what peak GPU memory consumption 4-bit quantization gives. Quantizing the model to 4-bit can be done with the same API as before - this time by passing `load_in_4bit=True` instead of `load_in_8bit=True`.


key: _node_content
string_value:
{"id_": "ca13b411-c559-43be-ba3c-1bab28a3231e", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b55ebf8c-87e9-4ea6-8e94-721750480d3f", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "aa8cd3be093046d3257fbfab84458a41573d1754dd9c01f708a8c3e29c21e395", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "610e823f-e160-4dd1-9126-3d07d96aedf4", "node_type": "1", "metadata": {}, "hash": "2bd5ee5757e14d9009141febf29deb688a2c282eda6159678f8c696d279cdcba", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 12564, "end_char_idx": 15302, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", load_in_8bit=True, pad_token_id=0)
```

Now, let's run our example again and measure the memory usage.

```python
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)

result = pipe(prompt, max_new_tokens=60)[0]["generated_text"][len(prompt):]
result
```

**Output**:
```
Here is a Python function that transforms bytes to Giga bytes:\n\n```python\ndef bytes_to_giga_bytes(bytes):\n    return bytes / 1024 / 1024 / 1024\n```\n\nThis function takes a single
```

Nice, we're getting the same result as before, so no loss in accuracy! Let's look at how much memory was used this time.

```python
bytes_to_giga_bytes(torch.cuda.max_memory_allocated())
```

**Output**:
```
15.219234466552734
```

Significantly less! We're down to just a bit over 15 GBs and could therefore run this model on consumer GPUs like the 4090.
We're seeing a very nice gain in memory efficiency and more or less no degradation to the model's output. However, we can also notice a slight slow-down during inference.


We delete the models and flush the memory again.
```python
del model
del pipe
```

```python
flush()
```

Let's see what peak GPU memory consumption 4-bit quantization gives. Quantizing the model to 4-bit can be done with the same API as before - this time by passing `load_in_4bit=True` instead of `load_in_8bit=True`.

```python
model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", load_in_4bit=True, low_cpu_mem_usage=True, pad_token_id=0)

pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)

result = pipe(prompt, max_new_tokens=60)[0]["generated_text"][len(prompt):]
result
```

**Output**:
```
Here is a Python function that transforms bytes to Giga bytes:\n\n```\ndef bytes_to_gigabytes(bytes):\n    return bytes / 1024 / 1024 / 1024\n```\n\nThis function takes a single argument
```

We're almost seeing the same output text as before - just the `python` is missing just before the code snippet. Let's see how much memory was required.

```python
bytes_to_giga_bytes(torch.cuda.max_memory_allocated())
```

**Output**:
```
9.543574333190918
```

Just 9.5GB! That's really not a lot for a >15 billion parameter model.

While we see very little degradation in accuracy for our model here, 4-bit quantization can in practice often lead to different results compared to 8-bit quantization or full `bfloat16` inference. It is up to the user to try it out.

Also note that inference here was again a bit slower compared to 8-bit quantization which is due to the more aggressive quantization method used for 4-bit quantization leading to \\( \text{quantize} \\) and \\( \text{dequantize} \\) taking longer during inference.


key: _node_content
string_value:
{"id_": "610e823f-e160-4dd1-9126-3d07d96aedf4", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ca13b411-c559-43be-ba3c-1bab28a3231e", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "c5212e80043bf9a429e65b0354ba865733d9ecb61838d049bcfee67541c126c2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3da8edcc-76ac-45d9-937f-85e3c870579d", "node_type": "1", "metadata": {}, "hash": "98304f94ad2869bf3228b38524be068ad7f14e0ca8a602f28ad77d8e601015bd", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 13822, "end_char_idx": 16979, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Quantizing the model to 4-bit can be done with the same API as before - this time by passing `load_in_4bit=True` instead of `load_in_8bit=True`.

```python
model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", load_in_4bit=True, low_cpu_mem_usage=True, pad_token_id=0)

pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)

result = pipe(prompt, max_new_tokens=60)[0]["generated_text"][len(prompt):]
result
```

**Output**:
```
Here is a Python function that transforms bytes to Giga bytes:\n\n```\ndef bytes_to_gigabytes(bytes):\n    return bytes / 1024 / 1024 / 1024\n```\n\nThis function takes a single argument
```

We're almost seeing the same output text as before - just the `python` is missing just before the code snippet. Let's see how much memory was required.

```python
bytes_to_giga_bytes(torch.cuda.max_memory_allocated())
```

**Output**:
```
9.543574333190918
```

Just 9.5GB! That's really not a lot for a >15 billion parameter model.

While we see very little degradation in accuracy for our model here, 4-bit quantization can in practice often lead to different results compared to 8-bit quantization or full `bfloat16` inference. It is up to the user to try it out.

Also note that inference here was again a bit slower compared to 8-bit quantization which is due to the more aggressive quantization method used for 4-bit quantization leading to \\( \text{quantize} \\) and \\( \text{dequantize} \\) taking longer during inference.

```python
del model
del pipe
```
```python
flush()
```

Overall, we saw that running OctoCoder in 8-bit precision reduced the required GPU VRAM from 32G GPU VRAM to only 15GB and running the model in 4-bit precision further reduces the required GPU VRAM to just a bit over 9GB.

4-bit quantization allows the model to be run on GPUs such as RTX3090, V100, and T4 which are quite accessible for most people.

For more information on quantization and to see how one can quantize models to require even less GPU VRAM memory than 4-bit, we recommend looking into the [`AutoGPTQ`](https://huggingface.co/docs/transformers/main/en/main_classes/quantization#autogptq-integration%60) implementation.

> As a conclusion, it is important to remember that model quantization trades improved memory efficiency against accuracy and in some cases inference time.

If GPU memory is not a constraint for your use case, there is often no need to look into quantization. However many GPUs simply can't run LLMs without quantization methods and in this case, 4-bit and 8-bit quantization schemes are extremely useful tools.

For more in-detail usage information, we strongly recommend taking a look at the [Transformers Quantization Docs](https://huggingface.co/docs/transformers/main_classes/quantization#general-usage).
Next, let's look into how we can improve computational and memory efficiency by using better algorithms and an improved model architecture.

## 2. Flash Attention

Today's top-performing LLMs share more or less the same fundamental architecture that consists of feed-forward layers, activation layers, layer normalization layers, and most crucially, self-attention layers.


key: _node_content
string_value:
{"id_": "3da8edcc-76ac-45d9-937f-85e3c870579d", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "610e823f-e160-4dd1-9126-3d07d96aedf4", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "22264f169ad35254910c57ac855bb5cd23d205510c68d050670526b697139af4", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "68bcc1cf-6cab-43b3-bfb9-f96b82d01c73", "node_type": "1", "metadata": {}, "hash": "023f51058026d1f146a53e2218eef553bab246f4dd0130463d98121450872a77", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 15304, "end_char_idx": 18322, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
del model
del pipe
```
```python
flush()
```

Overall, we saw that running OctoCoder in 8-bit precision reduced the required GPU VRAM from 32G GPU VRAM to only 15GB and running the model in 4-bit precision further reduces the required GPU VRAM to just a bit over 9GB.

4-bit quantization allows the model to be run on GPUs such as RTX3090, V100, and T4 which are quite accessible for most people.

For more information on quantization and to see how one can quantize models to require even less GPU VRAM memory than 4-bit, we recommend looking into the [`AutoGPTQ`](https://huggingface.co/docs/transformers/main/en/main_classes/quantization#autogptq-integration%60) implementation.

> As a conclusion, it is important to remember that model quantization trades improved memory efficiency against accuracy and in some cases inference time.

If GPU memory is not a constraint for your use case, there is often no need to look into quantization. However many GPUs simply can't run LLMs without quantization methods and in this case, 4-bit and 8-bit quantization schemes are extremely useful tools.

For more in-detail usage information, we strongly recommend taking a look at the [Transformers Quantization Docs](https://huggingface.co/docs/transformers/main_classes/quantization#general-usage).
Next, let's look into how we can improve computational and memory efficiency by using better algorithms and an improved model architecture.

## 2. Flash Attention

Today's top-performing LLMs share more or less the same fundamental architecture that consists of feed-forward layers, activation layers, layer normalization layers, and most crucially, self-attention layers.

Self-attention layers are central to Large Language Models (LLMs) in that they enable the model to understand the contextual relationships between input tokens.
However, the peak GPU memory consumption for self-attention layers grows *quadratically* both in compute and memory complexity with number of input tokens (also called *sequence length*) that we denote in the following by \\( N \\) .
While this is not really noticeable for shorter input sequences (of up to 1000 input tokens), it becomes a serious problem for longer input sequences (at around 16000 input tokens).

Let's take a closer look. The formula to compute the output \\( \mathbf{O} \\) of a self-attention layer for an input \\( \mathbf{X} \\) of length \\( N \\) is:

$$ \textbf{O} = \text{Attn}(\mathbf{X}) = \mathbf{V} \times \text{Softmax}(\mathbf{QK}^T) \text{ with } \mathbf{Q} = \mathbf{W}_q \mathbf{X}, \mathbf{V} = \mathbf{W}_v \mathbf{X}, \mathbf{K} = \mathbf{W}_k \mathbf{X} $$

\\(  \mathbf{X} = (\mathbf{x}_1, ... \mathbf{x}_{N}) \\) is thereby the input sequence to the attention layer. The projections \\( \mathbf{Q} \\) and \\( \mathbf{K} \\) will each consist of \\( N \\) vectors resulting in the \\( \mathbf{QK}^T \\) being of size \\( N^2 \\) .

LLMs usually have multiple attention heads, thus doing multiple self-attention computations in parallel.


key: _node_content
string_value:
{"id_": "68bcc1cf-6cab-43b3-bfb9-f96b82d01c73", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3da8edcc-76ac-45d9-937f-85e3c870579d", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "895e88f176bc2c2ba17b91a376639974bd07efa22186ccddab5c419744cfa648", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3e3a04d4-58c3-48ae-80d8-60385bf39ac6", "node_type": "1", "metadata": {}, "hash": "da13bc0ab8fec21fc3182e9f565ba4eac443cc461ee00d3688e877450f2e616c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 16981, "end_char_idx": 19439, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Self-attention layers are central to Large Language Models (LLMs) in that they enable the model to understand the contextual relationships between input tokens.
However, the peak GPU memory consumption for self-attention layers grows *quadratically* both in compute and memory complexity with number of input tokens (also called *sequence length*) that we denote in the following by \\( N \\) .
While this is not really noticeable for shorter input sequences (of up to 1000 input tokens), it becomes a serious problem for longer input sequences (at around 16000 input tokens).

Let's take a closer look. The formula to compute the output \\( \mathbf{O} \\) of a self-attention layer for an input \\( \mathbf{X} \\) of length \\( N \\) is:

$$ \textbf{O} = \text{Attn}(\mathbf{X}) = \mathbf{V} \times \text{Softmax}(\mathbf{QK}^T) \text{ with } \mathbf{Q} = \mathbf{W}_q \mathbf{X}, \mathbf{V} = \mathbf{W}_v \mathbf{X}, \mathbf{K} = \mathbf{W}_k \mathbf{X} $$

\\(  \mathbf{X} = (\mathbf{x}_1, ... \mathbf{x}_{N}) \\) is thereby the input sequence to the attention layer. The projections \\( \mathbf{Q} \\) and \\( \mathbf{K} \\) will each consist of \\( N \\) vectors resulting in the \\( \mathbf{QK}^T \\) being of size \\( N^2 \\) .

LLMs usually have multiple attention heads, thus doing multiple self-attention computations in parallel.
Assuming, the LLM has 40 attention heads and runs in bfloat16 precision, we can calculate the memory requirement to store the \\( \mathbf{QK^T} \\) matrices to be \\( 40 * 2 * N^2 \\) bytes. For \\( N=1000 \\) only around 50 MB of VRAM are needed, however, for \\( N=16000 \\) we would need 19 GB of VRAM, and for \\( N=100,000 \\) we would need almost 1TB just to store the \\( \mathbf{QK}^T \\) matrices.

Long story short, the default self-attention algorithm quickly becomes prohibitively memory-expensive for large input contexts.

As LLMs improve in text comprehension and generation, they are applied to increasingly complex tasks. While models once handled the translation or summarization of a few sentences, they now manage entire pages, demanding the capability to process extensive input lengths.

How can we get rid of the exorbitant memory requirements for large input lengths? We need a new way to compute the self-attention mechanism that gets rid of the \\( QK^T \\) matrix. [Tri Dao et al.](https://arxiv.org/abs/2205.14135) developed exactly such a new algorithm and called it **Flash Attention**.


key: _node_content
string_value:
{"id_": "3e3a04d4-58c3-48ae-80d8-60385bf39ac6", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "68bcc1cf-6cab-43b3-bfb9-f96b82d01c73", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "f19f4f6cd670f843a2b1174af47de89fbcb980425e74b79ba49cc58b79f514be", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "71e65dd3-5d90-4abf-9625-88800c1a6d1a", "node_type": "1", "metadata": {}, "hash": "60d9ca93c754891cb6388c141a3d9001b9f04f822dabc8d8bb6f27db750c8ba3", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 18053, "end_char_idx": 20731, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The projections \\( \mathbf{Q} \\) and \\( \mathbf{K} \\) will each consist of \\( N \\) vectors resulting in the \\( \mathbf{QK}^T \\) being of size \\( N^2 \\) .

LLMs usually have multiple attention heads, thus doing multiple self-attention computations in parallel.
Assuming, the LLM has 40 attention heads and runs in bfloat16 precision, we can calculate the memory requirement to store the \\( \mathbf{QK^T} \\) matrices to be \\( 40 * 2 * N^2 \\) bytes. For \\( N=1000 \\) only around 50 MB of VRAM are needed, however, for \\( N=16000 \\) we would need 19 GB of VRAM, and for \\( N=100,000 \\) we would need almost 1TB just to store the \\( \mathbf{QK}^T \\) matrices.

Long story short, the default self-attention algorithm quickly becomes prohibitively memory-expensive for large input contexts.

As LLMs improve in text comprehension and generation, they are applied to increasingly complex tasks. While models once handled the translation or summarization of a few sentences, they now manage entire pages, demanding the capability to process extensive input lengths.

How can we get rid of the exorbitant memory requirements for large input lengths? We need a new way to compute the self-attention mechanism that gets rid of the \\( QK^T \\) matrix. [Tri Dao et al.](https://arxiv.org/abs/2205.14135) developed exactly such a new algorithm and called it **Flash Attention**.

In a nutshell, Flash Attention breaks the  \\(\mathbf{V} \times \text{Softmax}(\mathbf{QK}^T\\)) computation apart and instead computes smaller chunks of the output by iterating over multiple softmax computation steps:

$$ \textbf{O}_i \leftarrow s^a_{ij} * \textbf{O}_i + s^b_{ij} * \mathbf{V}_{j} \times \text{Softmax}(\mathbf{QK}^T_{i,j}) \text{ for multiple } i, j \text{ iterations} $$

with \\( s^a_{ij} \\) and \\( s^b_{ij} \\) being some softmax normalization statistics that need to be recomputed for every \\( i \\) and \\( j \\) .

Please note that the whole Flash Attention is a bit more complex and is greatly simplified here as going in too much depth is out of scope for this guide. The reader is invited to take a look at the well-written [Flash Attention paper](https://arxiv.org/abs/2205.14135) for more details.

The main takeaway here is:

> By keeping track of softmax normalization statistics and by using some smart mathematics, Flash Attention gives **numerical identical** outputs compared to the default self-attention layer at a memory cost that only increases linearly with \\( N \\) .

Looking at the formula, one would intuitively say that Flash Attention must be much slower compared to the default self-attention formula as more computation needs to be done.


key: _node_content
string_value:
{"id_": "71e65dd3-5d90-4abf-9625-88800c1a6d1a", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3e3a04d4-58c3-48ae-80d8-60385bf39ac6", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "a4d5c9b165609075480926898cc436827b420c25abe52ac72fffc7b88e979314", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "71dc5314-4b04-4579-98d7-2923ffbda5cc", "node_type": "1", "metadata": {}, "hash": "bee6b6b65bed6cfa10cf27d5134d37246194f246e884428eb00cd4bd5581cd03", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 19215, "end_char_idx": 22592, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
We need a new way to compute the self-attention mechanism that gets rid of the \\( QK^T \\) matrix. [Tri Dao et al.](https://arxiv.org/abs/2205.14135) developed exactly such a new algorithm and called it **Flash Attention**.

In a nutshell, Flash Attention breaks the  \\(\mathbf{V} \times \text{Softmax}(\mathbf{QK}^T\\)) computation apart and instead computes smaller chunks of the output by iterating over multiple softmax computation steps:

$$ \textbf{O}_i \leftarrow s^a_{ij} * \textbf{O}_i + s^b_{ij} * \mathbf{V}_{j} \times \text{Softmax}(\mathbf{QK}^T_{i,j}) \text{ for multiple } i, j \text{ iterations} $$

with \\( s^a_{ij} \\) and \\( s^b_{ij} \\) being some softmax normalization statistics that need to be recomputed for every \\( i \\) and \\( j \\) .

Please note that the whole Flash Attention is a bit more complex and is greatly simplified here as going in too much depth is out of scope for this guide. The reader is invited to take a look at the well-written [Flash Attention paper](https://arxiv.org/abs/2205.14135) for more details.

The main takeaway here is:

> By keeping track of softmax normalization statistics and by using some smart mathematics, Flash Attention gives **numerical identical** outputs compared to the default self-attention layer at a memory cost that only increases linearly with \\( N \\) .

Looking at the formula, one would intuitively say that Flash Attention must be much slower compared to the default self-attention formula as more computation needs to be done. Indeed Flash Attention requires more FLOPs compared to normal attention as the softmax normalization statistics have to constantly be recomputed (see [paper](https://arxiv.org/abs/2205.14135) for more details if interested)

> However, Flash Attention is much faster in inference compared to default attention which comes from its ability to significantly reduce the demands on the slower, high-bandwidth memory of the GPU (VRAM), focusing instead on the faster on-chip memory (SRAM).

Essentially, Flash Attention makes sure that all intermediate write and read operations can be done using the fast *on-chip* SRAM memory instead of having to access the slower VRAM memory to compute the output vector \\( \mathbf{O} \\) .

In practice, there is currently absolutely no reason to **not** use Flash Attention if available. The algorithm gives mathematically the same outputs, and is both faster and more memory-efficient.

Let's look at a practical example.

Our OctoCoder model now gets a significantly longer input prompt which includes a so-called *system prompt*. System prompts are used to steer the LLM into a better assistant that is tailored to the users' task.
In the following, we use a system prompt that will make OctoCoder a better coding assistant.

```python
system_prompt = """Below are a series of dialogues between various people and an AI technical assistant.
The assistant tries to be helpful, polite, honest, sophisticated, emotionally aware, and humble but knowledgeable.
The assistant is happy to help with code questions and will do their best to understand exactly what is needed.
It also tries to avoid giving false or misleading information, and it caveats when it isn't entirely sure about the right answer.
That said, the assistant is practical really does its best, and doesn't let caution get too much in the way of being useful.


key: _node_content
string_value:
{"id_": "71dc5314-4b04-4579-98d7-2923ffbda5cc", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "71e65dd3-5d90-4abf-9625-88800c1a6d1a", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "539beb3591c95a9ffd59e66f3fe28a79fcfd35e235da0ca0c4b8034aa3925af2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "72e0fd37-8c30-4b2c-9812-1e5f57f03692", "node_type": "1", "metadata": {}, "hash": "ec6de3ec1a73968158524336b615c00b29a5022500cefa565d80500b76674616", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 20732, "end_char_idx": 24177, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Indeed Flash Attention requires more FLOPs compared to normal attention as the softmax normalization statistics have to constantly be recomputed (see [paper](https://arxiv.org/abs/2205.14135) for more details if interested)

> However, Flash Attention is much faster in inference compared to default attention which comes from its ability to significantly reduce the demands on the slower, high-bandwidth memory of the GPU (VRAM), focusing instead on the faster on-chip memory (SRAM).

Essentially, Flash Attention makes sure that all intermediate write and read operations can be done using the fast *on-chip* SRAM memory instead of having to access the slower VRAM memory to compute the output vector \\( \mathbf{O} \\) .

In practice, there is currently absolutely no reason to **not** use Flash Attention if available. The algorithm gives mathematically the same outputs, and is both faster and more memory-efficient.

Let's look at a practical example.

Our OctoCoder model now gets a significantly longer input prompt which includes a so-called *system prompt*. System prompts are used to steer the LLM into a better assistant that is tailored to the users' task.
In the following, we use a system prompt that will make OctoCoder a better coding assistant.

```python
system_prompt = """Below are a series of dialogues between various people and an AI technical assistant.
The assistant tries to be helpful, polite, honest, sophisticated, emotionally aware, and humble but knowledgeable.
The assistant is happy to help with code questions and will do their best to understand exactly what is needed.
It also tries to avoid giving false or misleading information, and it caveats when it isn't entirely sure about the right answer.
That said, the assistant is practical really does its best, and doesn't let caution get too much in the way of being useful.

The Starcoder models are a series of 15.5B parameter models trained on 80+ programming languages from The Stack (v1.2) (excluding opt-out requests).
The model uses Multi Query Attention, was trained using the Fill-in-the-Middle objective, and with 8,192 tokens context window for a trillion tokens of heavily deduplicated data.

-----

Question: Write a function that takes two lists and returns a list that has alternating elements from each input list.

Answer: Sure. Here is a function that does that.

def alternating(list1, list2):
   results = []
   for i in range(len(list1)):
       results.append(list1[i])
       results.append(list2[i])
   return results

Question: Can you write some test cases for this function?

Answer: Sure, here are some tests.

assert alternating([10, 20, 30], [1, 2, 3]) == [10, 1, 20, 2, 30, 3]
assert alternating([True, False], [4, 5]) == [True, 4, False, 5]
assert alternating([], []) == []

Question: Modify the function so that it returns all input elements when the lists have uneven length. The elements from the longer list should be at the end.

Answer: Here is the modified function.

def alternating(list1, list2):
   results = []
   for i in range(min(len(list1), len(list2))):
       results.append(list1[i])
       results.append(list2[i])
   if len(list1) > len(list2):
       results.extend(list1[i+1:])
   else:
       results.extend(list2[i+1:])
   return results

-----
"""
```
For demonstration purposes, we duplicate the system prompt by ten so that the input length is long enough to observe Flash Attention's memory savings.


key: _node_content
string_value:
{"id_": "72e0fd37-8c30-4b2c-9812-1e5f57f03692", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "71dc5314-4b04-4579-98d7-2923ffbda5cc", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "56dcc3a11332a9bb16f33c53d76ee1a3be87b1ee0e070dcbe12b8928917d6602", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e3181269-b7ec-41d9-8143-36196caaf159", "node_type": "1", "metadata": {}, "hash": "81edcc7eb0791a113b33f41742762d92cfdabb0372dad5da735ab96b7ee72a8d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 22594, "end_char_idx": 25689, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The Starcoder models are a series of 15.5B parameter models trained on 80+ programming languages from The Stack (v1.2) (excluding opt-out requests).
The model uses Multi Query Attention, was trained using the Fill-in-the-Middle objective, and with 8,192 tokens context window for a trillion tokens of heavily deduplicated data.

-----

Question: Write a function that takes two lists and returns a list that has alternating elements from each input list.

Answer: Sure. Here is a function that does that.

def alternating(list1, list2):
   results = []
   for i in range(len(list1)):
       results.append(list1[i])
       results.append(list2[i])
   return results

Question: Can you write some test cases for this function?

Answer: Sure, here are some tests.

assert alternating([10, 20, 30], [1, 2, 3]) == [10, 1, 20, 2, 30, 3]
assert alternating([True, False], [4, 5]) == [True, 4, False, 5]
assert alternating([], []) == []

Question: Modify the function so that it returns all input elements when the lists have uneven length. The elements from the longer list should be at the end.

Answer: Here is the modified function.

def alternating(list1, list2):
   results = []
   for i in range(min(len(list1), len(list2))):
       results.append(list1[i])
       results.append(list2[i])
   if len(list1) > len(list2):
       results.extend(list1[i+1:])
   else:
       results.extend(list2[i+1:])
   return results

-----
"""
```
For demonstration purposes, we duplicate the system prompt by ten so that the input length is long enough to observe Flash Attention's memory savings.
We append the original text prompt `"Question: Please write a function in Python that transforms bytes to Giga bytes.\n\nAnswer: Here"`

```python
long_prompt = 10 * system_prompt + prompt
```

We instantiate our model again in bfloat16 precision.

```python
model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", torch_dtype=torch.bfloat16, device_map="auto")
tokenizer = AutoTokenizer.from_pretrained("bigcode/octocoder")

pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)
```

Let's now run the model just like before *without Flash Attention* and measure the peak GPU memory requirement and inference time.

```python
import time

start_time = time.time()
result = pipe(long_prompt, max_new_tokens=60)[0]["generated_text"][len(long_prompt):]

print(f"Generated in {time.time() - start_time} seconds.")
result
```

**Output**:
```
Generated in 10.96854019165039 seconds.
Sure. Here is a function that does that.\n\ndef bytes_to_giga(bytes):\n   return bytes / 1024 / 1024 / 1024\n\nAnswer: Sure. Here is a function that does that.\n\ndef
````

We're getting the same output as before, however this time, the model repeats the answer multiple times until it's 60 tokens cut-off. This is not surprising as we've repeated the system prompt ten times for demonstration purposes and thus cued the model to repeat itself.

**Note** that the system prompt should not be repeated ten times in real-world applications - one time is enough!

Let's measure the peak GPU memory requirement.


key: _node_content
string_value:
{"id_": "e3181269-b7ec-41d9-8143-36196caaf159", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "72e0fd37-8c30-4b2c-9812-1e5f57f03692", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "e2dc162f6c3175b6bbbea27979c64ac239b9d255c65e1609f8f63686d9e82cff", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f1d87c36-b045-4983-826d-aac91a6f7a77", "node_type": "1", "metadata": {}, "hash": "ae05df733e7b8251b12aca7853fb9d1b226908defa724bcdf9b88e95dcd21560", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 24178, "end_char_idx": 27345, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
We append the original text prompt `"Question: Please write a function in Python that transforms bytes to Giga bytes.\n\nAnswer: Here"`

```python
long_prompt = 10 * system_prompt + prompt
```

We instantiate our model again in bfloat16 precision.

```python
model = AutoModelForCausalLM.from_pretrained("bigcode/octocoder", torch_dtype=torch.bfloat16, device_map="auto")
tokenizer = AutoTokenizer.from_pretrained("bigcode/octocoder")

pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)
```

Let's now run the model just like before *without Flash Attention* and measure the peak GPU memory requirement and inference time.

```python
import time

start_time = time.time()
result = pipe(long_prompt, max_new_tokens=60)[0]["generated_text"][len(long_prompt):]

print(f"Generated in {time.time() - start_time} seconds.")
result
```

**Output**:
```
Generated in 10.96854019165039 seconds.
Sure. Here is a function that does that.\n\ndef bytes_to_giga(bytes):\n   return bytes / 1024 / 1024 / 1024\n\nAnswer: Sure. Here is a function that does that.\n\ndef
````

We're getting the same output as before, however this time, the model repeats the answer multiple times until it's 60 tokens cut-off. This is not surprising as we've repeated the system prompt ten times for demonstration purposes and thus cued the model to repeat itself.

**Note** that the system prompt should not be repeated ten times in real-world applications - one time is enough!

Let's measure the peak GPU memory requirement.

```python
bytes_to_giga_bytes(torch.cuda.max_memory_allocated())
```

**Output**:
```bash
37.668193340301514
```

As we can see the peak GPU memory requirement is now significantly higher than in the beginning, which is largely due to the longer input sequence. Also the generation takes a little over a minute now.

We call `flush()` to free GPU memory for our next experiment.

```python
flush()
```

For comparison, let's run the same function, but enable Flash Attention instead.
To do so, we convert the model to [BetterTransformer](https://huggingface.co/docs/optimum/bettertransformer/overview) and by doing so enabling PyTorch's [SDPA self-attention](https://pytorch.org/docs/master/generated/torch.nn.functional.scaled_dot_product_attention) which in turn is able to use Flash Attention.

```python
model.to_bettertransformer()
```

Now we run the exact same code snippet as before and under the hood Transformers will make use of Flash Attention.

```py
start_time = time.time()
with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=False):
    result = pipe(long_prompt, max_new_tokens=60)[0]["generated_text"][len(long_prompt):]

print(f"Generated in {time.time() - start_time} seconds.")
result
```

**Output**:
```
Generated in 3.0211617946624756 seconds.
 Sure. Here is a function that does that.\n\ndef bytes_to_giga(bytes):\n   return bytes / 1024 / 1024 / 1024\n\nAnswer: Sure. Here is a function that does that.\n\ndef
```

We're getting the exact same result as before, but can observe a very significant speed-up thanks to Flash Attention.

Let's measure the memory consumption one last time.


key: _node_content
string_value:
{"id_": "f1d87c36-b045-4983-826d-aac91a6f7a77", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e3181269-b7ec-41d9-8143-36196caaf159", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "516dcb65e982cb09387d7fec9e080d13c16955a625b857c20fe5dbdbcbe0943c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "90151a19-c8a5-460e-84dd-462a0c65e8be", "node_type": "1", "metadata": {}, "hash": "b174175882ca439a6bb2ab7a212e4785ef187849050afcede8f6e684397ef1f9", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 25691, "end_char_idx": 28965, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
bytes_to_giga_bytes(torch.cuda.max_memory_allocated())
```

**Output**:
```bash
37.668193340301514
```

As we can see the peak GPU memory requirement is now significantly higher than in the beginning, which is largely due to the longer input sequence. Also the generation takes a little over a minute now.

We call `flush()` to free GPU memory for our next experiment.

```python
flush()
```

For comparison, let's run the same function, but enable Flash Attention instead.
To do so, we convert the model to [BetterTransformer](https://huggingface.co/docs/optimum/bettertransformer/overview) and by doing so enabling PyTorch's [SDPA self-attention](https://pytorch.org/docs/master/generated/torch.nn.functional.scaled_dot_product_attention) which in turn is able to use Flash Attention.

```python
model.to_bettertransformer()
```

Now we run the exact same code snippet as before and under the hood Transformers will make use of Flash Attention.

```py
start_time = time.time()
with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=False):
    result = pipe(long_prompt, max_new_tokens=60)[0]["generated_text"][len(long_prompt):]

print(f"Generated in {time.time() - start_time} seconds.")
result
```

**Output**:
```
Generated in 3.0211617946624756 seconds.
 Sure. Here is a function that does that.\n\ndef bytes_to_giga(bytes):\n   return bytes / 1024 / 1024 / 1024\n\nAnswer: Sure. Here is a function that does that.\n\ndef
```

We're getting the exact same result as before, but can observe a very significant speed-up thanks to Flash Attention.

Let's measure the memory consumption one last time.

```python
bytes_to_giga_bytes(torch.cuda.max_memory_allocated())
```

**Output**:
```
32.617331981658936
```

And we're almost back to our original 29GB peak GPU memory from the beginning.

We can observe that we only use roughly 100MB more GPU memory when passing a very long input sequence with Flash Attention compared to passing a short input sequence as done in the beginning.

```py
flush()
```

For more information on how to use Flash Attention, please have a look at [this doc page](https://huggingface.co/docs/transformers/en/perf_infer_gpu_one#flashattention-2).

## 3. Architectural Innovations

So far we have looked into improving computational and memory efficiency by:

-   Casting the weights to a lower precision format
-   Replacing the self-attention algorithm with a more memory- and compute efficient version

Let's now look into how we can change the architecture of an LLM so that it is most effective and efficient for task that require long text inputs, *e.g.*:
-   Retrieval augmented Questions Answering,
-   Summarization,
-   Chat

Note that *chat* not only requires the LLM to handle long text inputs, but it also necessitates that the LLM is able to efficiently handle the back-and-forth dialogue between user and assistant (such as ChatGPT).

Once trained, the fundamental LLM architecture is difficult to change, so it is important to make considerations about the LLM's tasks beforehand and accordingly optimize the model's architecture.
There are two important components of the model architecture that quickly become memory and/or performance bottlenecks for large input sequences.


key: _node_content
string_value:
{"id_": "90151a19-c8a5-460e-84dd-462a0c65e8be", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f1d87c36-b045-4983-826d-aac91a6f7a77", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "982dbe0f6752637dfc883d12a69a94173c1fb9e7c95125dd31c52b0783e7d652", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b5efe392-7a1b-45eb-8dcd-cb547cf3132f", "node_type": "1", "metadata": {}, "hash": "f477813cd5adf852190df5bb9c246dceac104b413cba1347853ab0228dc94175", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 27294, "end_char_idx": 30558, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Let's measure the memory consumption one last time.

```python
bytes_to_giga_bytes(torch.cuda.max_memory_allocated())
```

**Output**:
```
32.617331981658936
```

And we're almost back to our original 29GB peak GPU memory from the beginning.

We can observe that we only use roughly 100MB more GPU memory when passing a very long input sequence with Flash Attention compared to passing a short input sequence as done in the beginning.

```py
flush()
```

For more information on how to use Flash Attention, please have a look at [this doc page](https://huggingface.co/docs/transformers/en/perf_infer_gpu_one#flashattention-2).

## 3. Architectural Innovations

So far we have looked into improving computational and memory efficiency by:

-   Casting the weights to a lower precision format
-   Replacing the self-attention algorithm with a more memory- and compute efficient version

Let's now look into how we can change the architecture of an LLM so that it is most effective and efficient for task that require long text inputs, *e.g.*:
-   Retrieval augmented Questions Answering,
-   Summarization,
-   Chat

Note that *chat* not only requires the LLM to handle long text inputs, but it also necessitates that the LLM is able to efficiently handle the back-and-forth dialogue between user and assistant (such as ChatGPT).

Once trained, the fundamental LLM architecture is difficult to change, so it is important to make considerations about the LLM's tasks beforehand and accordingly optimize the model's architecture.
There are two important components of the model architecture that quickly become memory and/or performance bottlenecks for large input sequences.

-   The positional embeddings
-   The key-value cache

Let's go over each component in more detail

### 3.1 Improving positional embeddings of LLMs

Self-attention puts each token in relation to each other's tokens.
As an example, the \\( \text{Softmax}(\mathbf{QK}^T) \\) matrix of the text input sequence *"Hello", "I", "love", "you"* could look as follows:

![](/blog/assets/163_optimize_llm/self_attn_tokens.png)

Each word token is given a probability mass at which it attends all other word tokens and, therefore is put into relation with all other word tokens. E.g. the word *"love"* attends to the word *"Hello"* with 5%, to *"I"* with 30%, and to itself with 65%.

A LLM based on self-attention, but without position embeddings would have great difficulties in understanding the positions of the text inputs to each other.
This is because the probability score computed by \\( \mathbf{QK}^T \\) relates each word token to each other word token in \\( O(1) \\) computations regardless of their relative positional distance to each other.
Therefore, for the LLM without position embeddings each token appears to have the same distance to all other tokens, *e.g.* differentiating between *"Hello I love you"* and *"You love I hello"* would be very challenging.

For the LLM to understand sentence order, an additional *cue* is needed and is usually applied in the form of *positional encodings* (or also called *positional embeddings*).
Positional encodings, encode the position of each token into a numerical presentation that the LLM can leverage to better understand sentence order.


key: _node_content
string_value:
{"id_": "b5efe392-7a1b-45eb-8dcd-cb547cf3132f", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "90151a19-c8a5-460e-84dd-462a0c65e8be", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "4972cd960e5ee06ee1a1ee8b555a1f61d84f0c9f11b2116a91767b009f09f243", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4c432876-da89-478d-9848-4f12495f619e", "node_type": "1", "metadata": {}, "hash": "73f2fbbd3c80bae45682a4f88bd216b152d3d9ed185b7a7bf34dec9608ecbb3d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 28820, "end_char_idx": 31803, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
There are two important components of the model architecture that quickly become memory and/or performance bottlenecks for large input sequences.

-   The positional embeddings
-   The key-value cache

Let's go over each component in more detail

### 3.1 Improving positional embeddings of LLMs

Self-attention puts each token in relation to each other's tokens.
As an example, the \\( \text{Softmax}(\mathbf{QK}^T) \\) matrix of the text input sequence *"Hello", "I", "love", "you"* could look as follows:

![](/blog/assets/163_optimize_llm/self_attn_tokens.png)

Each word token is given a probability mass at which it attends all other word tokens and, therefore is put into relation with all other word tokens. E.g. the word *"love"* attends to the word *"Hello"* with 5%, to *"I"* with 30%, and to itself with 65%.

A LLM based on self-attention, but without position embeddings would have great difficulties in understanding the positions of the text inputs to each other.
This is because the probability score computed by \\( \mathbf{QK}^T \\) relates each word token to each other word token in \\( O(1) \\) computations regardless of their relative positional distance to each other.
Therefore, for the LLM without position embeddings each token appears to have the same distance to all other tokens, *e.g.* differentiating between *"Hello I love you"* and *"You love I hello"* would be very challenging.

For the LLM to understand sentence order, an additional *cue* is needed and is usually applied in the form of *positional encodings* (or also called *positional embeddings*).
Positional encodings, encode the position of each token into a numerical presentation that the LLM can leverage to better understand sentence order.

The authors of the [*Attention Is All You Need*](https://arxiv.org/abs/1706.03762) paper introduced sinusoidal positional embeddings \\( \mathbf{P} = \mathbf{p}_1, \ldots, \mathbf{p}_N \\) .
where each vector \\( \mathbf{p}_i \\) is computed as a sinusoidal function of its position \\( i \\) .
The positional encodings are then simply added to the input sequence vectors \\( \mathbf{\hat{X}} = \mathbf{\hat{x}}_1, \ldots, \mathbf{\hat{x}}_N \\) = \\( \mathbf{x}_1 + \mathbf{p}_1, \ldots, \mathbf{x}_N + \mathbf{p}_N \\) thereby cueing the model to better learn sentence order.

Instead of using fixed position embeddings, others (such as [Devlin et al.](https://arxiv.org/abs/1810.04805)) used learned positional encodings for which the positional embeddings
\\( \mathbf{P} \\) are learned during training.

Sinusoidal and learned position embeddings used to be the predominant methods to encode sentence order into LLMs, but a couple of problems related to these positional encodings were found:

  1. Sinusoidal and learned position embeddings are both absolute positional embeddings, *i.e.* encoding a unique embedding for each position id: \\( 0, \ldots, N \\) . As shown by [Huang et al.](https://arxiv.org/abs/2009.13658) and [Su et al.


key: _node_content
string_value:
{"id_": "4c432876-da89-478d-9848-4f12495f619e", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b5efe392-7a1b-45eb-8dcd-cb547cf3132f", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "0bbb3af180c1b66140bc6401011fbd10e38d9188f025e3b229129462a2505e0a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9e6fa64d-23fa-476d-9535-156439d5ad41", "node_type": "1", "metadata": {}, "hash": "3534575b8eb919461581803b041d68e76b87488bd34a642843ae49317445727d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 30410, "end_char_idx": 33251, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Positional encodings, encode the position of each token into a numerical presentation that the LLM can leverage to better understand sentence order.

The authors of the [*Attention Is All You Need*](https://arxiv.org/abs/1706.03762) paper introduced sinusoidal positional embeddings \\( \mathbf{P} = \mathbf{p}_1, \ldots, \mathbf{p}_N \\) .
where each vector \\( \mathbf{p}_i \\) is computed as a sinusoidal function of its position \\( i \\) .
The positional encodings are then simply added to the input sequence vectors \\( \mathbf{\hat{X}} = \mathbf{\hat{x}}_1, \ldots, \mathbf{\hat{x}}_N \\) = \\( \mathbf{x}_1 + \mathbf{p}_1, \ldots, \mathbf{x}_N + \mathbf{p}_N \\) thereby cueing the model to better learn sentence order.

Instead of using fixed position embeddings, others (such as [Devlin et al.](https://arxiv.org/abs/1810.04805)) used learned positional encodings for which the positional embeddings
\\( \mathbf{P} \\) are learned during training.

Sinusoidal and learned position embeddings used to be the predominant methods to encode sentence order into LLMs, but a couple of problems related to these positional encodings were found:

  1. Sinusoidal and learned position embeddings are both absolute positional embeddings, *i.e.* encoding a unique embedding for each position id: \\( 0, \ldots, N \\) . As shown by [Huang et al.](https://arxiv.org/abs/2009.13658) and [Su et al.](https://arxiv.org/abs/2104.09864), absolute positional embeddings lead to poor LLM performance for long text inputs. For long text inputs, it is advantageous if the model learns the relative positional distance input tokens have to each other instead of their absolute position.
  2. When using learned position embeddings, the LLM has to be trained on a fixed input length \\( N \\), which makes it difficult to extrapolate to an input length longer than what it was trained on.

Recently, relative positional embeddings that can tackle the above mentioned problems have become more popular, most notably:

-   [Rotary Position Embedding (RoPE)](https://arxiv.org/abs/2104.09864)
-   [ALiBi](https://arxiv.org/abs/2108.12409)

Both *RoPE* and *ALiBi* argue that it's best to cue the LLM about sentence order directly in the self-attention algorithm as it's there that word tokens are put into relation with each other. More specifically, sentence order should be cued by modifying the \\( \mathbf{QK}^T \\) computation.

Without going into too many details, *RoPE* notes that positional information can be encoded into query-key pairs, *e.g.* \\( \mathbf{q}_i \\) and \\( \mathbf{x}_j \\) by rotating each vector by an angle \\( \theta * i \\) and \\( \theta * j \\) respectively with \\( i, j \\) describing each vectors sentence position:

$$ \mathbf{\hat{q}}_i^T \mathbf{\hat{x}}_j = \mathbf{{q}}_i^T \mathbf{R}_{\theta, i -j} \mathbf{{x}}_j.


key: _node_content
string_value:
{"id_": "9e6fa64d-23fa-476d-9535-156439d5ad41", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4c432876-da89-478d-9848-4f12495f619e", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "4c0be1b0be39510ddcf4ebda86b3b0967ebcbfbdbded9fd8c4bd175cc349dc9e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ff066772-03cb-4dd9-9182-899ddff93fb6", "node_type": "1", "metadata": {}, "hash": "746622e56f12dd42c4e15c33214f92ccb751c5c3fde74580d9681e1527b3f1f7", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 31803, "end_char_idx": 34520, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
](https://arxiv.org/abs/2104.09864), absolute positional embeddings lead to poor LLM performance for long text inputs. For long text inputs, it is advantageous if the model learns the relative positional distance input tokens have to each other instead of their absolute position.
  2. When using learned position embeddings, the LLM has to be trained on a fixed input length \\( N \\), which makes it difficult to extrapolate to an input length longer than what it was trained on.

Recently, relative positional embeddings that can tackle the above mentioned problems have become more popular, most notably:

-   [Rotary Position Embedding (RoPE)](https://arxiv.org/abs/2104.09864)
-   [ALiBi](https://arxiv.org/abs/2108.12409)

Both *RoPE* and *ALiBi* argue that it's best to cue the LLM about sentence order directly in the self-attention algorithm as it's there that word tokens are put into relation with each other. More specifically, sentence order should be cued by modifying the \\( \mathbf{QK}^T \\) computation.

Without going into too many details, *RoPE* notes that positional information can be encoded into query-key pairs, *e.g.* \\( \mathbf{q}_i \\) and \\( \mathbf{x}_j \\) by rotating each vector by an angle \\( \theta * i \\) and \\( \theta * j \\) respectively with \\( i, j \\) describing each vectors sentence position:

$$ \mathbf{\hat{q}}_i^T \mathbf{\hat{x}}_j = \mathbf{{q}}_i^T \mathbf{R}_{\theta, i -j} \mathbf{{x}}_j. $$

\\( \mathbf{R}_{\theta, i - j} \\) thereby represents a rotational matrix. \\( \theta \\) is *not* learned during training, but instead set to a pre-defined value that depends on the maximum input sequence length during training.

> By doing so, the propability score between \\( \mathbf{q}_i \\) and \\( \mathbf{q}_j \\) is only affected if \\( i \ne j \\) and solely depends on the relative distance \\( i - j \\) regardless of each vector's specific positions \\( i \\) and \\( j \\) .

*RoPE* is used in multiple of today's most important LLMs, such as:

-   [**Falcon**](https://huggingface.co/tiiuae/falcon-40b)
-   [**Llama**](https://arxiv.org/abs/2302.13971)
-   [**PaLM**](https://arxiv.org/abs/2204.02311)

As an alternative, *ALiBi* proposes a much simpler relative position encoding scheme. The relative distance that input tokens have to each other is added as a negative integer scaled by a pre-defined value `m` to each query-key entry of the \\( \mathbf{QK}^T \\) matrix right before the softmax computation.

![](/blog/assets/163_optimize_llm/alibi.png)

As shown in the [ALiBi](https://arxiv.org/abs/2108.12409) paper, this simple relative positional encoding allows the model to retain a high performance even at very long text input sequences.


key: _node_content
string_value:
{"id_": "ff066772-03cb-4dd9-9182-899ddff93fb6", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9e6fa64d-23fa-476d-9535-156439d5ad41", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "8c4ccb196e159e1ae787a982818e9084a673e8bfb8fd44b1bbfa8192f7473351", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6dea00bc-9489-4c53-b2f2-2f341c9d5bf6", "node_type": "1", "metadata": {}, "hash": "952fb74b52be8619a9ba89b8c64a0e4e109a868436509abc357a1b1466675bc8", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 33252, "end_char_idx": 36207, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
$$

\\( \mathbf{R}_{\theta, i - j} \\) thereby represents a rotational matrix. \\( \theta \\) is *not* learned during training, but instead set to a pre-defined value that depends on the maximum input sequence length during training.

> By doing so, the propability score between \\( \mathbf{q}_i \\) and \\( \mathbf{q}_j \\) is only affected if \\( i \ne j \\) and solely depends on the relative distance \\( i - j \\) regardless of each vector's specific positions \\( i \\) and \\( j \\) .

*RoPE* is used in multiple of today's most important LLMs, such as:

-   [**Falcon**](https://huggingface.co/tiiuae/falcon-40b)
-   [**Llama**](https://arxiv.org/abs/2302.13971)
-   [**PaLM**](https://arxiv.org/abs/2204.02311)

As an alternative, *ALiBi* proposes a much simpler relative position encoding scheme. The relative distance that input tokens have to each other is added as a negative integer scaled by a pre-defined value `m` to each query-key entry of the \\( \mathbf{QK}^T \\) matrix right before the softmax computation.

![](/blog/assets/163_optimize_llm/alibi.png)

As shown in the [ALiBi](https://arxiv.org/abs/2108.12409) paper, this simple relative positional encoding allows the model to retain a high performance even at very long text input sequences.

*ALiBi* is used in multiple of today's most important LLMs, such as:

-   [**MPT**](https://huggingface.co/mosaicml/mpt-30b)
-   [**BLOOM**](https://huggingface.co/bigscience/bloom)

Both *RoPE* and *ALiBi* position encodings can extrapolate to input lengths not seen during training whereas it has been shown that extrapolation works much better out-of-the-box for *ALiBi* as compared to *RoPE*.
For ALiBi, one simply increases the values of the lower triangular position matrix to match the length of the input sequence.
For *RoPE*, keeping the same \\( \theta \\) that was used during training leads to poor results when passing text inputs much longer than those seen during training, *c.f* [Press et al.](https://arxiv.org/abs/2108.12409). However, the community has found a couple of effective tricks that adapt \\( \theta \\), thereby allowing *RoPE* position embeddings to work well for extrapolated text input sequences (see [here](https://github.com/huggingface/transformers/pull/24653)).

> Both RoPE and ALiBi are relative positional embeddings that are *not* learned during training, but instead are based on the following intuitions:
 -   Positional cues about the text inputs should be given directly to the \\( QK^T \\) matrix of the self-attention layer
 -   The LLM should be incentivized to learn a constant *relative* distance positional encodings have to each other
 -   The further text input tokens are from each other, the lower the probability of their query-value probability. Both RoPE and ALiBi lower the query-key probability of tokens far away from each other. RoPE by decreasing their vector product by increasing the angle between the query-key vectors.


key: _node_content
string_value:
{"id_": "6dea00bc-9489-4c53-b2f2-2f341c9d5bf6", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ff066772-03cb-4dd9-9182-899ddff93fb6", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "be2dbae258c9cdadc18ebcbc10075e5365ece61122b351f4dab0bff429a0e5da", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "63f52b96-d27b-4f4d-b7b7-411444517244", "node_type": "1", "metadata": {}, "hash": "24846d182f5654940a979efdbf2dff9f3fe461faabaf22c36dcce381893c0799", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 34919, "end_char_idx": 38101, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
For ALiBi, one simply increases the values of the lower triangular position matrix to match the length of the input sequence.
For *RoPE*, keeping the same \\( \theta \\) that was used during training leads to poor results when passing text inputs much longer than those seen during training, *c.f* [Press et al.](https://arxiv.org/abs/2108.12409). However, the community has found a couple of effective tricks that adapt \\( \theta \\), thereby allowing *RoPE* position embeddings to work well for extrapolated text input sequences (see [here](https://github.com/huggingface/transformers/pull/24653)).

> Both RoPE and ALiBi are relative positional embeddings that are *not* learned during training, but instead are based on the following intuitions:
 -   Positional cues about the text inputs should be given directly to the \\( QK^T \\) matrix of the self-attention layer
 -   The LLM should be incentivized to learn a constant *relative* distance positional encodings have to each other
 -   The further text input tokens are from each other, the lower the probability of their query-value probability. Both RoPE and ALiBi lower the query-key probability of tokens far away from each other. RoPE by decreasing their vector product by increasing the angle between the query-key vectors. ALiBi by adding large negative numbers to the vector product

In conclusion, LLMs that are intended to be deployed in tasks that require handling large text inputs are better trained with relative positional embeddings, such as RoPE and ALiBi. Also note that even if an LLM with RoPE and ALiBi has been trained only on a fixed length of say \\( N_1 = 2048 \\) it can still be used in practice with text inputs much larger than \\( N_1 \\), like \\( N_2 = 8192 > N_1 \\) by extrapolating the positional embeddings.

### 3.2 The key-value cache

Auto-regressive text generation with LLMs works by iteratively putting in an input sequence, sampling the next token, appending the next token to the input sequence, and continuing to do so until the LLM produces a token that signifies that the generation has finished.

Please have a look at [Transformer's Generate Text Tutorial](https://huggingface.co/docs/transformers/llm_tutorial#generate-text) to get a more visual explanation of how auto-regressive generation works.

Let's run a quick code snippet to show how auto-regressive works in practice. We will simply take the most likely next token via `torch.argmax`.

```python
input_ids = tokenizer(prompt, return_tensors="pt")["input_ids"].to("cuda")

for _ in range(5):
  next_logits = model(input_ids)["logits"][:, -1:]
  next_token_id = torch.argmax(next_logits,dim=-1)

  input_ids = torch.cat([input_ids, next_token_id], dim=-1)
  print("shape of input_ids", input_ids.shape)

generated_text = tokenizer.batch_decode(input_ids[:, -5:])
generated_text
```

**Output**:
```
shape of input_ids torch.Size([1, 21])
shape of input_ids torch.Size([1, 22])
shape of input_ids torch.Size([1, 23])
shape of input_ids torch.Size([1, 24])
shape of input_ids torch.Size([1, 25])
[' Here is a Python function']
```

As we can see every time we increase the text input tokens by the just sampled token.


key: _node_content
string_value:
{"id_": "63f52b96-d27b-4f4d-b7b7-411444517244", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6dea00bc-9489-4c53-b2f2-2f341c9d5bf6", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "ae2231674f74efb1e249a6dc1f8e569d06c3c1fa35218e94b0d73dad2668c6c8", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "aeee1e36-9216-490e-b647-6a3ac25bbf70", "node_type": "1", "metadata": {}, "hash": "38ddc65233b05630bb4c2bb673684fdd350e4e603434d83be896bcdb52d438d9", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 36723, "end_char_idx": 39430, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
### 3.2 The key-value cache

Auto-regressive text generation with LLMs works by iteratively putting in an input sequence, sampling the next token, appending the next token to the input sequence, and continuing to do so until the LLM produces a token that signifies that the generation has finished.

Please have a look at [Transformer's Generate Text Tutorial](https://huggingface.co/docs/transformers/llm_tutorial#generate-text) to get a more visual explanation of how auto-regressive generation works.

Let's run a quick code snippet to show how auto-regressive works in practice. We will simply take the most likely next token via `torch.argmax`.

```python
input_ids = tokenizer(prompt, return_tensors="pt")["input_ids"].to("cuda")

for _ in range(5):
  next_logits = model(input_ids)["logits"][:, -1:]
  next_token_id = torch.argmax(next_logits,dim=-1)

  input_ids = torch.cat([input_ids, next_token_id], dim=-1)
  print("shape of input_ids", input_ids.shape)

generated_text = tokenizer.batch_decode(input_ids[:, -5:])
generated_text
```

**Output**:
```
shape of input_ids torch.Size([1, 21])
shape of input_ids torch.Size([1, 22])
shape of input_ids torch.Size([1, 23])
shape of input_ids torch.Size([1, 24])
shape of input_ids torch.Size([1, 25])
[' Here is a Python function']
```

As we can see every time we increase the text input tokens by the just sampled token.

With very few exceptions, LLMs are trained using the [causal language modeling objective](https://huggingface.co/docs/transformers/tasks/language_modeling#causal-language-modeling) and therefore mask the upper triangle matrix of the attention score - this is why in the two diagrams above the attention scores are left blank (*a.k.a* have 0 probability). For a quick recap on causal language modeling you can refer to the [*Illustrated Self Attention blog*](https://jalammar.github.io/illustrated-gpt2/#part-2-illustrated-self-attention).

As a consequence, tokens *never* depend on previous tokens, more specifically the \\( \mathbf{q}_i \\) vector is never put in relation with any key, values vectors \\( \mathbf{k}_j, \mathbf{v}_j \\) if \\( j > i \\) . Instead \\( \mathbf{q}_i \\) only attends to previous key-value vectors \\( \mathbf{k}_{m < i}, \mathbf{v}_{m < i} \text{ , for } m \in \{0, \ldots i - 1\} \\). In order to reduce unnecessary computation, one can therefore cache each layer's key-value vectors for all previous timesteps.

In the following, we will tell the LLM to make use of the key-value cache by retrieving and forwarding it for each forward pass.
In Transformers, we can retrieve the key-value cache by passing the `use_cache` flag to the `forward` call and can then pass it with the current token.


key: _node_content
string_value:
{"id_": "aeee1e36-9216-490e-b647-6a3ac25bbf70", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "63f52b96-d27b-4f4d-b7b7-411444517244", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "e7070317de8c42cd1197a1f6ca5960c44f07fcf98e46ecc808a3ab01d0023fdf", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "43d3be99-0fc7-493d-8152-ca574c807b21", "node_type": "1", "metadata": {}, "hash": "c9cb2e02b42fc7b6d9c54967d96a5fedc624321fcba4b2a0494b55668d4ef2a9", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 38103, "end_char_idx": 41062, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
With very few exceptions, LLMs are trained using the [causal language modeling objective](https://huggingface.co/docs/transformers/tasks/language_modeling#causal-language-modeling) and therefore mask the upper triangle matrix of the attention score - this is why in the two diagrams above the attention scores are left blank (*a.k.a* have 0 probability). For a quick recap on causal language modeling you can refer to the [*Illustrated Self Attention blog*](https://jalammar.github.io/illustrated-gpt2/#part-2-illustrated-self-attention).

As a consequence, tokens *never* depend on previous tokens, more specifically the \\( \mathbf{q}_i \\) vector is never put in relation with any key, values vectors \\( \mathbf{k}_j, \mathbf{v}_j \\) if \\( j > i \\) . Instead \\( \mathbf{q}_i \\) only attends to previous key-value vectors \\( \mathbf{k}_{m < i}, \mathbf{v}_{m < i} \text{ , for } m \in \{0, \ldots i - 1\} \\). In order to reduce unnecessary computation, one can therefore cache each layer's key-value vectors for all previous timesteps.

In the following, we will tell the LLM to make use of the key-value cache by retrieving and forwarding it for each forward pass.
In Transformers, we can retrieve the key-value cache by passing the `use_cache` flag to the `forward` call and can then pass it with the current token.

```python
past_key_values = None # past_key_values is the key-value cache
generated_tokens = []
next_token_id = tokenizer(prompt, return_tensors="pt")["input_ids"].to("cuda")

for _ in range(5):
  next_logits, past_key_values = model(next_token_id, past_key_values=past_key_values, use_cache=True).to_tuple()
  next_logits = next_logits[:, -1:]
  next_token_id = torch.argmax(next_logits, dim=-1)

  print("shape of input_ids", next_token_id.shape)
  print("length of key-value cache", len(past_key_values[0][0]))  # past_key_values are of shape [num_layers, 0 for k, 1 for v, batch_size, length, hidden_dim]
  generated_tokens.append(next_token_id.item())

generated_text = tokenizer.batch_decode(generated_tokens)
generated_text
```

**Output**:
```
shape of input_ids torch.Size([1, 1])
length of key-value cache 20
shape of input_ids torch.Size([1, 1])
length of key-value cache 21
shape of input_ids torch.Size([1, 1])
length of key-value cache 22
shape of input_ids torch.Size([1, 1])
length of key-value cache 23
shape of input_ids torch.Size([1, 1])
length of key-value cache 24
[' Here', ' is', ' a', ' Python', ' function']
```

As one can see, when using the key-value cache the text input tokens are *not* increased in length, but remain a single input vector. The length of the key-value cache on the other hand is increased by one at every decoding step.

> Making use of the key-value cache means that the \\( \mathbf{QK}^T \\) is essentially reduced to \\( \mathbf{q}_c\mathbf{K}^T \\) with \\( \mathbf{q}_c \\) being the query projection of the currently passed input token which is *always* just a single vector.


key: _node_content
string_value:
{"id_": "43d3be99-0fc7-493d-8152-ca574c807b21", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "aeee1e36-9216-490e-b647-6a3ac25bbf70", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "8ff82756446e934344f8c369afa75167858611f14496a80b6b90afb23121a0eb", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f63fc3fd-a036-4848-82c3-cd829c2bd0c0", "node_type": "1", "metadata": {}, "hash": "c832afa7bcef6ea2ae20d8655703169ec0723f3edd6dab0de438c5a0c675a7a9", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 40705, "end_char_idx": 44120, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The length of the key-value cache on the other hand is increased by one at every decoding step.

> Making use of the key-value cache means that the \\( \mathbf{QK}^T \\) is essentially reduced to \\( \mathbf{q}_c\mathbf{K}^T \\) with \\( \mathbf{q}_c \\) being the query projection of the currently passed input token which is *always* just a single vector.

Using the key-value cache has two advantages:
-   Significant increase in computational efficiency as less computations are performed compared to computing the full \\( \mathbf{QK}^T \\) matrix. This leads to an increase in inference speed
-   The maximum required memory is not increased quadratically with the number of generated tokens, but only increases linearly.

> One should *always* make use of the key-value cache as it leads to identical results and a significant speed-up for longer input sequences. Transformers has the key-value cache enabled by default when making use of the text pipeline or the [`generate` method](https://huggingface.co/docs/transformers/main_classes/text_generation).

<Tip warning={true}>

Note that, despite our advice to use key-value caches, your LLM output may be slightly different when you use them. This is a property of the matrix multiplication kernels themselves -- you can read more about it [here](https://github.com/huggingface/transformers/issues/25420#issuecomment-1775317535).

</Tip>

#### 3.2.1 Multi-round conversation

The key-value cache is especially useful for applications such as chat where multiple passes of auto-regressive decoding are required. Let's look at an example.

```
User: How many people live in France?
Assistant: Roughly 75 million people live in France
User: And how many are in Germany?
Assistant: Germany has ca. 81 million inhabitants
```

In this chat, the LLM runs auto-regressive decoding twice:
  1. The first time, the key-value cache is empty and the input prompt is `"User: How many people live in France?"` and the model auto-regressively generates the text `"Roughly 75 million people live in France"` while increasing the key-value cache at every decoding step.
  2. The second time the input prompt is `"User: How many people live in France? \n Assistant: Roughly 75 million people live in France \n User: And how many in Germany?"`. Thanks to the cache, all key-value vectors for the first two sentences are already computed. Therefore the input prompt only consists of `"User: And how many in Germany?"`. While processing the shortened input prompt, its computed key-value vectors are concatenated to the key-value cache of the first decoding. The second Assistant's answer `"Germany has ca. 81 million inhabitants"` is then auto-regressively generated with the key-value cache consisting of encoded key-value vectors of `"User: How many people live in France? \n Assistant: Roughly 75 million people live in France \n User: And how many are in Germany?"`.

Two things should be noted here:
  1. Keeping all the context is crucial for LLMs deployed in chat so that the LLM understands all the previous context of the conversation. E.g. for the example above the LLM needs to understand that the user refers to the population when asking `"And how many are in Germany"`.
  2. The key-value cache is extremely useful for chat as it allows us to continuously grow the encoded chat history instead of having to re-encode the chat history again from scratch (as e.g.


key: _node_content
string_value:
{"id_": "f63fc3fd-a036-4848-82c3-cd829c2bd0c0", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "43d3be99-0fc7-493d-8152-ca574c807b21", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "8c9a8999caaeca3a1567cab8d7d0b9f1920bb677fa357b0b1c0b626a04de010f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4c324d4a-9d58-4a44-953d-b6e98dfffec8", "node_type": "1", "metadata": {}, "hash": "e6a25a528f08e3d1fa9da16f79acd34fba42d3e739ac537ec1924e877d695fd9", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 42431, "end_char_idx": 45856, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Assistant: Germany has ca. 81 million inhabitants
```

In this chat, the LLM runs auto-regressive decoding twice:
  1. The first time, the key-value cache is empty and the input prompt is `"User: How many people live in France?"` and the model auto-regressively generates the text `"Roughly 75 million people live in France"` while increasing the key-value cache at every decoding step.
  2. The second time the input prompt is `"User: How many people live in France? \n Assistant: Roughly 75 million people live in France \n User: And how many in Germany?"`. Thanks to the cache, all key-value vectors for the first two sentences are already computed. Therefore the input prompt only consists of `"User: And how many in Germany?"`. While processing the shortened input prompt, its computed key-value vectors are concatenated to the key-value cache of the first decoding. The second Assistant's answer `"Germany has ca. 81 million inhabitants"` is then auto-regressively generated with the key-value cache consisting of encoded key-value vectors of `"User: How many people live in France? \n Assistant: Roughly 75 million people live in France \n User: And how many are in Germany?"`.

Two things should be noted here:
  1. Keeping all the context is crucial for LLMs deployed in chat so that the LLM understands all the previous context of the conversation. E.g. for the example above the LLM needs to understand that the user refers to the population when asking `"And how many are in Germany"`.
  2. The key-value cache is extremely useful for chat as it allows us to continuously grow the encoded chat history instead of having to re-encode the chat history again from scratch (as e.g. would be the case when using an encoder-decoder architecture).

In `transformers`, a `generate` call will return `past_key_values` when `return_dict_in_generate=True` is passed, in addition to the default `use_cache=True`. Note that it is not yet available through the `pipeline` interface.

```python
# Generation as usual
prompt = system_prompt + "Question: Please write a function in Python that transforms bytes to Giga bytes.\n\nAnswer: Here"
model_inputs = tokenizer(prompt, return_tensors='pt')
generation_output = model.generate(**model_inputs, max_new_tokens=60, return_dict_in_generate=True)
decoded_output = tokenizer.batch_decode(generation_output.sequences)[0]

# Piping the returned `past_key_values` to speed up the next conversation round
prompt = decoded_output + "\nQuestion: How can I modify the function above to return Mega bytes instead?\n\nAnswer: Here"
model_inputs = tokenizer(prompt, return_tensors='pt')
generation_output = model.generate(
  **model_inputs,
  past_key_values=generation_output.past_key_values,
  max_new_tokens=60,
  return_dict_in_generate=True
)
tokenizer.batch_decode(generation_output.sequences)[0][len(prompt):]
```

**Output**:
```
 is a modified version of the function that returns Mega bytes instead.

def bytes_to_megabytes(bytes):
   return bytes / 1024 / 1024

Answer: The function takes a number of bytes as input and returns the number of
```

Great, no additional time is spent recomputing the same key and values for the attention layer! There is however one catch. While the required peak memory for the \\( \mathbf{QK}^T \\) matrix is significantly reduced, holding the key-value cache in memory can become very memory expensive for long input sequences or multi-turn chat.


key: _node_content
string_value:
{"id_": "4c324d4a-9d58-4a44-953d-b6e98dfffec8", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f63fc3fd-a036-4848-82c3-cd829c2bd0c0", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "af7fe762ab2d1d788a352dcae8d67faae696c12653c1c469d1646b379dbc93d3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2b239709-a544-4cce-9618-7ac3c7c3971c", "node_type": "1", "metadata": {}, "hash": "524d0e520cea28535feab9b2014e35857168fe5d735eca875ea09c947aa6f6bb", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 44121, "end_char_idx": 47413, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
would be the case when using an encoder-decoder architecture).

In `transformers`, a `generate` call will return `past_key_values` when `return_dict_in_generate=True` is passed, in addition to the default `use_cache=True`. Note that it is not yet available through the `pipeline` interface.

```python
# Generation as usual
prompt = system_prompt + "Question: Please write a function in Python that transforms bytes to Giga bytes.\n\nAnswer: Here"
model_inputs = tokenizer(prompt, return_tensors='pt')
generation_output = model.generate(**model_inputs, max_new_tokens=60, return_dict_in_generate=True)
decoded_output = tokenizer.batch_decode(generation_output.sequences)[0]

# Piping the returned `past_key_values` to speed up the next conversation round
prompt = decoded_output + "\nQuestion: How can I modify the function above to return Mega bytes instead?\n\nAnswer: Here"
model_inputs = tokenizer(prompt, return_tensors='pt')
generation_output = model.generate(
  **model_inputs,
  past_key_values=generation_output.past_key_values,
  max_new_tokens=60,
  return_dict_in_generate=True
)
tokenizer.batch_decode(generation_output.sequences)[0][len(prompt):]
```

**Output**:
```
 is a modified version of the function that returns Mega bytes instead.

def bytes_to_megabytes(bytes):
   return bytes / 1024 / 1024

Answer: The function takes a number of bytes as input and returns the number of
```

Great, no additional time is spent recomputing the same key and values for the attention layer! There is however one catch. While the required peak memory for the \\( \mathbf{QK}^T \\) matrix is significantly reduced, holding the key-value cache in memory can become very memory expensive for long input sequences or multi-turn chat. Remember that the key-value cache needs to store the key-value vectors for all previous input vectors \\( \mathbf{x}_i \text{, for } i \in \{1, \ldots, c - 1\} \\) for all self-attention layers and for all attention heads.

Let's compute the number of float values that need to be stored in the key-value cache for the LLM `bigcode/octocoder` that we used before.
The number of float values amounts to two times the sequence length times the number of attention heads times the attention head dimension and times the number of layers.
Computing this for our LLM at a hypothetical input sequence length of 16000 gives:

```python
config = model.config
2 * 16_000 * config.n_layer * config.n_head * config.n_embd // config.n_head
```

**Output**:
```
7864320000
```

Roughly 8 billion float values! Storing 8 billion float values in `float16` precision requires around 15 GB of RAM which is circa half as much as the model weights themselves!
Researchers have proposed two methods that allow to significantly reduce the memory cost of storing the key-value cache, which are explored in the next subsections.

#### 3.2.2 Multi-Query-Attention (MQA)

[Multi-Query-Attention](https://arxiv.org/abs/1911.02150) was proposed in Noam Shazeer's *Fast Transformer Decoding: One Write-Head is All You Need* paper. As the title says, Noam found out that instead of using `n_head` key-value projections weights, one can use a single head-value projection weight pair that is shared across all attention heads without that the model's performance significantly degrades.


key: _node_content
string_value:
{"id_": "2b239709-a544-4cce-9618-7ac3c7c3971c", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4c324d4a-9d58-4a44-953d-b6e98dfffec8", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "082abd1d6d8c9875ceaab67e38f08cc0924f043ff666c9ce3b7e1cc860d81116", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5811e301-dc53-4fad-89de-10d458649217", "node_type": "1", "metadata": {}, "hash": "2f9aef044376b19a83561c3b824f0b12907f2a65f86634c6467705a331caf24c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 45857, "end_char_idx": 49033, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Remember that the key-value cache needs to store the key-value vectors for all previous input vectors \\( \mathbf{x}_i \text{, for } i \in \{1, \ldots, c - 1\} \\) for all self-attention layers and for all attention heads.

Let's compute the number of float values that need to be stored in the key-value cache for the LLM `bigcode/octocoder` that we used before.
The number of float values amounts to two times the sequence length times the number of attention heads times the attention head dimension and times the number of layers.
Computing this for our LLM at a hypothetical input sequence length of 16000 gives:

```python
config = model.config
2 * 16_000 * config.n_layer * config.n_head * config.n_embd // config.n_head
```

**Output**:
```
7864320000
```

Roughly 8 billion float values! Storing 8 billion float values in `float16` precision requires around 15 GB of RAM which is circa half as much as the model weights themselves!
Researchers have proposed two methods that allow to significantly reduce the memory cost of storing the key-value cache, which are explored in the next subsections.

#### 3.2.2 Multi-Query-Attention (MQA)

[Multi-Query-Attention](https://arxiv.org/abs/1911.02150) was proposed in Noam Shazeer's *Fast Transformer Decoding: One Write-Head is All You Need* paper. As the title says, Noam found out that instead of using `n_head` key-value projections weights, one can use a single head-value projection weight pair that is shared across all attention heads without that the model's performance significantly degrades.

> By using a single head-value projection weight pair, the key value vectors \\( \mathbf{k}_i, \mathbf{v}_i \\) have to be identical across all attention heads which in turn means that we only need to store 1 key-value projection pair in the cache instead of `n_head` ones.

As most LLMs use between 20 and 100 attention heads, MQA significantly reduces the memory consumption of the key-value cache. For the LLM used in this notebook we could therefore reduce the required memory consumption from 15 GB to less than 400 MB at an input sequence length of 16000.

In addition to memory savings, MQA also leads to improved computational efficiency as explained in the following.
In auto-regressive decoding, large key-value vectors need to be reloaded, concatenated with the current key-value vector pair to be then fed into the \\( \mathbf{q}_c\mathbf{K}^T \\) computation at every step. For auto-regressive decoding, the required memory bandwidth for the constant reloading can become a serious time bottleneck. By reducing the size of the key-value vectors less memory needs to be accessed, thus reducing the memory bandwidth bottleneck. For more detail, please have a look at [Noam's paper](https://arxiv.org/abs/1911.02150).

The important part to understand here is that reducing the number of key-value attention heads to 1 only makes sense if a key-value cache is used. The peak memory consumption of the model for a single forward pass without key-value cache stays unchanged as every attention head still has a unique query vector so that each attention head still has a different \\( \mathbf{QK}^T \\) matrix.


key: _node_content
string_value:
{"id_": "5811e301-dc53-4fad-89de-10d458649217", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2b239709-a544-4cce-9618-7ac3c7c3971c", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "a7ba4463be8a9e8144506008bd4f51057f1c8c4ed497910b5898f6e965fbf885", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9a19c892-aa5c-44c5-9248-4ae527c43a72", "node_type": "1", "metadata": {}, "hash": "4d0c12a767cc74b6f797ad5b803029e6b60621621d01de4b0e5e8c187795d1d1", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 47415, "end_char_idx": 50613, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
> By using a single head-value projection weight pair, the key value vectors \\( \mathbf{k}_i, \mathbf{v}_i \\) have to be identical across all attention heads which in turn means that we only need to store 1 key-value projection pair in the cache instead of `n_head` ones.

As most LLMs use between 20 and 100 attention heads, MQA significantly reduces the memory consumption of the key-value cache. For the LLM used in this notebook we could therefore reduce the required memory consumption from 15 GB to less than 400 MB at an input sequence length of 16000.

In addition to memory savings, MQA also leads to improved computational efficiency as explained in the following.
In auto-regressive decoding, large key-value vectors need to be reloaded, concatenated with the current key-value vector pair to be then fed into the \\( \mathbf{q}_c\mathbf{K}^T \\) computation at every step. For auto-regressive decoding, the required memory bandwidth for the constant reloading can become a serious time bottleneck. By reducing the size of the key-value vectors less memory needs to be accessed, thus reducing the memory bandwidth bottleneck. For more detail, please have a look at [Noam's paper](https://arxiv.org/abs/1911.02150).

The important part to understand here is that reducing the number of key-value attention heads to 1 only makes sense if a key-value cache is used. The peak memory consumption of the model for a single forward pass without key-value cache stays unchanged as every attention head still has a unique query vector so that each attention head still has a different \\( \mathbf{QK}^T \\) matrix.

MQA has seen wide adoption by the community and is now used by many of the most popular LLMs:

-   [**Falcon**](https://huggingface.co/tiiuae/falcon-40b)
-   [**PaLM**](https://arxiv.org/abs/2204.02311)
-   [**MPT**](https://huggingface.co/mosaicml/mpt-30b)
-   [**BLOOM**](https://huggingface.co/bigscience/bloom)

Also, the checkpoint used in this notebook - `bigcode/octocoder` - makes use of MQA.

#### 3.2.3 Grouped-Query-Attention (GQA)

[Grouped-Query-Attention](https://arxiv.org/abs/2305.13245), as proposed by Ainslie et al. from Google, found that using MQA can often lead to quality degradation compared to using vanilla multi-key-value head projections. The paper argues that more model performance can be kept by less drastically reducing the number of query head projection weights. Instead of using just a single key-value projection weight, `n < n_head` key-value projection weights should be used. By choosing `n` to a significantly smaller value than `n_head`, such as 2,4 or 8 almost all of the memory and speed gains from MQA can be kept while sacrificing less model capacity and thus arguably less performance.

Moreover, the authors of GQA found out that existing model checkpoints can be *uptrained* to have a GQA architecture with as little as 5% of the original pre-training compute. While 5% of the original pre-training compute can still be a massive amount, GQA *uptraining* allows existing checkpoints to be useful for longer input sequences.

GQA was only recently proposed which is why there is less adoption at the time of writing this notebook.


key: _node_content
string_value:
{"id_": "9a19c892-aa5c-44c5-9248-4ae527c43a72", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1cc768eb-0be4-4be0-813a-900b9d9d3ae2", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5811e301-dc53-4fad-89de-10d458649217", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "047ee3ed3362d8f7782526a3533928ba32db8119546628ffc11db6adbcd4cb92", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 49035, "end_char_idx": 51979, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
MQA has seen wide adoption by the community and is now used by many of the most popular LLMs:

-   [**Falcon**](https://huggingface.co/tiiuae/falcon-40b)
-   [**PaLM**](https://arxiv.org/abs/2204.02311)
-   [**MPT**](https://huggingface.co/mosaicml/mpt-30b)
-   [**BLOOM**](https://huggingface.co/bigscience/bloom)

Also, the checkpoint used in this notebook - `bigcode/octocoder` - makes use of MQA.

#### 3.2.3 Grouped-Query-Attention (GQA)

[Grouped-Query-Attention](https://arxiv.org/abs/2305.13245), as proposed by Ainslie et al. from Google, found that using MQA can often lead to quality degradation compared to using vanilla multi-key-value head projections. The paper argues that more model performance can be kept by less drastically reducing the number of query head projection weights. Instead of using just a single key-value projection weight, `n < n_head` key-value projection weights should be used. By choosing `n` to a significantly smaller value than `n_head`, such as 2,4 or 8 almost all of the memory and speed gains from MQA can be kept while sacrificing less model capacity and thus arguably less performance.

Moreover, the authors of GQA found out that existing model checkpoints can be *uptrained* to have a GQA architecture with as little as 5% of the original pre-training compute. While 5% of the original pre-training compute can still be a massive amount, GQA *uptraining* allows existing checkpoints to be useful for longer input sequences.

GQA was only recently proposed which is why there is less adoption at the time of writing this notebook.
The most notable application of GQA is [Llama-v2](https://huggingface.co/meta-llama/Llama-2-70b-hf).

> As a conclusion, it is strongly recommended to make use of either GQA or MQA if the LLM is deployed with auto-regressive decoding and is required to handle large input sequences as is the case for example for chat.


## Conclusion

The research community is constantly coming up with new, nifty ways to speed up inference time for ever-larger LLMs. As an example, one such promising research direction is [speculative decoding](https://arxiv.org/abs/2211.17192) where "easy tokens" are generated by smaller, faster language models and only "hard tokens" are generated by the LLM itself. Going into more detail is out of the scope of this notebook, but can be read upon in this [nice blog post](https://huggingface.co/blog/assisted-generation).

The reason massive LLMs such as GPT3/4, Llama-2-70b, Claude, PaLM can run so quickly in chat-interfaces such as [Hugging Face Chat](https://huggingface.co/chat/) or ChatGPT is to a big part thanks to the above-mentioned improvements in precision, algorithms, and architecture.
Going forward, accelerators such as GPUs, TPUs, etc... will only get faster and allow for more memory, but one should nevertheless always make sure to use the best available algorithms and architectures to get the most bang for your buck 🤗


key: _node_content
string_value:
{"id_": "c0052697-2eea-458c-9e52-acc525427740", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "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": "044f3f9e-c9b6-4baa-9d16-c07cb19fe076", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "retrieve_doc": true, "source": "transformers"}, "hash": "4b86826f9bba621d3a707f6c4a2a50ed5b41d45f61784aba4ab515f105c22b0c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b8acacd0-dbc9-4860-ad46-d1cae1256d16", "node_type": "1", "metadata": {}, "hash": "50fd5a5adc056831bc2fd61cbe8f4893a067c37e99242b8064a19275778eba10", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3078, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Pipelines for inference

The [`pipeline`] makes it simple to use any model from the [Hub](https://huggingface.co/models) for inference on any language, computer vision, speech, and multimodal tasks. Even if you don't have experience with a specific modality or aren't familiar with the underlying code behind the models, you can still use them for inference with the [`pipeline`]! This tutorial will teach you to:

* Use a [`pipeline`] for inference.
* Use a specific tokenizer or model.
* Use a [`pipeline`] for audio, vision, and multimodal tasks.

<Tip>

Take a look at the [`pipeline`] documentation for a complete list of supported tasks and available parameters.

</Tip>

## Pipeline usage

While each task has an associated [`pipeline`], it is simpler to use the general [`pipeline`] abstraction which contains 
all the task-specific pipelines. The [`pipeline`] automatically loads a default model and a preprocessing class capable 
of inference for your task. Let's take the example of using the [`pipeline`] for automatic speech recognition (ASR), or
speech-to-text.


1. Start by creating a [`pipeline`] and specify the inference task:

```py
>>> from transformers import pipeline

>>> transcriber = pipeline(task="automatic-speech-recognition")
```

2. Pass your input to the [`pipeline`]. In the case of speech recognition, this is an audio input file:

```py
>>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
{'text': 'I HAVE A DREAM BUT ONE DAY THIS NATION WILL RISE UP LIVE UP THE TRUE MEANING OF ITS TREES'}
```

Not the result you had in mind? Check out some of the [most downloaded automatic speech recognition models](https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&sort=trending) 
on the Hub to see if you can get a better transcription.

Let's try the [Whisper large-v2](https://huggingface.co/openai/whisper-large) model from OpenAI. Whisper was released 
2 years later than Wav2Vec2, and was trained on close to 10x more data. As such, it beats Wav2Vec2 on most downstream 
benchmarks. It also has the added benefit of predicting punctuation and casing, neither of which are possible with  
Wav2Vec2.

Let's give it a try here to see how it performs:

```py
>>> transcriber = pipeline(model="openai/whisper-large-v2")
>>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'}
```

Now this result looks more accurate! For a deep-dive comparison on Wav2Vec2 vs Whisper, refer to the [Audio Transformers Course](https://huggingface.co/learn/audio-course/chapter5/asr_models).
We really encourage you to check out the Hub for models in different languages, models specialized in your field, and more.
You can check out and compare model results directly from your browser on the Hub to see if it fits or 
handles corner cases better than other ones.
And if you don't find a model for your use case, you can always start [training](training) your own!


key: _node_content
string_value:
{"id_": "b8acacd0-dbc9-4860-ad46-d1cae1256d16", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "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": "044f3f9e-c9b6-4baa-9d16-c07cb19fe076", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "retrieve_doc": true, "source": "transformers"}, "hash": "4b86826f9bba621d3a707f6c4a2a50ed5b41d45f61784aba4ab515f105c22b0c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c0052697-2eea-458c-9e52-acc525427740", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "retrieve_doc": true, "source": "transformers"}, "hash": "3230cca99df2f42629a0f2fae45faa7066d52e118a27bf4f61686247404d4326", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "0e693fe2-25fb-4408-b3d7-0f66586cfc78", "node_type": "1", "metadata": {}, "hash": "35006ca7c198b75ee86aa5ac99db349e52adabda3fb962b33bd29f1e7792996d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1603, "end_char_idx": 4776, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Check out some of the [most downloaded automatic speech recognition models](https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&sort=trending) 
on the Hub to see if you can get a better transcription.

Let's try the [Whisper large-v2](https://huggingface.co/openai/whisper-large) model from OpenAI. Whisper was released 
2 years later than Wav2Vec2, and was trained on close to 10x more data. As such, it beats Wav2Vec2 on most downstream 
benchmarks. It also has the added benefit of predicting punctuation and casing, neither of which are possible with  
Wav2Vec2.

Let's give it a try here to see how it performs:

```py
>>> transcriber = pipeline(model="openai/whisper-large-v2")
>>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'}
```

Now this result looks more accurate! For a deep-dive comparison on Wav2Vec2 vs Whisper, refer to the [Audio Transformers Course](https://huggingface.co/learn/audio-course/chapter5/asr_models).
We really encourage you to check out the Hub for models in different languages, models specialized in your field, and more.
You can check out and compare model results directly from your browser on the Hub to see if it fits or 
handles corner cases better than other ones.
And if you don't find a model for your use case, you can always start [training](training) your own!

If you have several inputs, you can pass your input as a list:

```py
transcriber(
    [
        "https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac",
        "https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac",
    ]
)
```

Pipelines are great for experimentation as switching from one model to another is trivial; however, there are some ways to optimize them for larger workloads than experimentation. See the following guides that dive into iterating over whole datasets or using pipelines in a webserver:
of the docs:
* [Using pipelines on a dataset](#using-pipelines-on-a-dataset)
* [Using pipelines for a webserver](./pipeline_webserver)

## Parameters

[`pipeline`] supports many parameters; some are task specific, and some are general to all pipelines.
In general, you can specify parameters anywhere you want:

```py
transcriber = pipeline(model="openai/whisper-large-v2", my_parameter=1)

out = transcriber(...)  # This will use `my_parameter=1`.
out = transcriber(..., my_parameter=2)  # This will override and use `my_parameter=2`.
out = transcriber(...)  # This will go back to using `my_parameter=1`.
```

Let's check out 3 important ones:

### Device

If you use `device=n`, the pipeline automatically puts the model on the specified device.
This will work regardless of whether you are using PyTorch or Tensorflow.

```py
transcriber = pipeline(model="openai/whisper-large-v2", device=0)
```

If the model is too large for a single GPU and you are using PyTorch, you can set `torch_dtype='float16'` to enable FP16 precision inference. Usually this would not cause significant performance drops but make sure you evaluate it on your models!


key: _node_content
string_value:
{"id_": "0e693fe2-25fb-4408-b3d7-0f66586cfc78", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "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": "044f3f9e-c9b6-4baa-9d16-c07cb19fe076", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "retrieve_doc": true, "source": "transformers"}, "hash": "4b86826f9bba621d3a707f6c4a2a50ed5b41d45f61784aba4ab515f105c22b0c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b8acacd0-dbc9-4860-ad46-d1cae1256d16", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "retrieve_doc": true, "source": "transformers"}, "hash": "651bdff68b9b567c4ea6bb99b3e9606f3bef567e3b6ac0f585f116700ee764c9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "eb64f74a-9ae9-4f8f-ac76-e09b04dd2ead", "node_type": "1", "metadata": {}, "hash": "f5a60559e3778ed0ebe7c7c7bc00cf888d81660b2dbc26f23d14217a76e8e30d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3524, "end_char_idx": 6802, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
See the following guides that dive into iterating over whole datasets or using pipelines in a webserver:
of the docs:
* [Using pipelines on a dataset](#using-pipelines-on-a-dataset)
* [Using pipelines for a webserver](./pipeline_webserver)

## Parameters

[`pipeline`] supports many parameters; some are task specific, and some are general to all pipelines.
In general, you can specify parameters anywhere you want:

```py
transcriber = pipeline(model="openai/whisper-large-v2", my_parameter=1)

out = transcriber(...)  # This will use `my_parameter=1`.
out = transcriber(..., my_parameter=2)  # This will override and use `my_parameter=2`.
out = transcriber(...)  # This will go back to using `my_parameter=1`.
```

Let's check out 3 important ones:

### Device

If you use `device=n`, the pipeline automatically puts the model on the specified device.
This will work regardless of whether you are using PyTorch or Tensorflow.

```py
transcriber = pipeline(model="openai/whisper-large-v2", device=0)
```

If the model is too large for a single GPU and you are using PyTorch, you can set `torch_dtype='float16'` to enable FP16 precision inference. Usually this would not cause significant performance drops but make sure you evaluate it on your models!

Alternatively, you can set `device_map="auto"` to automatically 
determine how to load and store the model weights. Using the `device_map` argument requires the 🤗 [Accelerate](https://huggingface.co/docs/accelerate)
package:

```bash
pip install --upgrade accelerate
```

The following code automatically loads and stores model weights across devices:

```py
transcriber = pipeline(model="openai/whisper-large-v2", device_map="auto")
```

Note that if  `device_map="auto"` is passed, there is no need to add the argument `device=device` when instantiating your `pipeline` as you may encounter some unexpected behavior!

### Batch size

By default, pipelines will not batch inference for reasons explained in detail [here](https://huggingface.co/docs/transformers/main_classes/pipelines#pipeline-batching). The reason is that batching is not necessarily faster, and can actually be quite slower in some cases.

But if it works in your use case, you can use:

```py
transcriber = pipeline(model="openai/whisper-large-v2", device=0, batch_size=2)
audio_filenames = [f"https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/{i}.flac" for i in range(1, 5)]
texts = transcriber(audio_filenames)
```

This runs the pipeline on the 4 provided audio files, but it will pass them in batches of 2
to the model (which is on a GPU, where batching is more likely to help) without requiring any further code from you. 
The output should always match what you would have received without batching. It is only meant as a way to help you get more speed out of a pipeline.

Pipelines can also alleviate some of the complexities of batching because, for some pipelines, a single item (like a long audio file) needs to be chunked into multiple parts to be processed by a model. The pipeline performs this [*chunk batching*](./main_classes/pipelines#pipeline-chunk-batching) for you.

### Task specific parameters

All tasks provide task specific parameters which allow for additional flexibility and options to help you get your job done.


key: _node_content
string_value:
{"id_": "eb64f74a-9ae9-4f8f-ac76-e09b04dd2ead", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "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": "044f3f9e-c9b6-4baa-9d16-c07cb19fe076", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "retrieve_doc": true, "source": "transformers"}, "hash": "4b86826f9bba621d3a707f6c4a2a50ed5b41d45f61784aba4ab515f105c22b0c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0e693fe2-25fb-4408-b3d7-0f66586cfc78", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "retrieve_doc": true, "source": "transformers"}, "hash": "af17e8ea50c98179998ddf9aac36666b7543d2a1762018bd1816c30ed9305541", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d0dc5bff-bb33-4c35-8561-6b6c542101a5", "node_type": "1", "metadata": {}, "hash": "906238569b9c1ee944b4c069e3d73b3a9ef5c120b52bc819d609487d93d9aef4", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5398, "end_char_idx": 6970, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
### Batch size

By default, pipelines will not batch inference for reasons explained in detail [here](https://huggingface.co/docs/transformers/main_classes/pipelines#pipeline-batching). The reason is that batching is not necessarily faster, and can actually be quite slower in some cases.

But if it works in your use case, you can use:

```py
transcriber = pipeline(model="openai/whisper-large-v2", device=0, batch_size=2)
audio_filenames = [f"https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/{i}.flac" for i in range(1, 5)]
texts = transcriber(audio_filenames)
```

This runs the pipeline on the 4 provided audio files, but it will pass them in batches of 2
to the model (which is on a GPU, where batching is more likely to help) without requiring any further code from you. 
The output should always match what you would have received without batching. It is only meant as a way to help you get more speed out of a pipeline.

Pipelines can also alleviate some of the complexities of batching because, for some pipelines, a single item (like a long audio file) needs to be chunked into multiple parts to be processed by a model. The pipeline performs this [*chunk batching*](./main_classes/pipelines#pipeline-chunk-batching) for you.

### Task specific parameters

All tasks provide task specific parameters which allow for additional flexibility and options to help you get your job done.
For instance, the [`transformers.AutomaticSpeechRecognitionPipeline.__call__`] method has a `return_timestamps` parameter which sounds promising for subtitling videos:


key: _node_content
string_value:
{"id_": "d0dc5bff-bb33-4c35-8561-6b6c542101a5", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "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": "044f3f9e-c9b6-4baa-9d16-c07cb19fe076", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "retrieve_doc": true, "source": "transformers"}, "hash": "4b86826f9bba621d3a707f6c4a2a50ed5b41d45f61784aba4ab515f105c22b0c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "eb64f74a-9ae9-4f8f-ac76-e09b04dd2ead", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "retrieve_doc": true, "source": "transformers"}, "hash": "a95ca77ac8f36c3f208657c537cd132730efa3e66c485c3448dbdb33ce02e9ba", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2bf4691a-5e14-41c4-a81d-c8a8aef43a85", "node_type": "1", "metadata": {}, "hash": "53974a720c7e1847322692775b013696d472f1ba6408014dd1f948dc0f5fc0d3", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5398, "end_char_idx": 9280, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
### Batch size

By default, pipelines will not batch inference for reasons explained in detail [here](https://huggingface.co/docs/transformers/main_classes/pipelines#pipeline-batching). The reason is that batching is not necessarily faster, and can actually be quite slower in some cases.

But if it works in your use case, you can use:

```py
transcriber = pipeline(model="openai/whisper-large-v2", device=0, batch_size=2)
audio_filenames = [f"https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/{i}.flac" for i in range(1, 5)]
texts = transcriber(audio_filenames)
```

This runs the pipeline on the 4 provided audio files, but it will pass them in batches of 2
to the model (which is on a GPU, where batching is more likely to help) without requiring any further code from you. 
The output should always match what you would have received without batching. It is only meant as a way to help you get more speed out of a pipeline.

Pipelines can also alleviate some of the complexities of batching because, for some pipelines, a single item (like a long audio file) needs to be chunked into multiple parts to be processed by a model. The pipeline performs this [*chunk batching*](./main_classes/pipelines#pipeline-chunk-batching) for you.

### Task specific parameters

All tasks provide task specific parameters which allow for additional flexibility and options to help you get your job done.
For instance, the [`transformers.AutomaticSpeechRecognitionPipeline.__call__`] method has a `return_timestamps` parameter which sounds promising for subtitling videos:


```py
>>> transcriber = pipeline(model="openai/whisper-large-v2", return_timestamps=True)
>>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.', 'chunks': [{'timestamp': (0.0, 11.88), 'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its'}, {'timestamp': (11.88, 12.38), 'text': ' creed.'}]}
```

As you can see, the model inferred the text and also outputted **when** the various sentences were pronounced.

There are many parameters available for each task, so check out each task's API reference to see what you can tinker with!
For instance, the [`~transformers.AutomaticSpeechRecognitionPipeline`] has a `chunk_length_s` parameter which is helpful 
for working on really long audio files (for example, subtitling entire movies or hour-long videos) that a model typically 
cannot handle on its own:

```python
>>> transcriber = pipeline(model="openai/whisper-large-v2", chunk_length_s=30)
>>> transcriber("https://huggingface.co/datasets/reach-vb/random-audios/resolve/main/ted_60.wav")
{'text': " So in college, I was a government major, which means I had to write a lot of papers. Now, when a normal student writes a paper, they might spread the work out a little like this. So, you know. You get started maybe a little slowly, but you get enough done in the first week that with some heavier days later on, everything gets done and things stay civil. And I would want to do that like that. That would be the plan. I would have it all ready to go, but then actually the paper would come along, and then I would kind of do this. And that would happen every single paper. But then came my 90-page senior thesis, a paper you're supposed to spend a year on. I knew for a paper like that, my normal workflow was not an option, it was way too big a project. So I planned things out and I decided I kind of had to go something like this. This is how the year would go. So I'd start off light and I'd bump it up"}
```

If you can't find a parameter that would really help you out, feel free to [request it](https://github.com/huggingface/transformers/issues/new?assignees=&labels=feature&template=feature-request.yml)!


key: _node_content
string_value:
{"id_": "2bf4691a-5e14-41c4-a81d-c8a8aef43a85", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "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": "044f3f9e-c9b6-4baa-9d16-c07cb19fe076", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "retrieve_doc": true, "source": "transformers"}, "hash": "4b86826f9bba621d3a707f6c4a2a50ed5b41d45f61784aba4ab515f105c22b0c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d0dc5bff-bb33-4c35-8561-6b6c542101a5", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "retrieve_doc": true, "source": "transformers"}, "hash": "9c532233d34fb72138486bf546ec5cfa16c3d19283977087c654a102e5a7cdcc", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "dd6b5e35-6083-4318-9b64-821c84e16410", "node_type": "1", "metadata": {}, "hash": "7cea01c2cb59d29bbddfcdf52061bcc88fc4723b90da085025312abfda05619c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 9283, "end_char_idx": 12395, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
## Using pipelines on a dataset

The pipeline can also run inference on a large dataset. The easiest way we recommend doing this is by using an iterator:

```py
def data():
    for i in range(1000):
        yield f"My example {i}"


pipe = pipeline(model="openai-community/gpt2", device=0)
generated_characters = 0
for out in pipe(data()):
    generated_characters += len(out[0]["generated_text"])
```

The iterator `data()` yields each result, and the pipeline automatically
recognizes the input is iterable and will start fetching the data while
it continues to process it on the GPU (this uses [DataLoader](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader) under the hood).
This is important because you don't have to allocate memory for the whole dataset
and you can feed the GPU as fast as possible.

Since batching could speed things up, it may be useful to try tuning the `batch_size` parameter here.

The simplest way to iterate over a dataset is to just load one from 🤗 [Datasets](https://github.com/huggingface/datasets/):

```py
# KeyDataset is a util that will just output the item we're interested in.
from transformers.pipelines.pt_utils import KeyDataset
from datasets import load_dataset

pipe = pipeline(model="hf-internal-testing/tiny-random-wav2vec2", device=0)
dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation[:10]")

for out in pipe(KeyDataset(dataset, "audio")):
    print(out)
```


## Using pipelines for a webserver

<Tip>
Creating an inference engine is a complex topic which deserves it's own
page.
</Tip>

[Link](./pipeline_webserver)

## Vision pipeline

Using a [`pipeline`] for vision tasks is practically identical.

Specify your task and pass your image to the classifier. The image can be a link, a local path or a base64-encoded image. For example, what species of cat is shown below?

![pipeline-cat-chonk](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg)

```py
>>> from transformers import pipeline

>>> vision_classifier = pipeline(model="google/vit-base-patch16-224")
>>> preds = vision_classifier(
...     images="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
... )
>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds]
>>> preds
[{'score': 0.4335, 'label': 'lynx, catamount'}, {'score': 0.0348, 'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor'}, {'score': 0.0324, 'label': 'snow leopard, ounce, Panthera uncia'}, {'score': 0.0239, 'label': 'Egyptian cat'}, {'score': 0.0229, 'label': 'tiger cat'}]
```

## Text pipeline

Using a [`pipeline`] for NLP tasks is practically identical.

```py
>>> from transformers import pipeline

>>> # This model is a `zero-shot-classification` model.
>>> # It will classify text, except you are free to choose any label you might imagine
>>> classifier = pipeline(model="facebook/bart-large-mnli")
>>> classifier(
...     "I have a problem with my iphone that needs to be resolved asap!!


key: _node_content
string_value:
{"id_": "dd6b5e35-6083-4318-9b64-821c84e16410", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "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": "044f3f9e-c9b6-4baa-9d16-c07cb19fe076", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "retrieve_doc": true, "source": "transformers"}, "hash": "4b86826f9bba621d3a707f6c4a2a50ed5b41d45f61784aba4ab515f105c22b0c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2bf4691a-5e14-41c4-a81d-c8a8aef43a85", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "retrieve_doc": true, "source": "transformers"}, "hash": "1094ca842d081b153095e20bca0c04251587ec172d65367182821c9a7afe7ce6", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "0835be8f-ec67-4924-83c1-13cd63ea5e26", "node_type": "1", "metadata": {}, "hash": "8b5f8f5377006f5476f9ae07e945daedd608f1482e0a1386ebb00526aac605a6", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 10876, "end_char_idx": 13423, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
</Tip>

[Link](./pipeline_webserver)

## Vision pipeline

Using a [`pipeline`] for vision tasks is practically identical.

Specify your task and pass your image to the classifier. The image can be a link, a local path or a base64-encoded image. For example, what species of cat is shown below?

![pipeline-cat-chonk](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg)

```py
>>> from transformers import pipeline

>>> vision_classifier = pipeline(model="google/vit-base-patch16-224")
>>> preds = vision_classifier(
...     images="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
... )
>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds]
>>> preds
[{'score': 0.4335, 'label': 'lynx, catamount'}, {'score': 0.0348, 'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor'}, {'score': 0.0324, 'label': 'snow leopard, ounce, Panthera uncia'}, {'score': 0.0239, 'label': 'Egyptian cat'}, {'score': 0.0229, 'label': 'tiger cat'}]
```

## Text pipeline

Using a [`pipeline`] for NLP tasks is practically identical.

```py
>>> from transformers import pipeline

>>> # This model is a `zero-shot-classification` model.
>>> # It will classify text, except you are free to choose any label you might imagine
>>> classifier = pipeline(model="facebook/bart-large-mnli")
>>> classifier(
...     "I have a problem with my iphone that needs to be resolved asap!!",
...     candidate_labels=["urgent", "not urgent", "phone", "tablet", "computer"],
... )
{'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['urgent', 'phone', 'computer', 'not urgent', 'tablet'], 'scores': [0.504, 0.479, 0.013, 0.003, 0.002]}
```

## Multimodal pipeline

The [`pipeline`] supports more than one modality. For example, a visual question answering (VQA) task combines text and image. Feel free to use any image link you like and a question you want to ask about the image. The image can be a URL or a local path to the image.

For example, if you use this [invoice image](https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png):

```py
>>> from transformers import pipeline

>>> vqa = pipeline(model="impira/layoutlm-document-qa")
>>> output = vqa(
...     image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png",
...     question="What is the invoice number?


key: _node_content
string_value:
{"id_": "0835be8f-ec67-4924-83c1-13cd63ea5e26", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "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": "044f3f9e-c9b6-4baa-9d16-c07cb19fe076", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "retrieve_doc": true, "source": "transformers"}, "hash": "4b86826f9bba621d3a707f6c4a2a50ed5b41d45f61784aba4ab515f105c22b0c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "dd6b5e35-6083-4318-9b64-821c84e16410", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "retrieve_doc": true, "source": "transformers"}, "hash": "9f215f396a68ad658f8cb93e6091851fc85fec87c865295d0354018b17d53588", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f16ed45b-f876-4cea-8526-6766a72e60fb", "node_type": "1", "metadata": {}, "hash": "8a5e444a0d80a927a08f127c9e5887e33bb56c2284b9d07af673c14ca0ee40d2", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 12058, "end_char_idx": 14832, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```py
>>> from transformers import pipeline

>>> # This model is a `zero-shot-classification` model.
>>> # It will classify text, except you are free to choose any label you might imagine
>>> classifier = pipeline(model="facebook/bart-large-mnli")
>>> classifier(
...     "I have a problem with my iphone that needs to be resolved asap!!",
...     candidate_labels=["urgent", "not urgent", "phone", "tablet", "computer"],
... )
{'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['urgent', 'phone', 'computer', 'not urgent', 'tablet'], 'scores': [0.504, 0.479, 0.013, 0.003, 0.002]}
```

## Multimodal pipeline

The [`pipeline`] supports more than one modality. For example, a visual question answering (VQA) task combines text and image. Feel free to use any image link you like and a question you want to ask about the image. The image can be a URL or a local path to the image.

For example, if you use this [invoice image](https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png):

```py
>>> from transformers import pipeline

>>> vqa = pipeline(model="impira/layoutlm-document-qa")
>>> output = vqa(
...     image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png",
...     question="What is the invoice number?",
... )
>>> output[0]["score"] = round(output[0]["score"], 3)
>>> output
[{'score': 0.425, 'answer': 'us-001', 'start': 16, 'end': 16}]
```

<Tip>

To run the example above you need to have [`pytesseract`](https://pypi.org/project/pytesseract/) installed in addition to 🤗 Transformers:

```bash
sudo apt install -y tesseract-ocr
pip install pytesseract
```

</Tip>

## Using `pipeline` on large models with 🤗 `accelerate`:

You can easily run `pipeline` on large models using 🤗 `accelerate`! First make sure you have installed `accelerate` with `pip install accelerate`. 

First load your model using `device_map="auto"`! We will use `facebook/opt-1.3b` for our example.

```py
# pip install accelerate
import torch
from transformers import pipeline

pipe = pipeline(model="facebook/opt-1.3b", torch_dtype=torch.bfloat16, device_map="auto")
output = pipe("This is a cool example!", do_sample=True, top_p=0.95)
```

You can also pass 8-bit loaded models if you install `bitsandbytes` and add the argument `load_in_8bit=True`

```py
# pip install accelerate bitsandbytes
import torch
from transformers import pipeline

pipe = pipeline(model="facebook/opt-1.3b", device_map="auto", model_kwargs={"load_in_8bit": True})
output = pipe("This is a cool example!", do_sample=True, top_p=0.95)
```

Note that you can replace the checkpoint with any Hugging Face model that supports large model loading, such as BLOOM.


key: _node_content
string_value:
{"id_": "f16ed45b-f876-4cea-8526-6766a72e60fb", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "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": "044f3f9e-c9b6-4baa-9d16-c07cb19fe076", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "retrieve_doc": true, "source": "transformers"}, "hash": "4b86826f9bba621d3a707f6c4a2a50ed5b41d45f61784aba4ab515f105c22b0c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0835be8f-ec67-4924-83c1-13cd63ea5e26", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4096, "retrieve_doc": true, "source": "transformers"}, "hash": "9d8eb49118bd974d8e4ca52060359d654f39617c65579d6714e3ae882fab89a2", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 13423, "end_char_idx": 16065, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
",
... )
>>> output[0]["score"] = round(output[0]["score"], 3)
>>> output
[{'score': 0.425, 'answer': 'us-001', 'start': 16, 'end': 16}]
```

<Tip>

To run the example above you need to have [`pytesseract`](https://pypi.org/project/pytesseract/) installed in addition to 🤗 Transformers:

```bash
sudo apt install -y tesseract-ocr
pip install pytesseract
```

</Tip>

## Using `pipeline` on large models with 🤗 `accelerate`:

You can easily run `pipeline` on large models using 🤗 `accelerate`! First make sure you have installed `accelerate` with `pip install accelerate`. 

First load your model using `device_map="auto"`! We will use `facebook/opt-1.3b` for our example.

```py
# pip install accelerate
import torch
from transformers import pipeline

pipe = pipeline(model="facebook/opt-1.3b", torch_dtype=torch.bfloat16, device_map="auto")
output = pipe("This is a cool example!", do_sample=True, top_p=0.95)
```

You can also pass 8-bit loaded models if you install `bitsandbytes` and add the argument `load_in_8bit=True`

```py
# pip install accelerate bitsandbytes
import torch
from transformers import pipeline

pipe = pipeline(model="facebook/opt-1.3b", device_map="auto", model_kwargs={"load_in_8bit": True})
output = pipe("This is a cool example!", do_sample=True, top_p=0.95)
```

Note that you can replace the checkpoint with any Hugging Face model that supports large model loading, such as BLOOM.

## Creating web demos from pipelines with `gradio`

Pipelines are automatically supported in [Gradio](https://github.com/gradio-app/gradio/), a library that makes creating beautiful and user-friendly machine learning apps on the web a breeze. First, make sure you have Gradio installed:

```
pip install gradio
```

Then, you can create a web demo around an image classification pipeline (or any other pipeline) in a single line of code by calling Gradio's [`Interface.from_pipeline`](https://www.gradio.app/docs/interface#interface-from-pipeline) function to launch the pipeline. This creates an intuitive drag-and-drop interface in your browser:

```py
from transformers import pipeline
import gradio as gr

pipe = pipeline("image-classification", model="google/vit-base-patch16-224")

gr.Interface.from_pipeline(pipe).launch()
```


![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/panda-classification.png)

By default, the web demo runs on a local server. If you'd like to share it with others, you can generate a temporary public
link by setting `share=True` in `launch()`. You can also host your demo on [Hugging Face Spaces](https://huggingface.co/spaces) for a permanent link.


key: _node_content
string_value:
{"id_": "b824e728-ef07-4e42-8c38-beb9c6502860", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 1846, "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": "ca775fb3-b80e-462a-813a-97998aa1ea41", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 1846, "retrieve_doc": true, "source": "transformers"}, "hash": "cb2207a9ae7a79718ccb6b00018b0acb9220d93bf7ed5ab0e1aa3e37b3035d8c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3afdae87-fcf9-415f-8b53-20f61575c7a2", "node_type": "1", "metadata": {}, "hash": "b94c674cd476a3b4515be786a34ddac8e3d7086a8eb69d870d387871ae81e59d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3391, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Fully Sharded Data Parallel

[Fully Sharded Data Parallel (FSDP)](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/) is a data parallel method that shards a model's parameters, gradients and optimizer states across the number of available GPUs (also called workers or *rank*). Unlike [DistributedDataParallel (DDP)](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html), FSDP reduces memory-usage because a model is replicated on each GPU. This improves GPU memory-efficiency and allows you to train much larger models on fewer GPUs. FSDP is integrated with the Accelerate, a library for easily managing training in distributed environments, which means it is available for use from the [`Trainer`] class.

Before you start, make sure Accelerate is installed and at least PyTorch 2.1.0 or newer.

```bash
pip install accelerate
```

## FSDP configuration

To start, run the [`accelerate config`](https://huggingface.co/docs/accelerate/package_reference/cli#accelerate-config) command to create a configuration file for your training environment. Accelerate uses this configuration file to automatically setup the correct training environment based on your selected training options in `accelerate config`.

```bash
accelerate config
```

When you run `accelerate config`, you'll be prompted with a series of options to configure your training environment. This section covers some of the most important FSDP options. To learn more about the other available FSDP options, take a look at the [fsdp_config](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.fsdp_config) parameters.

### Sharding strategy

FSDP offers a number of sharding strategies to select from:

* `FULL_SHARD` - shards model parameters, gradients and optimizer states across workers; select `1` for this option
* `SHARD_GRAD_OP`- shard gradients and optimizer states across workers; select `2` for this option
* `NO_SHARD` - don't shard anything (this is equivalent to DDP); select `3` for this option
* `HYBRID_SHARD` - shard model parameters, gradients and optimizer states within each worker where each worker also has a full copy; select `4` for this option
* `HYBRID_SHARD_ZERO2` - shard gradients and optimizer states within each worker where each worker also has a full copy; select `5` for this option

This is enabled by the `fsdp_sharding_strategy` flag.

### CPU offload

You could also offload parameters and gradients when they are not in use to the CPU to save even more GPU memory and help you fit large models where even FSDP may not be sufficient. This is enabled by setting `fsdp_offload_params: true` when running `accelerate config`.

### Wrapping policy

FSDP is applied by wrapping each layer in the network. The wrapping is usually applied in a nested way where the full weights are discarded after each forward pass to save memory for use in the next layer. The *auto wrapping* policy is the simplest way to implement this and you don't need to change any code. You should select `fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP` to wrap a Transformer layer and `fsdp_transformer_layer_cls_to_wrap` to specify which layer to wrap (for example `BertLayer`).

Otherwise, you can choose a size-based wrapping policy where FSDP is applied to a layer if it exceeds a certain number of parameters.


key: _node_content
string_value:
{"id_": "3afdae87-fcf9-415f-8b53-20f61575c7a2", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 1846, "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": "ca775fb3-b80e-462a-813a-97998aa1ea41", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 1846, "retrieve_doc": true, "source": "transformers"}, "hash": "cb2207a9ae7a79718ccb6b00018b0acb9220d93bf7ed5ab0e1aa3e37b3035d8c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b824e728-ef07-4e42-8c38-beb9c6502860", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 1846, "retrieve_doc": true, "source": "transformers"}, "hash": "5358aa4846b4e4f0f88e61228f619d9194e5e6079802685015e8613be6da0a1a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "37f5cfb8-d6cc-4622-a662-b1676d0ee352", "node_type": "1", "metadata": {}, "hash": "995373af9bd5278874c2cbff77d98dbef8eac496d636076b8e576e48d19c86f6", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1689, "end_char_idx": 4594, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
### Sharding strategy

FSDP offers a number of sharding strategies to select from:

* `FULL_SHARD` - shards model parameters, gradients and optimizer states across workers; select `1` for this option
* `SHARD_GRAD_OP`- shard gradients and optimizer states across workers; select `2` for this option
* `NO_SHARD` - don't shard anything (this is equivalent to DDP); select `3` for this option
* `HYBRID_SHARD` - shard model parameters, gradients and optimizer states within each worker where each worker also has a full copy; select `4` for this option
* `HYBRID_SHARD_ZERO2` - shard gradients and optimizer states within each worker where each worker also has a full copy; select `5` for this option

This is enabled by the `fsdp_sharding_strategy` flag.

### CPU offload

You could also offload parameters and gradients when they are not in use to the CPU to save even more GPU memory and help you fit large models where even FSDP may not be sufficient. This is enabled by setting `fsdp_offload_params: true` when running `accelerate config`.

### Wrapping policy

FSDP is applied by wrapping each layer in the network. The wrapping is usually applied in a nested way where the full weights are discarded after each forward pass to save memory for use in the next layer. The *auto wrapping* policy is the simplest way to implement this and you don't need to change any code. You should select `fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP` to wrap a Transformer layer and `fsdp_transformer_layer_cls_to_wrap` to specify which layer to wrap (for example `BertLayer`).

Otherwise, you can choose a size-based wrapping policy where FSDP is applied to a layer if it exceeds a certain number of parameters. This is enabled by setting `fsdp_wrap_policy: SIZE_BASED_WRAP` and `min_num_param` to the desired size threshold.

### Checkpointing

Intermediate checkpoints should be saved with `fsdp_state_dict_type: SHARDED_STATE_DICT` because saving the full state dict with CPU offloading on rank 0 takes a lot of time and often results in `NCCL Timeout` errors due to indefinite hanging during broadcasting. You can resume training with the sharded state dicts with the [`~accelerate.Accelerator.load_state`]` method.

```py
# directory containing checkpoints
accelerator.load_state("ckpt")
```

However, when training ends, you want to save the full state dict because sharded state dict is only compatible with FSDP.

```py
if trainer.is_fsdp_enabled:
    trainer.accelerator.state.fsdp_plugin.set_state_dict_type("FULL_STATE_DICT")

trainer.save_model(script_args.output_dir)
```

### TPU

[PyTorch XLA](https://pytorch.org/xla/release/2.1/index.html) supports FSDP training for TPUs and it can be enabled by modifying the FSDP configuration file generated by `accelerate config`. In addition to the sharding strategies and wrapping options specified above, you can add the parameters shown below to the file.


key: _node_content
string_value:
{"id_": "37f5cfb8-d6cc-4622-a662-b1676d0ee352", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 1846, "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": "ca775fb3-b80e-462a-813a-97998aa1ea41", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 1846, "retrieve_doc": true, "source": "transformers"}, "hash": "cb2207a9ae7a79718ccb6b00018b0acb9220d93bf7ed5ab0e1aa3e37b3035d8c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3afdae87-fcf9-415f-8b53-20f61575c7a2", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 1846, "retrieve_doc": true, "source": "transformers"}, "hash": "f9c8bbf0169d5cc7e26d0d9378e0ebbf493768ea27f094ae17b33802b3ab0200", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b5ce64f1-7996-490f-aea7-dbcc70448677", "node_type": "1", "metadata": {}, "hash": "68326477b8403a364c97ff227645ebda0035518ed2e529d191a0c2506fe097c7", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2960, "end_char_idx": 6014, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The *auto wrapping* policy is the simplest way to implement this and you don't need to change any code. You should select `fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP` to wrap a Transformer layer and `fsdp_transformer_layer_cls_to_wrap` to specify which layer to wrap (for example `BertLayer`).

Otherwise, you can choose a size-based wrapping policy where FSDP is applied to a layer if it exceeds a certain number of parameters. This is enabled by setting `fsdp_wrap_policy: SIZE_BASED_WRAP` and `min_num_param` to the desired size threshold.

### Checkpointing

Intermediate checkpoints should be saved with `fsdp_state_dict_type: SHARDED_STATE_DICT` because saving the full state dict with CPU offloading on rank 0 takes a lot of time and often results in `NCCL Timeout` errors due to indefinite hanging during broadcasting. You can resume training with the sharded state dicts with the [`~accelerate.Accelerator.load_state`]` method.

```py
# directory containing checkpoints
accelerator.load_state("ckpt")
```

However, when training ends, you want to save the full state dict because sharded state dict is only compatible with FSDP.

```py
if trainer.is_fsdp_enabled:
    trainer.accelerator.state.fsdp_plugin.set_state_dict_type("FULL_STATE_DICT")

trainer.save_model(script_args.output_dir)
```

### TPU

[PyTorch XLA](https://pytorch.org/xla/release/2.1/index.html) supports FSDP training for TPUs and it can be enabled by modifying the FSDP configuration file generated by `accelerate config`. In addition to the sharding strategies and wrapping options specified above, you can add the parameters shown below to the file.

```yaml
xla: True # must be set to True to enable PyTorch/XLA
xla_fsdp_settings: # XLA-specific FSDP parameters
xla_fsdp_grad_ckpt: True # use gradient checkpointing
```

The [`xla_fsdp_settings`](https://github.com/pytorch/xla/blob/2e6e183e0724818f137c8135b34ef273dea33318/torch_xla/distributed/fsdp/xla_fully_sharded_data_parallel.py#L128) allow you to configure additional XLA-specific parameters for FSDP.

## Launch training

An example FSDP configuration file may look like:

```yaml
compute_environment: LOCAL_MACHINE
debug: false
distributed_type: FSDP
downcast_bf16: 'no'
fsdp_config:
  fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
  fsdp_backward_prefetch_policy: BACKWARD_PRE
  fsdp_cpu_ram_efficient_loading: true
  fsdp_forward_prefetch: false
  fsdp_offload_params: true
  fsdp_sharding_strategy: 1
  fsdp_state_dict_type: SHARDED_STATE_DICT
  fsdp_sync_module_states: true
  fsdp_transformer_layer_cls_to_wrap: BertLayer
  fsdp_use_orig_params: true
machine_rank: 0
main_training_function: main
mixed_precision: bf16
num_machines: 1
num_processes: 2
rdzv_backend: static
same_network: true
tpu_env: []
tpu_use_cluster: false
tpu_use_sudo: false
use_cpu: false
```

To launch training, run the [`accelerate launch`](https://huggingface.co/docs/accelerate/package_reference/cli#accelerate-launch) command and it'll automatically use the configuration file you previously created with `accelerate config`.


key: _node_content
string_value:
{"id_": "b5ce64f1-7996-490f-aea7-dbcc70448677", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 1846, "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": "ca775fb3-b80e-462a-813a-97998aa1ea41", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 1846, "retrieve_doc": true, "source": "transformers"}, "hash": "cb2207a9ae7a79718ccb6b00018b0acb9220d93bf7ed5ab0e1aa3e37b3035d8c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "37f5cfb8-d6cc-4622-a662-b1676d0ee352", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 1846, "retrieve_doc": true, "source": "transformers"}, "hash": "7e9bf19819b85d80811b833a295f4992d78fa07b70d92c374253c1bc0aa23f70", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5007, "end_char_idx": 6981, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
## Launch training

An example FSDP configuration file may look like:

```yaml
compute_environment: LOCAL_MACHINE
debug: false
distributed_type: FSDP
downcast_bf16: 'no'
fsdp_config:
  fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
  fsdp_backward_prefetch_policy: BACKWARD_PRE
  fsdp_cpu_ram_efficient_loading: true
  fsdp_forward_prefetch: false
  fsdp_offload_params: true
  fsdp_sharding_strategy: 1
  fsdp_state_dict_type: SHARDED_STATE_DICT
  fsdp_sync_module_states: true
  fsdp_transformer_layer_cls_to_wrap: BertLayer
  fsdp_use_orig_params: true
machine_rank: 0
main_training_function: main
mixed_precision: bf16
num_machines: 1
num_processes: 2
rdzv_backend: static
same_network: true
tpu_env: []
tpu_use_cluster: false
tpu_use_sudo: false
use_cpu: false
```

To launch training, run the [`accelerate launch`](https://huggingface.co/docs/accelerate/package_reference/cli#accelerate-launch) command and it'll automatically use the configuration file you previously created with `accelerate config`.

```bash
accelerate launch my-trainer-script.py
```

```bash
accelerate launch --fsdp="full shard" --fsdp_config="path/to/fsdp_config/ my-trainer-script.py
```

## Next steps

FSDP can be a powerful tool for training really large models and you have access to more than one GPU or TPU. By sharding the model parameters, optimizer and gradient states, and even offloading them to the CPU when they're inactive, FSDP can reduce the high cost of large-scale training. If you're interested in learning more, the following may be helpful:

* Follow along with the more in-depth Accelerate guide for [FSDP](https://huggingface.co/docs/accelerate/usage_guides/fsdp).
* Read the [Introducing PyTorch Fully Sharded Data Parallel (FSDP) API](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/) blog post.
* Read the [Scaling PyTorch models on Cloud TPUs with FSDP](https://pytorch.org/blog/scaling-pytorch-models-on-cloud-tpus-with-fsdp/) blog post.


key: _node_content
string_value:
{"id_": "664a3e5f-87fa-44be-ba66-741892b60e97", "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": "adaee218-ec5d-417e-b27b-f0e8487774a8", "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"}, "3": {"node_id": "6623b6e0-5acd-415a-95ce-059fb4d5bac7", "node_type": "1", "metadata": {}, "hash": "510d17991dbb4867cfe0febee037598b0c6759fe2ee5bbfef62f54d206f7d9f2", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3129, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# The Transformer model family

Since its introduction in 2017, the [original Transformer](https://arxiv.org/abs/1706.03762) model (see the [Annotated Transformer](http://nlp.seas.harvard.edu/2018/04/03/attention.html) blog post for a gentle technical introduction) has inspired many new and exciting models that extend beyond natural language processing (NLP) tasks. There are models for [predicting the folded structure of proteins](https://huggingface.co/blog/deep-learning-with-proteins), [training a cheetah to run](https://huggingface.co/blog/train-decision-transformers), and [time series forecasting](https://huggingface.co/blog/time-series-transformers). With so many Transformer variants available, it can be easy to miss the bigger picture. What all these models have in common is they're based on the original Transformer architecture. Some models only use the encoder or decoder, while others use both. This provides a useful taxonomy to categorize and examine the high-level differences within models in the Transformer family, and it'll help you understand Transformers you haven't encountered before.

If you aren't familiar with the original Transformer model or need a refresher, check out the [How do Transformers work](https://huggingface.co/course/chapter1/4?fw=pt) chapter from the Hugging Face course.

<div align="center">
    <iframe width="560" height="315" src="https://www.youtube.com/embed/H39Z_720T5s" title="YouTube video player"
    frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope;
    picture-in-picture" allowfullscreen></iframe>
</div>

## Computer vision

<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%2FacQBpeFBVvrDUlzFlkejoz%2FModelscape-timeline%3Fnode-id%3D0%253A1%26t%3Dm0zJ7m2BQ9oe0WtO-1" allowfullscreen></iframe> 

### Convolutional network

For a long time, convolutional networks (CNNs) were the dominant paradigm for computer vision tasks until the [Vision Transformer](https://arxiv.org/abs/2010.11929) demonstrated its scalability and efficiency. Even then, some of a CNN's best qualities, like translation invariance, are so powerful (especially for certain tasks) that some Transformers incorporate convolutions in their architecture. [ConvNeXt](model_doc/convnext) flipped this exchange around and incorporated design choices from Transformers to modernize a CNN. For example, ConvNeXt uses non-overlapping sliding windows to patchify an image and a larger kernel to increase its global receptive field. ConvNeXt also makes several layer design choices to be more memory-efficient and improve performance, so it competes favorably with Transformers!

### Encoder[[cv-encoder]]

The [Vision Transformer (ViT)](model_doc/vit) opened the door to computer vision tasks without convolutions. ViT uses a standard Transformer encoder, but its main breakthrough was how it treated an image. It splits an image into fixed-size patches and uses them to create an embedding, just like how a sentence is split into tokens.


key: _node_content
string_value:
{"id_": "6623b6e0-5acd-415a-95ce-059fb4d5bac7", "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": "adaee218-ec5d-417e-b27b-f0e8487774a8", "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": "664a3e5f-87fa-44be-ba66-741892b60e97", "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": "0e5d6f759cdb5d41cda3b0f2cf9742049a1c02704908bb7610bfb75a42c6d29c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "090ebbf8-0255-43f5-9f76-2445baec0d28", "node_type": "1", "metadata": {}, "hash": "f9123e30781ced80dc6cd7e0a629ed3208b2e25e111da26e24d04c0c51a76d8e", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2163, "end_char_idx": 5725, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Even then, some of a CNN's best qualities, like translation invariance, are so powerful (especially for certain tasks) that some Transformers incorporate convolutions in their architecture. [ConvNeXt](model_doc/convnext) flipped this exchange around and incorporated design choices from Transformers to modernize a CNN. For example, ConvNeXt uses non-overlapping sliding windows to patchify an image and a larger kernel to increase its global receptive field. ConvNeXt also makes several layer design choices to be more memory-efficient and improve performance, so it competes favorably with Transformers!

### Encoder[[cv-encoder]]

The [Vision Transformer (ViT)](model_doc/vit) opened the door to computer vision tasks without convolutions. ViT uses a standard Transformer encoder, but its main breakthrough was how it treated an image. It splits an image into fixed-size patches and uses them to create an embedding, just like how a sentence is split into tokens. ViT capitalized on the Transformers' efficient architecture to demonstrate competitive results with the CNNs at the time while requiring fewer resources to train. ViT was soon followed by other vision models that could also handle dense vision tasks like segmentation as well as detection.

One of these models is the [Swin](model_doc/swin) Transformer. It builds hierarchical feature maps (like a CNN 👀 and unlike ViT) from smaller-sized patches and merges them with neighboring patches in deeper layers. Attention is only computed within a local window, and the window is shifted between attention layers to create connections to help the model learn better. Since the Swin Transformer can produce hierarchical feature maps, it is a good candidate for dense prediction tasks like segmentation and detection. The [SegFormer](model_doc/segformer) also uses a Transformer encoder to build hierarchical feature maps, but it adds a simple multilayer perceptron (MLP) decoder on top to combine all the feature maps and make a prediction.

Other vision models, like BeIT and ViTMAE, drew inspiration from BERT's pretraining objective. [BeIT](model_doc/beit) is pretrained by *masked image modeling (MIM)*; the image patches are randomly masked, and the image is also tokenized into visual tokens. BeIT is trained to predict the visual tokens corresponding to the masked patches. [ViTMAE](model_doc/vitmae) has a similar pretraining objective, except it must predict the pixels instead of visual tokens. What's unusual is 75% of the image patches are masked! The decoder reconstructs the pixels from the masked tokens and encoded patches. After pretraining, the decoder is thrown away, and the encoder is ready to be used in downstream tasks.

### Decoder[[cv-decoder]]

Decoder-only vision models are rare because most vision models rely on an encoder to learn an image representation. But for use cases like image generation, the decoder is a natural fit, as we've seen from text generation models like GPT-2. [ImageGPT](model_doc/imagegpt) uses the same architecture as GPT-2, but instead of predicting the next token in a sequence, it predicts the next pixel in an image. In addition to image generation, ImageGPT could also be finetuned for image classification.

### Encoder-decoder[[cv-encoder-decoder]]

Vision models commonly use an encoder (also known as a backbone) to extract important image features before passing them to a Transformer decoder. [DETR](model_doc/detr) has a pretrained backbone, but it also uses the complete Transformer encoder-decoder architecture for object detection.


key: _node_content
string_value:
{"id_": "090ebbf8-0255-43f5-9f76-2445baec0d28", "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": "adaee218-ec5d-417e-b27b-f0e8487774a8", "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": "6623b6e0-5acd-415a-95ce-059fb4d5bac7", "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": "b8dee52ed3e3ec41bf06b70405e356a2078f575120edf086cced6e79aa508a02", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4d1704fd-c005-49e8-b38f-98a3b30a93f0", "node_type": "1", "metadata": {}, "hash": "8512f7945e4e45e353158f4d39346f978e6ee029df678571246aac19e2f64bf4", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 4165, "end_char_idx": 7305, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Other vision models, like BeIT and ViTMAE, drew inspiration from BERT's pretraining objective. [BeIT](model_doc/beit) is pretrained by *masked image modeling (MIM)*; the image patches are randomly masked, and the image is also tokenized into visual tokens. BeIT is trained to predict the visual tokens corresponding to the masked patches. [ViTMAE](model_doc/vitmae) has a similar pretraining objective, except it must predict the pixels instead of visual tokens. What's unusual is 75% of the image patches are masked! The decoder reconstructs the pixels from the masked tokens and encoded patches. After pretraining, the decoder is thrown away, and the encoder is ready to be used in downstream tasks.

### Decoder[[cv-decoder]]

Decoder-only vision models are rare because most vision models rely on an encoder to learn an image representation. But for use cases like image generation, the decoder is a natural fit, as we've seen from text generation models like GPT-2. [ImageGPT](model_doc/imagegpt) uses the same architecture as GPT-2, but instead of predicting the next token in a sequence, it predicts the next pixel in an image. In addition to image generation, ImageGPT could also be finetuned for image classification.

### Encoder-decoder[[cv-encoder-decoder]]

Vision models commonly use an encoder (also known as a backbone) to extract important image features before passing them to a Transformer decoder. [DETR](model_doc/detr) has a pretrained backbone, but it also uses the complete Transformer encoder-decoder architecture for object detection. The encoder learns image representations and combines them with object queries (each object query is a learned embedding that focuses on a region or object in an image) in the decoder. DETR predicts the bounding box coordinates and class label for each object query.

## Natural language processing

<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%2FUhbQAZDlpYW5XEpdFy6GoG%2Fnlp-model-timeline%3Fnode-id%3D0%253A1%26t%3D4mZMr4r1vDEYGJ50-1" allowfullscreen></iframe>

### Encoder[[nlp-encoder]]

[BERT](model_doc/bert) is an encoder-only Transformer that randomly masks certain tokens in the input to avoid seeing other tokens, which would allow it to "cheat". The pretraining objective is to predict the masked token based on the context. This allows BERT to fully use the left and right contexts to help it learn a deeper and richer representation of the inputs. However, there was still room for improvement in BERT's pretraining strategy. [RoBERTa](model_doc/roberta) improved upon this by introducing a new pretraining recipe that includes training for longer and on larger batches, randomly masking tokens at each epoch instead of just once during preprocessing, and removing the next-sentence prediction objective. 

The dominant strategy to improve performance is to increase the model size. But training large models is computationally expensive. One way to reduce computational costs is using a smaller model like [DistilBERT](model_doc/distilbert).


key: _node_content
string_value:
{"id_": "4d1704fd-c005-49e8-b38f-98a3b30a93f0", "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": "adaee218-ec5d-417e-b27b-f0e8487774a8", "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": "090ebbf8-0255-43f5-9f76-2445baec0d28", "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": "ab735995d323c697e5672fb632249e1c5223f364933c32628fd2f291ccc27802", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b87bf301-abd5-48f5-921a-bc0653a39629", "node_type": "1", "metadata": {}, "hash": "0cf213ec57003fb8c06fbbaffd4409237761532a45b660940005affc1a7a6a23", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5726, "end_char_idx": 9017, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The encoder learns image representations and combines them with object queries (each object query is a learned embedding that focuses on a region or object in an image) in the decoder. DETR predicts the bounding box coordinates and class label for each object query.

## Natural language processing

<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%2FUhbQAZDlpYW5XEpdFy6GoG%2Fnlp-model-timeline%3Fnode-id%3D0%253A1%26t%3D4mZMr4r1vDEYGJ50-1" allowfullscreen></iframe>

### Encoder[[nlp-encoder]]

[BERT](model_doc/bert) is an encoder-only Transformer that randomly masks certain tokens in the input to avoid seeing other tokens, which would allow it to "cheat". The pretraining objective is to predict the masked token based on the context. This allows BERT to fully use the left and right contexts to help it learn a deeper and richer representation of the inputs. However, there was still room for improvement in BERT's pretraining strategy. [RoBERTa](model_doc/roberta) improved upon this by introducing a new pretraining recipe that includes training for longer and on larger batches, randomly masking tokens at each epoch instead of just once during preprocessing, and removing the next-sentence prediction objective. 

The dominant strategy to improve performance is to increase the model size. But training large models is computationally expensive. One way to reduce computational costs is using a smaller model like [DistilBERT](model_doc/distilbert). DistilBERT uses [knowledge distillation](https://arxiv.org/abs/1503.02531) - a compression technique - to create a smaller version of BERT while keeping nearly all of its language understanding capabilities. 

However, most Transformer models continued to trend towards more parameters, leading to new models focused on improving training efficiency. [ALBERT](model_doc/albert) reduces memory consumption by lowering the number of parameters in two ways: separating the larger vocabulary embedding into two smaller matrices and allowing layers to share parameters. [DeBERTa](model_doc/deberta) added a disentangled attention mechanism where the word and its position are separately encoded in two vectors. The attention is computed from these separate vectors instead of a single vector containing the word and position embeddings. [Longformer](model_doc/longformer) also focused on making attention more efficient, especially for processing documents with longer sequence lengths. It uses a combination of local windowed attention (attention only calculated from fixed window size around each token) and global attention (only for specific task tokens like `[CLS]` for classification) to create a sparse attention matrix instead of a full attention matrix.

### Decoder[[nlp-decoder]]

[GPT-2](model_doc/gpt2) is a decoder-only Transformer that predicts the next word in the sequence. It masks tokens to the right so the model can't "cheat" by looking ahead. By pretraining on a massive body of text, GPT-2 became really good at generating text, even if the text is only sometimes accurate or true. But GPT-2 lacked the bidirectional context from BERT's pretraining, which made it unsuitable for certain tasks.


key: _node_content
string_value:
{"id_": "b87bf301-abd5-48f5-921a-bc0653a39629", "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": "adaee218-ec5d-417e-b27b-f0e8487774a8", "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": "4d1704fd-c005-49e8-b38f-98a3b30a93f0", "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": "b3b068642bf42be0a7f344b4fd8a1de96c7e1d960a1237a30eab9916c1226ea7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "19c805f6-2639-4868-bdd7-8c88a6592531", "node_type": "1", "metadata": {}, "hash": "ddc653538932ca46bf8cc1f16c62fec654434af80223eb7dda3b9e2db715350b", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 7146, "end_char_idx": 10667, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
But training large models is computationally expensive. One way to reduce computational costs is using a smaller model like [DistilBERT](model_doc/distilbert). DistilBERT uses [knowledge distillation](https://arxiv.org/abs/1503.02531) - a compression technique - to create a smaller version of BERT while keeping nearly all of its language understanding capabilities. 

However, most Transformer models continued to trend towards more parameters, leading to new models focused on improving training efficiency. [ALBERT](model_doc/albert) reduces memory consumption by lowering the number of parameters in two ways: separating the larger vocabulary embedding into two smaller matrices and allowing layers to share parameters. [DeBERTa](model_doc/deberta) added a disentangled attention mechanism where the word and its position are separately encoded in two vectors. The attention is computed from these separate vectors instead of a single vector containing the word and position embeddings. [Longformer](model_doc/longformer) also focused on making attention more efficient, especially for processing documents with longer sequence lengths. It uses a combination of local windowed attention (attention only calculated from fixed window size around each token) and global attention (only for specific task tokens like `[CLS]` for classification) to create a sparse attention matrix instead of a full attention matrix.

### Decoder[[nlp-decoder]]

[GPT-2](model_doc/gpt2) is a decoder-only Transformer that predicts the next word in the sequence. It masks tokens to the right so the model can't "cheat" by looking ahead. By pretraining on a massive body of text, GPT-2 became really good at generating text, even if the text is only sometimes accurate or true. But GPT-2 lacked the bidirectional context from BERT's pretraining, which made it unsuitable for certain tasks. [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.

After 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.

### Encoder-decoder[[nlp-encoder-decoder]]

[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.


key: _node_content
string_value:
{"id_": "19c805f6-2639-4868-bdd7-8c88a6592531", "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": "adaee218-ec5d-417e-b27b-f0e8487774a8", "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": "b87bf301-abd5-48f5-921a-bc0653a39629", "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": "48da9e1d-8e4f-402d-bb30-993d2b8079eb", "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"}


key: chroma:document
string_value:
[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.

After 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.

### Encoder-decoder[[nlp-encoder-decoder]]

[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).

## Audio

<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>

### Encoder[[audio-encoder]]

[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.

### Encoder-decoder[[audio-encoder-decoder]]

[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.


key: _node_content
string_value:
{"id_": "48da9e1d-8e4f-402d-bb30-993d2b8079eb", "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": "adaee218-ec5d-417e-b27b-f0e8487774a8", "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": "19c805f6-2639-4868-bdd7-8c88a6592531", "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": "3b3af79b-f8c6-4584-a4d1-e2cc9f161992", "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"}


key: chroma:document
string_value:
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).

## Audio

<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>

### Encoder[[audio-encoder]]

[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.

### Encoder-decoder[[audio-encoder-decoder]]

[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 ✨ labeled ✨ 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.

## Multimodal

<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>

### Encoder[[mm-encoder]]

[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.


key: _node_content
string_value:
{"id_": "3b3af79b-f8c6-4584-a4d1-e2cc9f161992", "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": "adaee218-ec5d-417e-b27b-f0e8487774a8", "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": "48da9e1d-8e4f-402d-bb30-993d2b8079eb", "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": "964d882a-5ee4-4eef-9331-46c606ea5e32", "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"}


key: chroma:document
string_value:
[Whisper](model_doc/whisper) is also an ASR model, but unlike many other speech models, it is pretrained on a massive amount of ✨ labeled ✨ 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.

## Multimodal

<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>

### Encoder[[mm-encoder]]

[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.

[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.

### Encoder-decoder[[mm-encoder-decoder]]

Optical 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.


key: _node_content
string_value:
{"id_": "964d882a-5ee4-4eef-9331-46c606ea5e32", "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": "adaee218-ec5d-417e-b27b-f0e8487774a8", "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": "3b3af79b-f8c6-4584-a4d1-e2cc9f161992", "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"}


key: chroma:document
string_value:
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.

[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.

### Encoder-decoder[[mm-encoder-decoder]]

Optical 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).

## Reinforcement learning

<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>

### Decoder[[rl-decoder]]

The 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.


key: _node_content
string_value:
{"id_": "da8da98d-a7e1-4ecd-94da-e96505859b46", "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": "18872355-da1c-42af-812b-48bdec943ac7", "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": "414be59a-30b0-4cf9-878f-6f43ad364112", "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"}


key: chroma:document
string_value:
<!---
Copyright 2022 The HuggingFace Team. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.

-->


# Custom hardware for training

The hardware you use to run model training and inference can have a big effect on performance. For a deep dive into GPUs make sure to check out Tim Dettmer's excellent [blog post](https://timdettmers.com/2020/09/07/which-gpu-for-deep-learning/).

Let's have a look at some practical advice for GPU setups.

## GPU
When you train bigger models you have essentially three options:

- bigger GPUs
- more GPUs
- more CPU and NVMe (offloaded to by [DeepSpeed-Infinity](main_classes/deepspeed#nvme-support))

Let's start at the case where you have a single GPU.

### Power and Cooling

If you bought an expensive high end GPU make sure you give it the correct power and sufficient cooling.

**Power**:

Some 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.

Each 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.

Some other cards may use a PCI-E 12-Pin connectors, and these can deliver up to 500-600W of power.

Low end cards may use 6-Pin connectors, which supply up to 75W of power.

Additionally 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.

And of course the PSU needs to have enough unused Watts to power the card.

**Cooling**:

When 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.

It'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.

Next let's have a look at one of the most important aspects when having multiple GPUs: connectivity.

### Multi-GPU Connectivity

If you use multiple GPUs the way cards are inter-connected can have a huge impact on the total training time.


key: _node_content
string_value:
{"id_": "414be59a-30b0-4cf9-878f-6f43ad364112", "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": "18872355-da1c-42af-812b-48bdec943ac7", "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": "da8da98d-a7e1-4ecd-94da-e96505859b46", "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": "d353e570-3690-47a1-875c-6f4fd23f566e", "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"}


key: chroma:document
string_value:
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.

Each 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.

Some other cards may use a PCI-E 12-Pin connectors, and these can deliver up to 500-600W of power.

Low end cards may use 6-Pin connectors, which supply up to 75W of power.

Additionally 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.

And of course the PSU needs to have enough unused Watts to power the card.

**Cooling**:

When 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.

It'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.

Next let's have a look at one of the most important aspects when having multiple GPUs: connectivity.

### Multi-GPU Connectivity

If 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:

```bash
nvidia-smi topo -m
```

and 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:

```
        GPU0    GPU1    CPU Affinity    NUMA Affinity
GPU0     X      NV2     0-23            N/A
GPU1    NV2      X      0-23            N/A
```

on a different machine w/o NVLink we may see:
```
        GPU0    GPU1    CPU Affinity    NUMA Affinity
GPU0     X      PHB     0-11            N/A
GPU1    PHB      X      0-11            N/A
```

The report includes this legend:

```
  X    = Self
  SYS  = Connection traversing PCIe as well as the SMP interconnect between NUMA nodes (e.g., QPI/UPI)
  NODE = Connection traversing PCIe as well as the interconnect between PCIe Host Bridges within a NUMA node
  PHB  = Connection traversing PCIe as well as a PCIe Host Bridge (typically the CPU)
  PXB  = Connection traversing multiple PCIe bridges (without traversing the PCIe Host Bridge)
  PIX  = Connection traversing at most a single PCIe bridge
  NV#  = Connection traversing a bonded set of # NVLinks
```

So 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.

Check 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).


key: _node_content
string_value:
{"id_": "d353e570-3690-47a1-875c-6f4fd23f566e", "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": "18872355-da1c-42af-812b-48bdec943ac7", "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": "414be59a-30b0-4cf9-878f-6f43ad364112", "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": "5839c2e3-1c02-4494-bd7d-6005ec8d8590", "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"}


key: chroma:document
string_value:
If the GPUs are on the same physical node, you can run:

```bash
nvidia-smi topo -m
```

and 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:

```
        GPU0    GPU1    CPU Affinity    NUMA Affinity
GPU0     X      NV2     0-23            N/A
GPU1    NV2      X      0-23            N/A
```

on a different machine w/o NVLink we may see:
```
        GPU0    GPU1    CPU Affinity    NUMA Affinity
GPU0     X      PHB     0-11            N/A
GPU1    PHB      X      0-11            N/A
```

The report includes this legend:

```
  X    = Self
  SYS  = Connection traversing PCIe as well as the SMP interconnect between NUMA nodes (e.g., QPI/UPI)
  NODE = Connection traversing PCIe as well as the interconnect between PCIe Host Bridges within a NUMA node
  PHB  = Connection traversing PCIe as well as a PCIe Host Bridge (typically the CPU)
  PXB  = Connection traversing multiple PCIe bridges (without traversing the PCIe Host Bridge)
  PIX  = Connection traversing at most a single PCIe bridge
  NV#  = Connection traversing a bonded set of # NVLinks
```

So 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.

Check 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).

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.

#### NVlink

[NVLink](https://en.wikipedia.org/wiki/NVLink) is a wire-based serial multi-lane near-range communications link developed by Nvidia.

Each 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):

> Third-Generation NVLink®
> GA102 GPUs utilize NVIDIA’s third-generation NVLink interface, which includes four x4 links,
> with each link providing 14.0625 GB/sec bandwidth in each direction between two GPUs. Four
> links provide 56.25 GB/sec bandwidth in each direction, and 112.5 GB/sec total bandwidth
> between two GPUs. Two RTX 3090 GPUs can be connected together for SLI using NVLink.
> (Note that 3-Way and 4-Way SLI configurations are not supported.)

So 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.

Let's compare the execution of an openai-community/gpt2 language model training over a small sample of wikitext.

The results are:


key: _node_content
string_value:
{"id_": "5839c2e3-1c02-4494-bd7d-6005ec8d8590", "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": "18872355-da1c-42af-812b-48bdec943ac7", "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": "d353e570-3690-47a1-875c-6f4fd23f566e", "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": "e8068e71-84a1-435e-a3e7-d83dad44b383", "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"}


key: chroma:document
string_value:
Some of these will make the communication between cards faster (e.g. NVLink), others slower (e.g. PHB).

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.

#### NVlink

[NVLink](https://en.wikipedia.org/wiki/NVLink) is a wire-based serial multi-lane near-range communications link developed by Nvidia.

Each 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):

> Third-Generation NVLink®
> GA102 GPUs utilize NVIDIA’s third-generation NVLink interface, which includes four x4 links,
> with each link providing 14.0625 GB/sec bandwidth in each direction between two GPUs. Four
> links provide 56.25 GB/sec bandwidth in each direction, and 112.5 GB/sec total bandwidth
> between two GPUs. Two RTX 3090 GPUs can be connected together for SLI using NVLink.
> (Note that 3-Way and 4-Way SLI configurations are not supported.)

So 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.

Let's compare the execution of an openai-community/gpt2 language model training over a small sample of wikitext.

The results are:


| NVlink | Time |
| -----  | ---: |
| Y      | 101s |
| N      | 131s |


key: _node_content
string_value:
{"id_": "e8068e71-84a1-435e-a3e7-d83dad44b383", "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": "18872355-da1c-42af-812b-48bdec943ac7", "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": "5839c2e3-1c02-4494-bd7d-6005ec8d8590", "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"}


key: chroma:document
string_value:
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.

#### NVlink

[NVLink](https://en.wikipedia.org/wiki/NVLink) is a wire-based serial multi-lane near-range communications link developed by Nvidia.

Each 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):

> Third-Generation NVLink®
> GA102 GPUs utilize NVIDIA’s third-generation NVLink interface, which includes four x4 links,
> with each link providing 14.0625 GB/sec bandwidth in each direction between two GPUs. Four
> links provide 56.25 GB/sec bandwidth in each direction, and 112.5 GB/sec total bandwidth
> between two GPUs. Two RTX 3090 GPUs can be connected together for SLI using NVLink.
> (Note that 3-Way and 4-Way SLI configurations are not supported.)

So 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.

Let's compare the execution of an openai-community/gpt2 language model training over a small sample of wikitext.

The results are:


| NVlink | Time |
| -----  | ---: |
| Y      | 101s |
| N      | 131s |


You 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.

Here is the full benchmark code and outputs:

```bash
# DDP w/ NVLink

rm -r /tmp/test-clm; CUDA_VISIBLE_DEVICES=0,1 torchrun \
--nproc_per_node 2 examples/pytorch/language-modeling/run_clm.py --model_name_or_path openai-community/gpt2 \
--dataset_name wikitext --dataset_config_name wikitext-2-raw-v1 --do_train \
--output_dir /tmp/test-clm --per_device_train_batch_size 4 --max_steps 200

{'train_runtime': 101.9003, 'train_samples_per_second': 1.963, 'epoch': 0.69}

# DDP w/o NVLink

rm -r /tmp/test-clm; CUDA_VISIBLE_DEVICES=0,1 NCCL_P2P_DISABLE=1 torchrun \
--nproc_per_node 2 examples/pytorch/language-modeling/run_clm.py --model_name_or_path openai-community/gpt2 \
--dataset_name wikitext --dataset_config_name wikitext-2-raw-v1 --do_train
--output_dir /tmp/test-clm --per_device_train_batch_size 4 --max_steps 200

{'train_runtime': 131.4367, 'train_samples_per_second': 1.522, 'epoch': 0.69}
```

Hardware: 2x TITAN RTX 24GB each + NVlink with 2 NVLinks (`NV2` in `nvidia-smi topo -m`)
Software: `pytorch-1.8-to-be` + `cuda-11.0` / `transformers==4.3.0.dev0`


key: _node_content
string_value:
{"id_": "19666354-e2e2-44c0-9445-b9c59fff2374", "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": "7d2583fe-4b72-4f22-bcc7-944f209f7047", "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": "ae7d81ec-71a6-4360-861f-8d4d2291eaba", "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"}


key: chroma:document
string_value:
# GGUF and interaction with Transformers

The GGUF file format is used to store models for inference with [GGML](https://github.com/ggerganov/ggml) and other 
libraries that depend on it, like the very popular [llama.cpp](https://github.com/ggerganov/llama.cpp) or 
[whisper.cpp](https://github.com/ggerganov/whisper.cpp).

It is a file format [supported by the Hugging Face Hub](https://huggingface.co/docs/hub/en/gguf) with features 
allowing for quick inspection of tensors and metadata within the file.

This file format is designed as a "single-file-format" where a single file usually contains both the configuration
attributes, the tokenizer vocabulary and other attributes, as well as all tensors to be loaded in the model. These
files come in different formats according to the quantization type of the file. We briefly go over some of them
[here](https://huggingface.co/docs/hub/en/gguf#quantization-types).

## Support within Transformers

We have added the ability to load `gguf` files within `transformers` in order to offer further training/fine-tuning
capabilities to gguf models, before converting back those models to `gguf` to use within the `ggml` ecosystem. When
loading a model, we first dequantize it to fp32, before loading the weights to be used in PyTorch.

> [!NOTE]
> The support is still very exploratory and we welcome contributions in order to solidify it across quantization types
> and model architectures.

For now, here are the supported model architectures and quantization types:

### Supported quantization types

The initial supported quantization types are decided according to the popular quantized files that have been shared
on the Hub.

- F32
- Q2_K
- Q3_K
- Q4_0
- Q4_K
- Q5_K
- Q6_K
- Q8_0

We take example from the excellent [99991/pygguf](https://github.com/99991/pygguf) Python parser to dequantize the 
weights.

### Supported model architectures

For now the supported model architectures are the architectures that have been very popular on the Hub, namely:

- LLaMa
- Mistral
- Qwen2

## Example usage

In order to load `gguf` files in `transformers`, you should specify the `gguf_file` argument to the `from_pretrained`
methods of both tokenizers and models. Here is how one would load a tokenizer and a model, which can be loaded
from the exact same file:

```py
from transformers import AutoTokenizer, AutoModelForCausalLM

model_id = "TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF"
filename = "tinyllama-1.1b-chat-v1.0.Q6_K.gguf"

tokenizer = AutoTokenizer.from_pretrained(model_id, gguf_file=filename)
model = AutoModelForCausalLM.from_pretrained(model_id, gguf_file=filename)
```

Now you have access to the full, unquantized version of the model in the PyTorch ecosystem, where you can combine it
with a plethora of other tools.

In order to convert back to a `gguf` file, we recommend using the 
[`convert-hf-to-gguf.py` file](https://github.com/ggerganov/llama.cpp/blob/master/convert-hf-to-gguf.py) from llama.cpp.


key: _node_content
string_value:
{"id_": "ae7d81ec-71a6-4360-861f-8d4d2291eaba", "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": "7d2583fe-4b72-4f22-bcc7-944f209f7047", "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": "19666354-e2e2-44c0-9445-b9c59fff2374", "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"}


key: chroma:document
string_value:
- F32
- Q2_K
- Q3_K
- Q4_0
- Q4_K
- Q5_K
- Q6_K
- Q8_0

We take example from the excellent [99991/pygguf](https://github.com/99991/pygguf) Python parser to dequantize the 
weights.

### Supported model architectures

For now the supported model architectures are the architectures that have been very popular on the Hub, namely:

- LLaMa
- Mistral
- Qwen2

## Example usage

In order to load `gguf` files in `transformers`, you should specify the `gguf_file` argument to the `from_pretrained`
methods of both tokenizers and models. Here is how one would load a tokenizer and a model, which can be loaded
from the exact same file:

```py
from transformers import AutoTokenizer, AutoModelForCausalLM

model_id = "TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF"
filename = "tinyllama-1.1b-chat-v1.0.Q6_K.gguf"

tokenizer = AutoTokenizer.from_pretrained(model_id, gguf_file=filename)
model = AutoModelForCausalLM.from_pretrained(model_id, gguf_file=filename)
```

Now you have access to the full, unquantized version of the model in the PyTorch ecosystem, where you can combine it
with a plethora of other tools.

In order to convert back to a `gguf` file, we recommend using the 
[`convert-hf-to-gguf.py` file](https://github.com/ggerganov/llama.cpp/blob/master/convert-hf-to-gguf.py) from llama.cpp.

Here's how you would complete the script above to save the model and export it back to `gguf`:

```py
tokenizer.save_pretrained('directory')
model.save_pretrained('directory')

!python ${path_to_llama_cpp}/convert-hf-to-gguf.py ${directory}
```


key: _node_content
string_value:
{"id_": "88d6d8fe-fd85-4d0b-9c58-09f14dfdc5f4", "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": "472ae749-7e1a-4e59-a876-44eebdec08e0", "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"}


key: chroma:document
string_value:
# Attention mechanisms

Most transformer models use full attention in the sense that the attention matrix is square. It can be a big
computational bottleneck when you have long texts. Longformer and reformer are models that try to be more efficient and
use a sparse version of the attention matrix to speed up training.

## LSH attention

[Reformer](model_doc/reformer) uses LSH attention. In the softmax(QK^t), only the biggest elements (in the softmax
dimension) of the matrix QK^t are going to give useful contributions. So for each query q in Q, we can consider only
the 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
modified to mask the current token (except at the first position), because it will give a query and a key equal (so
very similar to each other). Since the hash can be a bit random, several hash functions are used in practice
(determined by a n_rounds parameter) and then are averaged together.

## Local attention

[Longformer](model_doc/longformer) uses local attention: often, the local context (e.g., what are the two tokens to the
left and right?) is enough to take action for a given token. Also, by stacking attention layers that have a small
window, the last layer will have a receptive field of more than just the tokens in the window, allowing them to build a
representation of the whole sentence.

Some preselected input tokens are also given global attention: for those few tokens, the attention matrix can access
all tokens and this process is symmetric: all other tokens have access to those specific tokens (on top of the ones in
their local window). This is shown in Figure 2d of the paper, see below for a sample attention mask:

<div class="flex justify-center">
    <img scale="50 %" align="center" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/local_attention_mask.png"/>
</div>

Using those attention matrices with less parameters then allows the model to have inputs having a bigger sequence
length.

## Other tricks

### Axial positional encodings

[Reformer](model_doc/reformer) uses axial positional encodings: in traditional transformer models, the positional encoding
E is a matrix of size \\(l\\) by \\(d\\), \\(l\\) being the sequence length and \\(d\\) the dimension of the
hidden state. If you have very long texts, this matrix can be huge and take way too much space on the GPU. To alleviate
that, axial positional encodings consist of factorizing that big matrix E in two smaller matrices E1 and E2, with
dimensions \\(l_{1} \times d_{1}\\) and \\(l_{2} \times d_{2}\\), such that \\(l_{1} \times l_{2} = l\\) and
\\(d_{1} + d_{2} = d\\) (with the product for the lengths, this ends up being way smaller). The embedding for time
step \\(j\\) in E is obtained by concatenating the embeddings for timestep \\(j \% l1\\) in E1 and \\(j // l1\\)
in E2.


key: _node_content
string_value:
{"id_": "f6ac45a7-2e28-4928-9d37-bb92a67b4167", "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": "527aeef3-6ae7-4d9c-9b89-ffaf57af679e", "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"}


key: chroma:document
string_value:
# Use tokenizers from 🤗 Tokenizers

The [`PreTrainedTokenizerFast`] depends on the [🤗 Tokenizers](https://huggingface.co/docs/tokenizers) library. The tokenizers obtained from the 🤗 Tokenizers library can be
loaded very simply into 🤗 Transformers.

Before getting in the specifics, let's first start by creating a dummy tokenizer in a few lines:

```python
>>> from tokenizers import Tokenizer
>>> from tokenizers.models import BPE
>>> from tokenizers.trainers import BpeTrainer
>>> from tokenizers.pre_tokenizers import Whitespace

>>> tokenizer = Tokenizer(BPE(unk_token="[UNK]"))
>>> trainer = BpeTrainer(special_tokens=["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"])

>>> tokenizer.pre_tokenizer = Whitespace()
>>> files = [...]
>>> tokenizer.train(files, trainer)
```

We now have a tokenizer trained on the files we defined. We can either continue using it in that runtime, or save it to
a JSON file for future re-use.

## Loading directly from the tokenizer object

Let's see how to leverage this tokenizer object in the 🤗 Transformers library. The
[`PreTrainedTokenizerFast`] class allows for easy instantiation, by accepting the instantiated
*tokenizer* object as an argument:

```python
>>> from transformers import PreTrainedTokenizerFast

>>> fast_tokenizer = PreTrainedTokenizerFast(tokenizer_object=tokenizer)
```

This object can now be used with all the methods shared by the 🤗 Transformers tokenizers! Head to [the tokenizer
page](main_classes/tokenizer) for more information.

## Loading from a JSON file

In order to load a tokenizer from a JSON file, let's first start by saving our tokenizer:

```python
>>> tokenizer.save("tokenizer.json")
```

The path to which we saved this file can be passed to the [`PreTrainedTokenizerFast`] initialization
method using the `tokenizer_file` parameter:

```python
>>> from transformers import PreTrainedTokenizerFast

>>> fast_tokenizer = PreTrainedTokenizerFast(tokenizer_file="tokenizer.json")
```

This object can now be used with all the methods shared by the 🤗 Transformers tokenizers! Head to [the tokenizer
page](main_classes/tokenizer) for more information.


key: _node_content
string_value:
{"id_": "e8d18abd-d894-44f1-85ce-2e568317f8e5", "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": "bc33d55b-687e-4170-91ae-852d6a8d3e76", "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": "8e001d34-0789-45d0-9894-07caa9054dcc", "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"}


key: chroma:document
string_value:
# Instantiate a big model

A barrier to accessing very large pretrained models is the amount of memory required. When loading a pretrained PyTorch model, you usually:

1. Create a model with random weights.
2. Load your pretrained weights.
3. Put those pretrained weights in the model.

The 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.

> [!TIP]
> 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.

This guide will show you how Transformers can help you load large pretrained models despite their memory requirements.

## Sharded checkpoints

From 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.

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.

For example, let's shard [BioMistral/BioMistral-7B](https://hf.co/BioMistral/BioMistral-7B).

```py
>>> with tempfile.TemporaryDirectory() as tmp_dir:
...     model.save_pretrained(tmp_dir, max_shard_size="5GB")
...     print(sorted(os.listdir(tmp_dir)))
['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']
```

The sharded checkpoint is reloaded with the [`~PreTrainedModel.from_pretrained`] method.

```py
>>> with tempfile.TemporaryDirectory() as tmp_dir:
...     model.save_pretrained(tmp_dir, max_shard_size="5GB")
...     new_model = AutoModel.from_pretrained(tmp_dir)
```

The 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.

You 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.


key: _node_content
string_value:
{"id_": "8e001d34-0789-45d0-9894-07caa9054dcc", "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": "bc33d55b-687e-4170-91ae-852d6a8d3e76", "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": "e8d18abd-d894-44f1-85ce-2e568317f8e5", "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": "df49c4cd-94fc-40d3-b0d9-665329b07a33", "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"}


key: chroma:document
string_value:
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.

For example, let's shard [BioMistral/BioMistral-7B](https://hf.co/BioMistral/BioMistral-7B).

```py
>>> with tempfile.TemporaryDirectory() as tmp_dir:
...     model.save_pretrained(tmp_dir, max_shard_size="5GB")
...     print(sorted(os.listdir(tmp_dir)))
['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']
```

The sharded checkpoint is reloaded with the [`~PreTrainedModel.from_pretrained`] method.

```py
>>> with tempfile.TemporaryDirectory() as tmp_dir:
...     model.save_pretrained(tmp_dir, max_shard_size="5GB")
...     new_model = AutoModel.from_pretrained(tmp_dir)
```

The 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.

You 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.

```py
>>> from transformers.modeling_utils import load_sharded_checkpoint

>>> with tempfile.TemporaryDirectory() as tmp_dir:
...     model.save_pretrained(tmp_dir, max_shard_size="5GB")
...     load_sharded_checkpoint(model, tmp_dir)
```

### Shard metadata

The 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.

```py
>>> import json

>>> with tempfile.TemporaryDirectory() as tmp_dir:
...     model.save_pretrained(tmp_dir, max_shard_size="5GB")
...     with open(os.path.join(tmp_dir, "model.safetensors.index.json"), "r") as f:
...         index = json.load(f)

>>> print(index.keys())
dict_keys(['metadata', 'weight_map'])
```

The `metadata` key provides the total model size.

```py
>>> index["metadata"]
{'total_size': 28966928384}
```

The `weight_map` key maps each parameter name (typically `state_dict` in a PyTorch model) to the shard it's stored in.

```py
>>> index["weight_map"]
{'lm_head.weight': 'model-00006-of-00006.safetensors',
 'model.embed_tokens.weight': 'model-00001-of-00006.safetensors',
 'model.layers.0.input_layernorm.weight': 'model-00001-of-00006.safetensors',
 'model.layers.0.mlp.down_proj.weight': 'model-00001-of-00006.safetensors',
 ...
}
```

## Accelerate's Big Model Inference

> [!TIP]
> Make sure you have Accelerate v0.9.0 or later and PyTorch v1.9.0 or later installed.


key: _node_content
string_value:
{"id_": "df49c4cd-94fc-40d3-b0d9-665329b07a33", "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": "bc33d55b-687e-4170-91ae-852d6a8d3e76", "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": "8e001d34-0789-45d0-9894-07caa9054dcc", "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": "510c08f1-d161-41b9-aeaa-a0d61db4a3a5", "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"}


key: chroma:document
string_value:
```py
>>> from transformers.modeling_utils import load_sharded_checkpoint

>>> with tempfile.TemporaryDirectory() as tmp_dir:
...     model.save_pretrained(tmp_dir, max_shard_size="5GB")
...     load_sharded_checkpoint(model, tmp_dir)
```

### Shard metadata

The 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.

```py
>>> import json

>>> with tempfile.TemporaryDirectory() as tmp_dir:
...     model.save_pretrained(tmp_dir, max_shard_size="5GB")
...     with open(os.path.join(tmp_dir, "model.safetensors.index.json"), "r") as f:
...         index = json.load(f)

>>> print(index.keys())
dict_keys(['metadata', 'weight_map'])
```

The `metadata` key provides the total model size.

```py
>>> index["metadata"]
{'total_size': 28966928384}
```

The `weight_map` key maps each parameter name (typically `state_dict` in a PyTorch model) to the shard it's stored in.

```py
>>> index["weight_map"]
{'lm_head.weight': 'model-00006-of-00006.safetensors',
 'model.embed_tokens.weight': 'model-00001-of-00006.safetensors',
 'model.layers.0.input_layernorm.weight': 'model-00001-of-00006.safetensors',
 'model.layers.0.mlp.down_proj.weight': 'model-00001-of-00006.safetensors',
 ...
}
```

## Accelerate's Big Model Inference

> [!TIP]
> Make sure you have Accelerate v0.9.0 or later and PyTorch v1.9.0 or later installed.

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.

To enable Big Model Inference in Transformers, set `low_cpu_mem_usage=True` in the [`~PreTrainedModel.from_pretrained`] method.

```py
from transformers import AutoModelForCausalLM

gemma = AutoModelForCausalLM.from_pretrained("google/gemma-7b", low_cpu_mem_usage=True)
```

Accelerate 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.


key: _node_content
string_value:
{"id_": "510c08f1-d161-41b9-aeaa-a0d61db4a3a5", "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": "bc33d55b-687e-4170-91ae-852d6a8d3e76", "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": "df49c4cd-94fc-40d3-b0d9-665329b07a33", "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": "7a337093-f081-456d-b8aa-fc25e9034660", "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"}


key: chroma:document
string_value:
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.

To enable Big Model Inference in Transformers, set `low_cpu_mem_usage=True` in the [`~PreTrainedModel.from_pretrained`] method.

```py
from transformers import AutoModelForCausalLM

gemma = AutoModelForCausalLM.from_pretrained("google/gemma-7b", low_cpu_mem_usage=True)
```

Accelerate 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.

```py
from transformers import AutoModelForCausalLM

# these loading methods are equivalent
gemma = AutoModelForCausalLM.from_pretrained("google/gemma-7b", device_map="auto")
gemma = AutoModelForCausalLM.from_pretrained("google/gemma-7b", device_map="auto", low_cpu_mem_usage=True)
```

You 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.

```python
device_map = {"model.layers.1": 0, "model.layers.14": 1, "model.layers.31": "cpu", "lm_head": "disk"}
```

Access `hf_device_map` attribute to see how Accelerate split the model across devices.


key: _node_content
string_value:
{"id_": "7a337093-f081-456d-b8aa-fc25e9034660", "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": "bc33d55b-687e-4170-91ae-852d6a8d3e76", "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": "510c08f1-d161-41b9-aeaa-a0d61db4a3a5", "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": "ff3cb909-c0cc-40f1-b934-99b364007dee", "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"}


key: chroma:document
string_value:
To enable Big Model Inference in Transformers, set `low_cpu_mem_usage=True` in the [`~PreTrainedModel.from_pretrained`] method.

```py
from transformers import AutoModelForCausalLM

gemma = AutoModelForCausalLM.from_pretrained("google/gemma-7b", low_cpu_mem_usage=True)
```

Accelerate 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.

```py
from transformers import AutoModelForCausalLM

# these loading methods are equivalent
gemma = AutoModelForCausalLM.from_pretrained("google/gemma-7b", device_map="auto")
gemma = AutoModelForCausalLM.from_pretrained("google/gemma-7b", device_map="auto", low_cpu_mem_usage=True)
```

You 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.

```python
device_map = {"model.layers.1": 0, "model.layers.14": 1, "model.layers.31": "cpu", "lm_head": "disk"}
```

Access `hf_device_map` attribute to see how Accelerate split the model across devices.

```py
gemma.hf_device_map
```

```python out
{'model.embed_tokens': 0,
 'model.layers.0': 0,
 'model.layers.1': 0,
 'model.layers.2': 0,
 'model.layers.3': 0,
 'model.layers.4': 0,
 'model.layers.5': 0,
 'model.layers.6': 0,
 'model.layers.7': 0,
 'model.layers.8': 0,
 'model.layers.9': 0,
 'model.layers.10': 0,
 'model.layers.11': 0,
 'model.layers.12': 0,
 'model.layers.13': 0,
 'model.layers.14': 'cpu',
 'model.layers.15': 'cpu',
 'model.layers.16': 'cpu',
 'model.layers.17': 'cpu',
 'model.layers.18': 'cpu',
 'model.layers.19': 'cpu',
 'model.layers.20': 'cpu',
 'model.layers.21': 'cpu',
 'model.layers.22': 'cpu',
 'model.layers.23': 'cpu',
 'model.layers.24': 'cpu',
 'model.layers.25': 'cpu',
 'model.layers.26': 'cpu',
 'model.layers.27': 'cpu',
 'model.layers.28': 'cpu',
 'model.layers.29': 'cpu',
 'model.layers.30': 'cpu',
 'model.layers.31': 'cpu',
 'model.norm': 'cpu',
 'lm_head': 'cpu'}
```

## Model data type

PyTorch 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.


key: _node_content
string_value:
{"id_": "ff3cb909-c0cc-40f1-b934-99b364007dee", "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": "bc33d55b-687e-4170-91ae-852d6a8d3e76", "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": "7a337093-f081-456d-b8aa-fc25e9034660", "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"}


key: chroma:document
string_value:
```py
gemma.hf_device_map
```

```python out
{'model.embed_tokens': 0,
 'model.layers.0': 0,
 'model.layers.1': 0,
 'model.layers.2': 0,
 'model.layers.3': 0,
 'model.layers.4': 0,
 'model.layers.5': 0,
 'model.layers.6': 0,
 'model.layers.7': 0,
 'model.layers.8': 0,
 'model.layers.9': 0,
 'model.layers.10': 0,
 'model.layers.11': 0,
 'model.layers.12': 0,
 'model.layers.13': 0,
 'model.layers.14': 'cpu',
 'model.layers.15': 'cpu',
 'model.layers.16': 'cpu',
 'model.layers.17': 'cpu',
 'model.layers.18': 'cpu',
 'model.layers.19': 'cpu',
 'model.layers.20': 'cpu',
 'model.layers.21': 'cpu',
 'model.layers.22': 'cpu',
 'model.layers.23': 'cpu',
 'model.layers.24': 'cpu',
 'model.layers.25': 'cpu',
 'model.layers.26': 'cpu',
 'model.layers.27': 'cpu',
 'model.layers.28': 'cpu',
 'model.layers.29': 'cpu',
 'model.layers.30': 'cpu',
 'model.layers.31': 'cpu',
 'model.norm': 'cpu',
 'lm_head': 'cpu'}
```

## Model data type

PyTorch 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.

> [!WARNING]
> Due to how PyTorch is designed, the `torch_dtype` parameter only supports floating data types.

To 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).

<hfoptions id="dtype">
<hfoption id="specific dtype">

```py
from transformers import AutoModelForCausalLM

gemma = AutoModelForCausalLM.from_pretrained("google/gemma-7b", torch_dtype=torch.float16)
```

</hfoption>
<hfoption id="auto dtype">

```py
from transformers import AutoModelForCausalLM

gemma = AutoModelForCausalLM.from_pretrained("google/gemma-7b", torch_dtype="auto")
```

</hfoption>
</hfoptions>

You can also set the data type to use for models instantiated from scratch.

```python
import torch
from transformers import AutoConfig, AutoModel

my_config = AutoConfig.from_pretrained("google/gemma-2b", torch_dtype=torch.float16)
model = AutoModel.from_config(my_config)
```


key: _node_content
string_value:
{"id_": "1c56eb0e-cea4-4bd4-a072-11a13ed255c0", "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": "1156c5e4-7d37-488b-b742-d04acacbf3e0", "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": "6cc9fa90-bcaa-41f5-a7a3-d7ec98b8912a", "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"}


key: chroma:document
string_value:
# Efficient Training on CPU

This guide focuses on training large models efficiently on CPU.

## Mixed precision with IPEX
Mixed 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® Xeon® Scalable processors natively support bf16, so you should get more performance out of the box by enabling mixed precision training with bf16.

To further maximize training performance, you can use Intel® Extension for PyTorch (IPEX), which is a library built on PyTorch and adds additional CPU instruction level architecture (ISA) level support such as Intel® Advanced Vector Extensions 512 Vector Neural Network Instructions (Intel® AVX512-VNNI), and Intel® Advanced Matrix Extensions (Intel® 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.

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.

Check more detailed information for [Auto Mixed Precision](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/features/amp.html).

### IPEX installation:

IPEX release is following PyTorch, to install via pip:

| PyTorch Version   | IPEX version   |
| :---------------: | :----------:   |
| 2.1.x             |  2.1.100+cpu   |
| 2.0.x             |  2.0.100+cpu   |
| 1.13              |  1.13.0+cpu    |
| 1.12              |  1.12.300+cpu  |

Please run `pip list | grep torch` to get your `pytorch_version`, so you can get the `IPEX version_name`.
```bash
pip install intel_extension_for_pytorch==<version_name> -f https://developer.intel.com/ipex-whl-stable-cpu
```
You can check the latest versions in [ipex-whl-stable-cpu](https://developer.intel.com/ipex-whl-stable-cpu) if needed.

Check more approaches for [IPEX installation](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/installation.html).

### Usage in Trainer
To enable auto mixed precision with IPEX in Trainer, users should add `use_ipex`, `bf16` and `no_cuda` in training command arguments.


key: _node_content
string_value:
{"id_": "6cc9fa90-bcaa-41f5-a7a3-d7ec98b8912a", "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": "1156c5e4-7d37-488b-b742-d04acacbf3e0", "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": "1c56eb0e-cea4-4bd4-a072-11a13ed255c0", "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"}


key: chroma:document
string_value:
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.

Check more detailed information for [Auto Mixed Precision](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/features/amp.html).

### IPEX installation:

IPEX release is following PyTorch, to install via pip:

| PyTorch Version   | IPEX version   |
| :---------------: | :----------:   |
| 2.1.x             |  2.1.100+cpu   |
| 2.0.x             |  2.0.100+cpu   |
| 1.13              |  1.13.0+cpu    |
| 1.12              |  1.12.300+cpu  |

Please run `pip list | grep torch` to get your `pytorch_version`, so you can get the `IPEX version_name`.
```bash
pip install intel_extension_for_pytorch==<version_name> -f https://developer.intel.com/ipex-whl-stable-cpu
```
You can check the latest versions in [ipex-whl-stable-cpu](https://developer.intel.com/ipex-whl-stable-cpu) if needed.

Check more approaches for [IPEX installation](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/installation.html).

### Usage in Trainer
To enable auto mixed precision with IPEX in Trainer, users should add `use_ipex`, `bf16` and `no_cuda` in training command arguments.

Take an example of the use cases on [Transformers question-answering](https://github.com/huggingface/transformers/tree/main/examples/pytorch/question-answering)

- Training with IPEX using BF16 auto mixed precision on CPU:
<pre> python run_qa.py \
--model_name_or_path google-bert/bert-base-uncased \
--dataset_name squad \
--do_train \
--do_eval \
--per_device_train_batch_size 12 \
--learning_rate 3e-5 \
--num_train_epochs 2 \
--max_seq_length 384 \
--doc_stride 128 \
--output_dir /tmp/debug_squad/ \
<b>--use_ipex</b> \
<b>--bf16</b> \
<b>--use_cpu</b></pre> 

If you want to enable `use_ipex` and `bf16` in your script, add these parameters to `TrainingArguments` like this:
```diff
training_args = TrainingArguments(
    output_dir=args.output_path,
+   bf16=True,
+   use_ipex=True,
+   use_cpu=True,
    **kwargs
)
```

### Practice example

Blog: [Accelerating PyTorch Transformers with Intel Sapphire Rapids](https://huggingface.co/blog/intel-sapphire-rapids)


key: _node_content
string_value:
{"id_": "489a3907-4c70-438f-9b16-47bdc0132b83", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "dd960067-f047-4064-a614-0c4fb3b411f9", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "hash": "13c1d1df5bd4f7d976e9a09a204c3ffea3813736bd49565008bda2dd6f1fc03d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2e2f677b-bcdf-4ea6-9101-fcc679d8470e", "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"}


key: chroma:document
string_value:
<!---
Copyright 2023 The HuggingFace Team. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

# Model training anatomy

To understand performance optimization techniques that one can apply to improve efficiency of model training 
speed and memory utilization, it's helpful to get familiar with how GPU is utilized during training, and how compute 
intensity varies depending on an operation performed.

Let's start by exploring a motivating example of GPU utilization and the training run of a model. For the demonstration, 
we'll need to install a few libraries: 

```bash
pip install transformers datasets accelerate nvidia-ml-py3
```

The `nvidia-ml-py3` library allows us to monitor the memory usage of the models from within Python. You might be familiar 
with the `nvidia-smi` command in the terminal - this library allows to access the same information in Python directly.

Then, we create some dummy data: random token IDs between 100 and 30000 and binary labels for a classifier. 
In total, we get 512 sequences each with length 512 and store them in a [`~datasets.Dataset`] with PyTorch format.


```py
>>> import numpy as np
>>> from datasets import Dataset


>>> seq_len, dataset_size = 512, 512
>>> dummy_data = {
...     "input_ids": np.random.randint(100, 30000, (dataset_size, seq_len)),
...     "labels": np.random.randint(0, 1, (dataset_size)),
... }
>>> ds = Dataset.from_dict(dummy_data)
>>> ds.set_format("pt")
```

To print summary statistics for the GPU utilization and the training run with the [`Trainer`] we define two helper functions:

```py
>>> from pynvml import *


>>> def print_gpu_utilization():
...     nvmlInit()
...     handle = nvmlDeviceGetHandleByIndex(0)
...     info = nvmlDeviceGetMemoryInfo(handle)
...     print(f"GPU memory occupied: {info.used//1024**2} MB.")


>>> def print_summary(result):
...     print(f"Time: {result.metrics['train_runtime']:.2f}")
...     print(f"Samples/second: {result.metrics['train_samples_per_second']:.2f}")
...     print_gpu_utilization()
```

Let's verify that we start with a free GPU memory:

```py
>>> print_gpu_utilization()
GPU memory occupied: 0 MB.
```

That looks good: the GPU memory is not occupied as we would expect before we load any models. If that's not the case on 
your machine make sure to stop all processes that are using GPU memory. However, not all free GPU memory can be used by 
the 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 
much it is we load a tiny tensor into the GPU which triggers the kernels to be loaded as well.

```py
>>> import torch


key: _node_content
string_value:
{"id_": "2e2f677b-bcdf-4ea6-9101-fcc679d8470e", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "dd960067-f047-4064-a614-0c4fb3b411f9", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "hash": "13c1d1df5bd4f7d976e9a09a204c3ffea3813736bd49565008bda2dd6f1fc03d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "489a3907-4c70-438f-9b16-47bdc0132b83", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "hash": "70d9b744470facac5683ba1b9c8b619954496285fb913d824bc3401aa314ea8c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f003317a-a2bd-4b43-88de-af649a1834da", "node_type": "1", "metadata": {}, "hash": "23ced0273f9b27cf845b683a4943362524ccd82cc5bd4ee3b70ac79b0905b1f0", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1607, "end_char_idx": 4120, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```py
>>> import numpy as np
>>> from datasets import Dataset


>>> seq_len, dataset_size = 512, 512
>>> dummy_data = {
...     "input_ids": np.random.randint(100, 30000, (dataset_size, seq_len)),
...     "labels": np.random.randint(0, 1, (dataset_size)),
... }
>>> ds = Dataset.from_dict(dummy_data)
>>> ds.set_format("pt")
```

To print summary statistics for the GPU utilization and the training run with the [`Trainer`] we define two helper functions:

```py
>>> from pynvml import *


>>> def print_gpu_utilization():
...     nvmlInit()
...     handle = nvmlDeviceGetHandleByIndex(0)
...     info = nvmlDeviceGetMemoryInfo(handle)
...     print(f"GPU memory occupied: {info.used//1024**2} MB.")


>>> def print_summary(result):
...     print(f"Time: {result.metrics['train_runtime']:.2f}")
...     print(f"Samples/second: {result.metrics['train_samples_per_second']:.2f}")
...     print_gpu_utilization()
```

Let's verify that we start with a free GPU memory:

```py
>>> print_gpu_utilization()
GPU memory occupied: 0 MB.
```

That looks good: the GPU memory is not occupied as we would expect before we load any models. If that's not the case on 
your machine make sure to stop all processes that are using GPU memory. However, not all free GPU memory can be used by 
the 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 
much it is we load a tiny tensor into the GPU which triggers the kernels to be loaded as well.

```py
>>> import torch


>>> torch.ones((1, 1)).to("cuda")
>>> print_gpu_utilization()
GPU memory occupied: 1343 MB.
```

We see that the kernels alone take up 1.3GB of GPU memory. Now let's see how much space the model uses.

## Load Model

First, we load the `google-bert/bert-large-uncased` model. We load the model weights directly to the GPU so that we can check 
how much space just the weights use.


```py
>>> from transformers import AutoModelForSequenceClassification


>>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-large-uncased").to("cuda")
>>> print_gpu_utilization()
GPU memory occupied: 2631 MB.
```

We can see that the model weights alone take up 1.3 GB of GPU memory. The exact number depends on the specific 
GPU you are using. Note that on newer GPUs a model can sometimes take up more space since the weights are loaded in an 
optimized fashion that speeds up the usage of the model. Now we can also quickly check if we get the same result 
as with `nvidia-smi` CLI:


key: _node_content
string_value:
{"id_": "f003317a-a2bd-4b43-88de-af649a1834da", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "dd960067-f047-4064-a614-0c4fb3b411f9", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "hash": "13c1d1df5bd4f7d976e9a09a204c3ffea3813736bd49565008bda2dd6f1fc03d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "2e2f677b-bcdf-4ea6-9101-fcc679d8470e", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "hash": "eb0495ecb28a854c5d1f26501604f3769baea895ce5f629b13fde0b62058607c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "df6412f0-f686-47b8-bd02-fc652e4cf1a3", "node_type": "1", "metadata": {}, "hash": "1566cacb2f23c92f1dfe7fbc0bf6ef2aa26ed03b0885c23d2bfbf941e4e279d4", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3123, "end_char_idx": 6477, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
>>> torch.ones((1, 1)).to("cuda")
>>> print_gpu_utilization()
GPU memory occupied: 1343 MB.
```

We see that the kernels alone take up 1.3GB of GPU memory. Now let's see how much space the model uses.

## Load Model

First, we load the `google-bert/bert-large-uncased` model. We load the model weights directly to the GPU so that we can check 
how much space just the weights use.


```py
>>> from transformers import AutoModelForSequenceClassification


>>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-large-uncased").to("cuda")
>>> print_gpu_utilization()
GPU memory occupied: 2631 MB.
```

We can see that the model weights alone take up 1.3 GB of GPU memory. The exact number depends on the specific 
GPU you are using. Note that on newer GPUs a model can sometimes take up more space since the weights are loaded in an 
optimized fashion that speeds up the usage of the model. Now we can also quickly check if we get the same result 
as with `nvidia-smi` CLI:


```bash
nvidia-smi
```

```bash
Tue Jan 11 08:58:05 2022
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 460.91.03    Driver Version: 460.91.03    CUDA Version: 11.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  Tesla V100-SXM2...  On   | 00000000:00:04.0 Off |                    0 |
| N/A   37C    P0    39W / 300W |   2631MiB / 16160MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|    0   N/A  N/A      3721      C   ...nvs/codeparrot/bin/python     2629MiB |
+-----------------------------------------------------------------------------+
```

We 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 
start training the model and see how the GPU memory consumption changes. First, we set up a few standard training 
arguments:

```py
default_args = {
    "output_dir": "tmp",
    "eval_strategy": "steps",
    "num_train_epochs": 1,
    "log_level": "error",
    "report_to": "none",
}
```

<Tip>

 If you plan to run multiple experiments, in order to properly clear the memory between experiments, restart the Python 
 kernel between experiments.

</Tip>

## Memory utilization at vanilla training

Let's use the [`Trainer`] and train the model without using any GPU performance optimization techniques and a batch size of 4:

```py
>>> from transformers import TrainingArguments, Trainer, logging

>>> logging.set_verbosity_error()


key: _node_content
string_value:
{"id_": "df6412f0-f686-47b8-bd02-fc652e4cf1a3", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "dd960067-f047-4064-a614-0c4fb3b411f9", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "hash": "13c1d1df5bd4f7d976e9a09a204c3ffea3813736bd49565008bda2dd6f1fc03d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f003317a-a2bd-4b43-88de-af649a1834da", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "hash": "794a406bf0cd4f83901fcce966b84bd322ceca9b1d8495650652ee717530b3f7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8203fa41-ce10-4848-abbb-a745d69118f7", "node_type": "1", "metadata": {}, "hash": "ce3bd0a4349584d623b0611e962a92bb7ab63b06c0f5212df274e862e9a4bcaf", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 6480, "end_char_idx": 8220, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
>>> training_args = TrainingArguments(per_device_train_batch_size=4, **default_args)
>>> trainer = Trainer(model=model, args=training_args, train_dataset=ds)
>>> result = trainer.train()
>>> print_summary(result)
```

```
Time: 57.82
Samples/second: 8.86
GPU memory occupied: 14949 MB.
```

We see that already a relatively small batch size almost fills up our GPU's entire memory. However, a larger batch size 
can often result in faster model convergence or better end performance. So ideally we want to tune the batch size to our
model's needs and not to the GPU limitations. What's interesting is that we use much more memory than the size of the model. 
To understand a bit better why this is the case let's have a look at a model's operations and memory needs.

## Anatomy of Model's Operations

Transformers architecture includes 3 main groups of operations grouped below by compute-intensity.

1. **Tensor Contractions**

    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.

2. **Statistical Normalizations**

    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.

3. **Element-wise Operators**

    These are the remaining operators: **biases, dropout, activations, and residual connections**. These are the least compute-intensive operations.

This knowledge can be helpful to know when analyzing performance bottlenecks.

This summary is derived from [Data Movement Is All You Need: A Case Study on Optimizing Transformers 2020](https://arxiv.org/abs/2007.00072)


key: _node_content
string_value:
{"id_": "8203fa41-ce10-4848-abbb-a745d69118f7", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "dd960067-f047-4064-a614-0c4fb3b411f9", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "hash": "13c1d1df5bd4f7d976e9a09a204c3ffea3813736bd49565008bda2dd6f1fc03d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "df6412f0-f686-47b8-bd02-fc652e4cf1a3", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "hash": "0829a9f4370bdd0facadd507bdc0b91bc5faa1915e6ad1c4abf2a1e636f8c5ad", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 6480, "end_char_idx": 11390, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
>>> training_args = TrainingArguments(per_device_train_batch_size=4, **default_args)
>>> trainer = Trainer(model=model, args=training_args, train_dataset=ds)
>>> result = trainer.train()
>>> print_summary(result)
```

```
Time: 57.82
Samples/second: 8.86
GPU memory occupied: 14949 MB.
```

We see that already a relatively small batch size almost fills up our GPU's entire memory. However, a larger batch size 
can often result in faster model convergence or better end performance. So ideally we want to tune the batch size to our
model's needs and not to the GPU limitations. What's interesting is that we use much more memory than the size of the model. 
To understand a bit better why this is the case let's have a look at a model's operations and memory needs.

## Anatomy of Model's Operations

Transformers architecture includes 3 main groups of operations grouped below by compute-intensity.

1. **Tensor Contractions**

    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.

2. **Statistical Normalizations**

    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.

3. **Element-wise Operators**

    These are the remaining operators: **biases, dropout, activations, and residual connections**. These are the least compute-intensive operations.

This knowledge can be helpful to know when analyzing performance bottlenecks.

This summary is derived from [Data Movement Is All You Need: A Case Study on Optimizing Transformers 2020](https://arxiv.org/abs/2007.00072)


## Anatomy of Model's Memory

We've seen that training the model uses much more memory than just putting the model on the GPU. This is because there 
are many components during training that use GPU memory. The components on GPU memory are the following:

1. model weights
2. optimizer states
3. gradients
4. forward activations saved for gradient computation
5. temporary buffers
6. functionality-specific memory

A typical model trained in mixed precision with AdamW requires 18 bytes per model parameter plus activation memory. For 
inference there are no optimizer states and gradients, so we can subtract those. And thus we end up with 6 bytes per 
model parameter for mixed precision inference, plus activation memory.

Let's look at the details.

**Model Weights:**

- 4 bytes * number of parameters for fp32 training
- 6 bytes * number of parameters for mixed precision training (maintains a model in fp32 and one in fp16 in memory)

**Optimizer States:**

- 8 bytes * number of parameters for normal AdamW (maintains 2 states)
- 2 bytes * number of parameters for 8-bit AdamW optimizers like [bitsandbytes](https://github.com/TimDettmers/bitsandbytes)
- 4 bytes * number of parameters for optimizers like SGD with momentum (maintains only 1 state)

**Gradients**

- 4 bytes * number of parameters for either fp32 or mixed precision training (gradients are always kept in fp32)

**Forward Activations**

- size depends on many factors, the key ones being sequence length, hidden size and batch size.

There are the input and output that are being passed and returned by the forward and the backward functions and the 
forward activations saved for gradient computation.

**Temporary Memory**

Additionally, there are all kinds of temporary variables which get released once the calculation is done, but in the 
moment these could require additional memory and could push to OOM. Therefore, when coding it's crucial to think 
strategically about such temporary variables and sometimes to explicitly free those as soon as they are no longer needed.

**Functionality-specific memory**

Then, your software could have special memory needs. For example, when generating text using beam search, the software 
needs to maintain multiple copies of inputs and outputs.

**`forward` vs `backward` Execution Speed**

For convolutions and linear layers there are 2x flops in the backward compared to the forward, which generally translates 
into ~2x slower (sometimes more, because sizes in the backward tend to be more awkward). Activations are usually 
bandwidth-limited, and it’s typical for an activation to have to read more data in the backward than in the forward 
(e.g. activation forward reads once, writes once, activation backward reads twice, gradOutput and output of the forward, 
and writes once, gradInput).

As you can see, there are potentially a few places where we could save GPU memory or speed up operations. 
Now that you understand what affects GPU utilization and computation speed, refer to 
the [Methods and tools for efficient training on a single GPU](perf_train_gpu_one) documentation page to learn about 
performance optimization techniques.


key: _node_content
string_value:
{"id_": "3d52a79e-41ec-478a-8460-aa6ef8e1f6a6", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/perplexity", "title": "Perplexity of fixed-length models", "tokens": 1903, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "0187f108-be22-444b-a494-a0c549691954", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/perplexity", "title": "Perplexity of fixed-length models", "tokens": 1903, "retrieve_doc": true, "source": "transformers"}, "hash": "c29ba1f258b9e32a5b6f976fff7045260dca085781f1e2dff67156b969945dc5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3b518f4b-2d4e-4f6e-b29b-efaefeb08537", "node_type": "1", "metadata": {}, "hash": "349273f6595ed9a52b59bc0c7e6170d465dee7e40a42eb62ca7e02927db7b804", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3254, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


