text
stringlengths
5
631k
id
stringlengths
14
178
metadata
dict
__index_level_0__
int64
0
647
# Using TGI with Nvidia GPUs TGI optimized models are supported on NVIDIA [H100](https://www.nvidia.com/en-us/data-center/h100/), [A100](https://www.nvidia.com/en-us/data-center/a100/), [A10G](https://www.nvidia.com/en-us/data-center/products/a10-gpu/) and [T4](https://www.nvidia.com/en-us/data-center/tesla-t4/) GPUs with CUDA 12.2+. Note that you have to install [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html) to use it. For other NVIDIA GPUs, continuous batching will still apply, but some operations like flash attention and paged attention will not be executed. TGI can be used on NVIDIA GPUs through its official docker image: ```bash model=teknium/OpenHermes-2.5-Mistral-7B volume=$PWD/data # share a volume with the Docker container to avoid downloading weights every run docker run --gpus all --shm-size 64g -p 8080:80 -v $volume:/data \ ghcr.io/huggingface/text-generation-inference:3.3.4 \ --model-id $model ``` The launched TGI server can then be queried from clients, make sure to check out the [Consuming TGI](./basic_tutorials/consuming_tgi) guide.
text-generation-inference/docs/source/installation_nvidia.md/0
{ "file_path": "text-generation-inference/docs/source/installation_nvidia.md", "repo_id": "text-generation-inference", "token_count": 377 }
300
from typing import Any, Dict, Generator from _pytest.fixtures import SubRequest from huggingface_hub import AsyncInferenceClient import pytest def pytest_configure(config): config.addinivalue_line( "markers", "gaudi_all_models: mark test to run with all models" ) # The "args" values in TEST_CONFIGS are not optimized for speed but only check that the inference is working for the different models architectures. TEST_CONFIGS = { "meta-llama/Llama-3.1-8B-Instruct-sharded": { "model_id": "meta-llama/Llama-3.1-8B-Instruct", "input": "What is Deep Learning?", "expected_greedy_output": " A Beginner’s Guide\nDeep learning is a subset of machine learning that involves the use of artificial neural networks to analyze and interpret data. It is a type of", "expected_batch_output": " A Beginner’s Guide\nDeep learning is a subset of machine learning that involves the use of artificial neural networks to analyze and interpret data. It is a type of", "args": [ "--sharded", "true", "--num-shard", "2", "--max-input-tokens", "512", "--max-total-tokens", "1024", "--max-batch-size", "4", "--max-batch-prefill-tokens", "2048", ], "run_by_default": True, }, "meta-llama/Llama-3.1-8B-Instruct": { "model_id": "meta-llama/Llama-3.1-8B-Instruct", "input": "What is Deep Learning?", "expected_greedy_output": " A Beginner’s Guide\nDeep learning is a subset of machine learning that involves the use of artificial neural networks to analyze and interpret data. It is a type of", "expected_batch_output": " A Beginner’s Guide\nDeep learning is a subset of machine learning that involves the use of artificial neural networks to analyze and interpret data. It is a type of", "env_config": {}, "args": [ "--max-input-tokens", "512", "--max-total-tokens", "1024", "--max-batch-size", "4", "--max-batch-prefill-tokens", "2048", ], "run_by_default": True, }, "meta-llama/Llama-2-7b-chat-hf": { "model_id": "meta-llama/Llama-2-7b-chat-hf", "input": "What is Deep Learning?", "expected_greedy_output": "\n\nDeep learning (also known as deep structured learning) is part of a broader family of machine learning techniques based on artificial neural networks\u2014specific", "expected_batch_output": "\n\nDeep learning (also known as deep structured learning) is part of a broader family of machine learning techniques based on artificial neural networks\u2014specific", "args": [ "--max-input-tokens", "512", "--max-total-tokens", "1024", "--max-batch-size", "4", "--max-batch-prefill-tokens", "2048", ], }, "mistralai/Mistral-7B-Instruct-v0.3": { "model_id": "mistralai/Mistral-7B-Instruct-v0.3", "input": "What is Deep Learning?", "expected_greedy_output": "\n\nDeep learning is a subset of machine learning in artificial intelligence (AI) that has networks capable of learning unsupervised from data that is unstructured", "expected_batch_output": "\n\nDeep learning is a subset of machine learning in artificial intelligence (AI) that has networks capable of learning unsupervised from data that is unstructured", "args": [ "--max-input-tokens", "512", "--max-total-tokens", "1024", "--max-batch-size", "4", "--max-batch-prefill-tokens", "2048", ], }, "bigcode/starcoder2-3b": { "model_id": "bigcode/starcoder2-3b", "input": "What is Deep Learning?", "expected_greedy_output": "\n\nDeep learning is a subset of machine learning that uses artificial neural networks to perform tasks.\n\nNeural networks are a type of machine learning algorithm that", "expected_batch_output": "\n\nDeep learning is a subset of machine learning that uses artificial neural networks to perform tasks.\n\nNeural networks are a type of machine learning algorithm that", "args": [ "--max-input-tokens", "512", "--max-total-tokens", "1024", "--max-batch-size", "4", "--max-batch-prefill-tokens", "2048", ], }, "google/gemma-7b-it": { "model_id": "google/gemma-7b-it", "input": "What is Deep Learning?", "expected_greedy_output": "\n\nDeep learning is a subset of machine learning that uses artificial neural networks to learn from large amounts of data. Deep learning is a powerful tool for many tasks,", "expected_batch_output": "\n\nDeep learning is a subset of machine learning that uses artificial neural networks to learn from large amounts of data. Deep learning is a powerful tool for many tasks,", "args": [ "--max-input-tokens", "512", "--max-total-tokens", "1024", "--max-batch-size", "4", "--max-batch-prefill-tokens", "2048", ], }, "Qwen/Qwen2-0.5B-Instruct": { "model_id": "Qwen/Qwen2-0.5B-Instruct", "input": "What is Deep Learning?", "expected_greedy_output": " Deep Learning is a type of machine learning that is based on the principles of artificial neural networks. It is a type of machine learning that is used to train models", "expected_batch_output": " Deep Learning is a type of machine learning that is based on the principles of artificial neural networks. It is a type of machine learning that is used to train models", "args": [ "--max-input-tokens", "512", "--max-total-tokens", "1024", "--max-batch-size", "4", "--max-batch-prefill-tokens", "2048", ], }, "tiiuae/falcon-7b-instruct": { "model_id": "tiiuae/falcon-7b-instruct", "input": "What is Deep Learning?", "expected_greedy_output": "\nDeep learning is a branch of machine learning that uses artificial neural networks to learn and make decisions. It is based on the concept of hierarchical learning, where a", "expected_batch_output": "\nDeep learning is a branch of machine learning that uses artificial neural networks to learn and make decisions. It is based on the concept of hierarchical learning, where a", "args": [ "--max-input-tokens", "512", "--max-total-tokens", "1024", "--max-batch-size", "4", ], }, "microsoft/phi-1_5": { "model_id": "microsoft/phi-1_5", "input": "What is Deep Learning?", "expected_greedy_output": "\n\nDeep Learning is a subfield of Machine Learning that focuses on building neural networks with multiple layers of interconnected nodes. These networks are designed to learn from large", "expected_batch_output": "\n\nDeep Learning is a subfield of Machine Learning that focuses on building neural networks with multiple layers of interconnected nodes. These networks are designed to learn from large", "args": [ "--max-input-tokens", "512", "--max-total-tokens", "1024", "--max-batch-size", "4", ], }, "openai-community/gpt2": { "model_id": "openai-community/gpt2", "input": "What is Deep Learning?", "expected_greedy_output": "\n\nDeep learning is a subset of machine learning that is based on artificial neural networks. It is a type of machine learning that is based on the idea of", "expected_batch_output": "\n\nDeep learning is a subset of machine learning that is based on artificial neural networks. It is a type of machine learning that is based on the idea of", "args": [ "--max-input-tokens", "512", "--max-total-tokens", "1024", "--max-batch-size", "4", ], }, "EleutherAI/gpt-j-6b": { "model_id": "EleutherAI/gpt-j-6b", "input": "What is Deep Learning?", "expected_greedy_output": "\n\nDeep learning is a subset of machine learning that is based on the idea of neural networks. Neural networks are a type of artificial intelligence that is inspired by", "expected_batch_output": "\n\nDeep learning is a subset of machine learning that is based on the idea of neural networks. Neural networks are a type of artificial intelligence that is inspired by", "args": [ "--max-input-tokens", "512", "--max-total-tokens", "1024", "--max-batch-size", "4", ], }, } def pytest_generate_tests(metafunc): if "test_config" in metafunc.fixturenames: if metafunc.config.getoption("--gaudi-all-models"): models = list(TEST_CONFIGS.keys()) else: models = [ name for name, config in TEST_CONFIGS.items() if config.get("run_by_default", False) ] print(f"Testing {len(models)} models") metafunc.parametrize("test_config", models, indirect=True) @pytest.fixture(scope="module") def test_config(request: SubRequest) -> Dict[str, Any]: """Fixture that provides model configurations for testing.""" model_name = request.param test_config = TEST_CONFIGS[model_name] test_config["test_name"] = model_name return test_config @pytest.fixture(scope="module") def model_id(test_config: Dict[str, Any]) -> Generator[str, None, None]: yield test_config["model_id"] @pytest.fixture(scope="module") def test_name(test_config: Dict[str, Any]) -> Generator[str, None, None]: yield test_config["test_name"] @pytest.fixture(scope="module") def expected_outputs(test_config: Dict[str, Any]) -> Dict[str, str]: return { "greedy": test_config["expected_greedy_output"], "batch": test_config["expected_batch_output"], } @pytest.fixture(scope="module") def input(test_config: Dict[str, Any]) -> str: return test_config["input"] @pytest.fixture(scope="module") def tgi_service( gaudi_launcher, model_id: str, test_name: str, test_config: Dict[str, Any] ): with gaudi_launcher( model_id, test_name, tgi_args=test_config.get("args", []), env_config=test_config.get("env_config", {}), ) as tgi_service: yield tgi_service @pytest.fixture(scope="module") async def tgi_client(tgi_service) -> AsyncInferenceClient: await tgi_service.health(1000) return tgi_service.client @pytest.mark.asyncio @pytest.mark.all_models async def test_model_single_request( tgi_client: AsyncInferenceClient, expected_outputs: Dict[str, str], input: str ): # Bounded greedy decoding without input response = await tgi_client.text_generation( input, max_new_tokens=32, details=True, decoder_input_details=True, ) assert response.details.generated_tokens == 32 assert response.generated_text == expected_outputs["greedy"] @pytest.mark.asyncio @pytest.mark.all_models async def test_model_multiple_requests( tgi_client: AsyncInferenceClient, gaudi_generate_load, expected_outputs: Dict[str, str], input: str, ): num_requests = 4 responses = await gaudi_generate_load( tgi_client, input, max_new_tokens=32, n=num_requests, ) assert len(responses) == 4 expected = expected_outputs["batch"] for r in responses: assert r.details.generated_tokens == 32 assert r.generated_text == expected
text-generation-inference/integration-tests/gaudi/test_gaudi_generate.py/0
{ "file_path": "text-generation-inference/integration-tests/gaudi/test_gaudi_generate.py", "repo_id": "text-generation-inference", "token_count": 5095 }
301
{ "choices": [ { "finish_reason": "length", "index": 0, "logprobs": null, "text": " A Beginner’s Guide\nDeep learning is a subset" } ], "created": 1741264812, "id": "", "model": "meta-llama/Llama-3.1-8B-Instruct", "object": "text_completion", "system_fingerprint": "3.1.2-dev0-native", "usage": { "completion_tokens": 10, "prompt_tokens": 6, "total_tokens": 16 } }
text-generation-inference/integration-tests/models/__snapshots__/test_completion_prompts/test_flash_llama_completion_single_prompt.json/0
{ "file_path": "text-generation-inference/integration-tests/models/__snapshots__/test_completion_prompts/test_flash_llama_completion_single_prompt.json", "repo_id": "text-generation-inference", "token_count": 209 }
302
{ "details": { "best_of_sequences": null, "finish_reason": "eos_token", "generated_tokens": 30, "prefill": [], "seed": null, "tokens": [ { "id": 6377, "logprob": -0.14916992, "special": false, "text": "{\"" }, { "id": 29888, "logprob": -0.13598633, "special": false, "text": "f" }, { "id": 12935, "logprob": -0.017669678, "special": false, "text": "irs" }, { "id": 29873, "logprob": -0.00085639954, "special": false, "text": "t" }, { "id": 1170, "logprob": -0.0054016113, "special": false, "text": "Name" }, { "id": 4710, "logprob": -0.13549805, "special": false, "text": "\":\"" }, { "id": 19504, "logprob": -0.8852539, "special": false, "text": "David" }, { "id": 3284, "logprob": -0.16394043, "special": false, "text": "\",\"" }, { "id": 29882, "logprob": -0.08862305, "special": false, "text": "h" }, { "id": 711, "logprob": -0.66259766, "special": false, "text": "ob" }, { "id": 1609, "logprob": -5.51939e-05, "special": false, "text": "by" }, { "id": 4710, "logprob": -0.23120117, "special": false, "text": "\":\"" }, { "id": 29911, "logprob": -2.3730469, "special": false, "text": "T" }, { "id": 11003, "logprob": -0.032104492, "special": false, "text": "rees" }, { "id": 3284, "logprob": -0.22021484, "special": false, "text": "\",\"" }, { "id": 4230, "logprob": -0.06726074, "special": false, "text": "last" }, { "id": 1170, "logprob": -0.003501892, "special": false, "text": "Name" }, { "id": 4710, "logprob": -0.0045661926, "special": false, "text": "\":\"" }, { "id": 29950, "logprob": -0.12512207, "special": false, "text": "H" }, { "id": 14339, "logprob": -0.009552002, "special": false, "text": "olt" }, { "id": 29920, "logprob": -0.00042438507, "special": false, "text": "z" }, { "id": 3284, "logprob": -0.11651611, "special": false, "text": "\",\"" }, { "id": 29876, "logprob": -0.29736328, "special": false, "text": "n" }, { "id": 398, "logprob": -0.003030777, "special": false, "text": "um" }, { "id": 29907, "logprob": -0.3774414, "special": false, "text": "C" }, { "id": 1446, "logprob": -0.0003130436, "special": false, "text": "ats" }, { "id": 1115, "logprob": -0.0021514893, "special": false, "text": "\":" }, { "id": 29906, "logprob": -0.071899414, "special": false, "text": "2" }, { "id": 29913, "logprob": -0.018997192, "special": false, "text": "}" }, { "id": 2, "logprob": 0.0, "special": true, "text": "</s>" } ], "top_tokens": null }, "generated_text": "{\"firstName\":\"David\",\"hobby\":\"Trees\",\"lastName\":\"Holtz\",\"numCats\":2}" }
text-generation-inference/integration-tests/models/__snapshots__/test_flash_grammar_llama/test_flash_llama_grammar_json.json/0
{ "file_path": "text-generation-inference/integration-tests/models/__snapshots__/test_flash_grammar_llama/test_flash_llama_grammar_json.json", "repo_id": "text-generation-inference", "token_count": 2413 }
303
{ "details": { "best_of_sequences": null, "finish_reason": "length", "generated_tokens": 10, "prefill": [], "seed": null, "tokens": [ { "id": 198, "logprob": -2.5742188, "special": false, "text": "\n" }, { "id": 262, "logprob": -1.6230469, "special": false, "text": " " }, { "id": 3270, "logprob": -2.046875, "special": false, "text": " \"\"\"\n" }, { "id": 262, "logprob": -0.015281677, "special": false, "text": " " }, { "id": 422, "logprob": -2.1425781, "special": false, "text": " if" }, { "id": 1715, "logprob": -0.9238281, "special": false, "text": " request" }, { "id": 13204, "logprob": -0.076660156, "special": false, "text": ".method" }, { "id": 624, "logprob": -0.021987915, "special": false, "text": " ==" }, { "id": 364, "logprob": -0.39208984, "special": false, "text": " '" }, { "id": 3019, "logprob": -0.10821533, "special": false, "text": "POST" } ], "top_tokens": null }, "generated_text": "\n \"\"\"\n if request.method == 'POST" }
text-generation-inference/integration-tests/models/__snapshots__/test_flash_llama_gptq/test_flash_llama_gptq.json/0
{ "file_path": "text-generation-inference/integration-tests/models/__snapshots__/test_flash_llama_gptq/test_flash_llama_gptq.json", "repo_id": "text-generation-inference", "token_count": 883 }
304
{ "details": { "best_of_sequences": null, "finish_reason": "length", "generated_tokens": 20, "prefill": [], "seed": null, "tokens": [ { "id": 108, "logprob": -0.48046875, "special": false, "text": "\n" }, { "id": 30234, "logprob": -2.21875, "special": false, "text": "Brown" }, { "id": 108, "logprob": -0.119140625, "special": false, "text": "\n" }, { "id": 3726, "logprob": -1.703125, "special": false, "text": "Car" }, { "id": 108, "logprob": -0.0390625, "special": false, "text": "\n" }, { "id": 2915, "logprob": -1.8203125, "special": false, "text": "Color" }, { "id": 108, "logprob": -0.035888672, "special": false, "text": "\n" }, { "id": 19178, "logprob": -2.015625, "special": false, "text": "Cool" }, { "id": 108, "logprob": -0.08105469, "special": false, "text": "\n" }, { "id": 40544, "logprob": -2.09375, "special": false, "text": "Decor" }, { "id": 108, "logprob": -0.038330078, "special": false, "text": "\n" }, { "id": 108, "logprob": -1.515625, "special": false, "text": "\n" }, { "id": 108, "logprob": -1.8671875, "special": false, "text": "\n" }, { "id": 108, "logprob": -1.6328125, "special": false, "text": "\n" }, { "id": 108, "logprob": -1.265625, "special": false, "text": "\n" }, { "id": 108, "logprob": -1.0078125, "special": false, "text": "\n" }, { "id": 108, "logprob": -1.03125, "special": false, "text": "\n" }, { "id": 235336, "logprob": -1.2109375, "special": false, "text": "?" }, { "id": 108, "logprob": -0.29101562, "special": false, "text": "\n" }, { "id": 235336, "logprob": -0.08935547, "special": false, "text": "?" } ], "top_tokens": null }, "generated_text": "\nBrown\nCar\nColor\nCool\nDecor\n\n\n\n\n\n\n?\n?" }
text-generation-inference/integration-tests/models/__snapshots__/test_flash_pali_gemma2/test_flash_pali_gemma_image.json/0
{ "file_path": "text-generation-inference/integration-tests/models/__snapshots__/test_flash_pali_gemma2/test_flash_pali_gemma_image.json", "repo_id": "text-generation-inference", "token_count": 1628 }
305
{ "choices": [ { "finish_reason": "stop", "index": 0, "logprobs": null, "message": { "content": "The image depicts an anthropomorphic rabbit, wearing a spacesuit, standing in a barren, rocky landscape that resembles the surface of another planet, possibly Mars. The rabbit has a red digestive system label on its chest, and the surrounding environment features red sandy terrain and a hazy, floating planet or moon in the background. The scene has a surreal, fantastical quality, blending elements of science fiction and space exploration with a whimsical character.", "name": null, "role": "assistant", "tool_calls": null }, "usage": null } ], "created": 1738347908, "id": "", "model": "Qwen/Qwen2-VL-7B-Instruct", "object": "chat.completion", "system_fingerprint": "3.1.1-dev0-native", "usage": { "completion_tokens": 89, "prompt_tokens": 1364, "total_tokens": 1453 } }
text-generation-inference/integration-tests/models/__snapshots__/test_flash_qwen2_vl/test_flash_qwen2_vl_simple.json/0
{ "file_path": "text-generation-inference/integration-tests/models/__snapshots__/test_flash_qwen2_vl/test_flash_qwen2_vl_simple.json", "repo_id": "text-generation-inference", "token_count": 353 }
306
{ "details": { "best_of_sequences": null, "finish_reason": "stop_sequence", "generated_tokens": 6, "prefill": [], "seed": 0, "tokens": [ { "id": 13, "logprob": -1.0654297, "special": false, "text": "\n" }, { "id": 1014, "logprob": -2.7460938, "special": false, "text": "The" }, { "id": 6032, "logprob": -1.359375, "special": false, "text": " purpose" }, { "id": 302, "logprob": 0.0, "special": false, "text": " of" }, { "id": 456, "logprob": 0.0, "special": false, "text": " this" }, { "id": 1369, "logprob": -0.40063477, "special": false, "text": " test" } ], "top_tokens": null }, "generated_text": "Test request\nThe purpose of this test" }
text-generation-inference/integration-tests/models/__snapshots__/test_llava_next/test_flash_llava_next_all_params.json/0
{ "file_path": "text-generation-inference/integration-tests/models/__snapshots__/test_llava_next/test_flash_llava_next_all_params.json", "repo_id": "text-generation-inference", "token_count": 563 }
307
[ { "details": { "best_of_sequences": null, "finish_reason": "eos_token", "generated_tokens": 6, "prefill": [ { "id": 0, "logprob": null, "text": "<pad>" } ], "seed": null, "tokens": [ { "id": 259, "logprob": -1.3798828, "special": false, "text": " " }, { "id": 39261, "logprob": -0.36328125, "special": false, "text": "Because" }, { "id": 609, "logprob": -1.0947266, "special": false, "text": " it" }, { "id": 339, "logprob": -0.8286133, "special": false, "text": " is" }, { "id": 16017, "logprob": -1.6826172, "special": false, "text": " blue" }, { "id": 1, "logprob": -0.7290039, "special": true, "text": "</s>" } ] }, "generated_text": "Because it is blue" }, { "details": { "best_of_sequences": null, "finish_reason": "eos_token", "generated_tokens": 6, "prefill": [ { "id": 0, "logprob": null, "text": "<pad>" } ], "seed": null, "tokens": [ { "id": 259, "logprob": -1.3789062, "special": false, "text": " " }, { "id": 39261, "logprob": -0.36279297, "special": false, "text": "Because" }, { "id": 609, "logprob": -1.0966797, "special": false, "text": " it" }, { "id": 339, "logprob": -0.8276367, "special": false, "text": " is" }, { "id": 16017, "logprob": -1.6845703, "special": false, "text": " blue" }, { "id": 1, "logprob": -0.72753906, "special": true, "text": "</s>" } ] }, "generated_text": "Because it is blue" }, { "details": { "best_of_sequences": null, "finish_reason": "eos_token", "generated_tokens": 6, "prefill": [ { "id": 0, "logprob": null, "text": "<pad>" } ], "seed": null, "tokens": [ { "id": 259, "logprob": -1.3789062, "special": false, "text": " " }, { "id": 39261, "logprob": -0.36279297, "special": false, "text": "Because" }, { "id": 609, "logprob": -1.0966797, "special": false, "text": " it" }, { "id": 339, "logprob": -0.8276367, "special": false, "text": " is" }, { "id": 16017, "logprob": -1.6845703, "special": false, "text": " blue" }, { "id": 1, "logprob": -0.72753906, "special": true, "text": "</s>" } ] }, "generated_text": "Because it is blue" }, { "details": { "best_of_sequences": null, "finish_reason": "eos_token", "generated_tokens": 6, "prefill": [ { "id": 0, "logprob": null, "text": "<pad>" } ], "seed": null, "tokens": [ { "id": 259, "logprob": -1.3789062, "special": false, "text": " " }, { "id": 39261, "logprob": -0.36279297, "special": false, "text": "Because" }, { "id": 609, "logprob": -1.0966797, "special": false, "text": " it" }, { "id": 339, "logprob": -0.8276367, "special": false, "text": " is" }, { "id": 16017, "logprob": -1.6845703, "special": false, "text": " blue" }, { "id": 1, "logprob": -0.72753906, "special": true, "text": "</s>" } ] }, "generated_text": "Because it is blue" } ]
text-generation-inference/integration-tests/models/__snapshots__/test_mt0_base/test_mt0_base_load.json/0
{ "file_path": "text-generation-inference/integration-tests/models/__snapshots__/test_mt0_base/test_mt0_base_load.json", "repo_id": "text-generation-inference", "token_count": 2874 }
308
import pytest @pytest.fixture(scope="module") def bloom_560m_sharded_handle(launcher): with launcher("bigscience/bloom-560m", num_shard=2) as handle: yield handle @pytest.fixture(scope="module") async def bloom_560m_sharded(bloom_560m_sharded_handle): await bloom_560m_sharded_handle.health(240) return bloom_560m_sharded_handle.client @pytest.mark.release @pytest.mark.asyncio async def test_bloom_560m_sharded(bloom_560m_sharded, response_snapshot): response = await bloom_560m_sharded.generate( "Pour déguster un ortolan, il faut tout d'abord", max_new_tokens=10, top_p=0.9, decoder_input_details=True, seed=0, ) assert response.details.generated_tokens == 10 assert response == response_snapshot @pytest.mark.release @pytest.mark.asyncio async def test_bloom_560m_sharded_load( bloom_560m_sharded, generate_load, response_snapshot ): responses = await generate_load( bloom_560m_sharded, "Pour déguster un ortolan, il faut tout d'abord", max_new_tokens=10, n=4, ) assert len(responses) == 4 assert all([r.generated_text == responses[0].generated_text for r in responses]) assert responses == response_snapshot
text-generation-inference/integration-tests/models/test_bloom_560m_sharded.py/0
{ "file_path": "text-generation-inference/integration-tests/models/test_bloom_560m_sharded.py", "repo_id": "text-generation-inference", "token_count": 527 }
309
import base64 from io import BytesIO from PIL import Image import pytest @pytest.fixture(scope="module") def flash_gemma3_handle(launcher): with launcher("google/gemma-3-4b-it", num_shard=2) as handle: yield handle @pytest.fixture(scope="module") async def flash_gemma3(flash_gemma3_handle): await flash_gemma3_handle.health(300) return flash_gemma3_handle.client async def test_flash_gemma3(flash_gemma3, response_snapshot): response = await flash_gemma3.generate( "Hello I am doing a project on the 1918 flu pandemic and I am trying to find out how many", seed=42, max_new_tokens=100, ) assert ( response.generated_text == " people died in the United States.\n\nThe generally accepted estimate is that 675,000 people died in the United States. However, some historians believe the actual number could be as high as 10 million.\n\nI am looking for more information on this discrepancy and the factors that contributed to the wide range of estimates.\n\nHere's a breakdown of the factors contributing to the wide range of estimates for the 1918 flu pandemic death toll in the United States" ) assert response.details.generated_tokens == 100 assert response == response_snapshot async def test_flash_gemma3_image_cow_dog(flash_gemma3, response_snapshot): image_url = "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/cow_beach_1.png" response = await flash_gemma3.chat( seed=42, messages=[ { "role": "user", "content": [ {"type": "image_url", "image_url": {"url": image_url}}, { "type": "text", "text": "What is the breed of the dog in the image?", }, ], }, ], max_tokens=100, ) assert ( response.choices[0].message.content == "That's a fantastic question! However, the image doesn't show a dog. It shows a **Brown Swiss cow** standing on a beach. \n\nBrown Swiss cows are known for their beautiful reddish-brown coats and distinctive white markings. \n\nIf you'd like, you can send me another image, and I'll do my best to identify the animal in it!" ) assert response.usage["completion_tokens"] == 80 assert response == response_snapshot async def test_flash_gemma3_image_cow(flash_gemma3, response_snapshot): image_url = "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/cow_beach_1.png" response = await flash_gemma3.chat( seed=42, messages=[ { "role": "user", "content": [ {"type": "image_url", "image_url": {"url": image_url}}, {"type": "text", "text": "What is shown in this image?"}, ], }, ], max_tokens=100, ) assert ( response.choices[0].message.content == "Here's a description of what's shown in the image:\n\nThe image depicts a brown cow standing on a sandy beach. The beach has turquoise water and a distant island visible in the background. The sky is bright blue with some white clouds. \n\nIt's a quite a humorous and unusual scene – a cow enjoying a beach day!" ) assert response.usage["completion_tokens"] == 72 assert response == response_snapshot async def test_exceed_window(flash_gemma3, response_snapshot): response = await flash_gemma3.generate( "This is a nice place. " * 800 + "I really enjoy the scenery,", seed=42, max_new_tokens=20, ) assert ( response.generated_text == " the people, and the food.\n\nThis is a nice place.\n" ) assert response.details.generated_tokens == 16 assert response == response_snapshot # Helper function to convert a Pillow image to a base64 data URL def image_to_data_url(img: Image.Image, fmt: str) -> str: buffer = BytesIO() img.save(buffer, format=fmt) img_data = buffer.getvalue() b64_str = base64.b64encode(img_data).decode("utf-8") mime_type = "image/png" if fmt.upper() == "PNG" else "image/jpeg" return f"data:{mime_type};base64,{b64_str}" async def test_flash_gemma3_image_base64_rgba(flash_gemma3, response_snapshot): # Create an empty 100x100 PNG image with alpha (transparent background) img = Image.new("RGBA", (100, 100), (0, 0, 0, 0)) data_url = image_to_data_url(img, "PNG") response = await flash_gemma3.chat( seed=42, messages=[ { "role": "user", "content": [ {"type": "image_url", "image_url": {"url": data_url}}, { "type": "text", "text": "What do you see in this transparent image?", }, ], }, ], max_tokens=100, ) assert response == response_snapshot async def test_flash_gemma3_image_base64_rgb_png(flash_gemma3, response_snapshot): # Create an empty 100x100 PNG image without alpha (white background) img = Image.new("RGB", (100, 100), (255, 255, 255)) data_url = image_to_data_url(img, "PNG") response = await flash_gemma3.chat( seed=42, messages=[ { "role": "user", "content": [ {"type": "image_url", "image_url": {"url": data_url}}, {"type": "text", "text": "What do you see in this plain image?"}, ], }, ], max_tokens=100, ) assert response == response_snapshot async def test_flash_gemma3_image_base64_rgb_jpg(flash_gemma3, response_snapshot): # Create an empty 100x100 JPEG image (white background) img = Image.new("RGB", (100, 100), (255, 255, 255)) data_url = image_to_data_url(img, "JPEG") response = await flash_gemma3.chat( seed=42, messages=[ { "role": "user", "content": [ {"type": "image_url", "image_url": {"url": data_url}}, {"type": "text", "text": "What do you see in this JPEG image?"}, ], }, ], max_tokens=100, ) assert response == response_snapshot
text-generation-inference/integration-tests/models/test_flash_gemma3.py/0
{ "file_path": "text-generation-inference/integration-tests/models/test_flash_gemma3.py", "repo_id": "text-generation-inference", "token_count": 2840 }
310
import pytest @pytest.fixture(scope="module") def flash_mixtral_awq_handle(launcher): with launcher("casperhansen/mixtral-instruct-awq", num_shard=2) as handle: yield handle @pytest.fixture(scope="module") async def flash_mixtral_awq(flash_mixtral_awq_handle): await flash_mixtral_awq_handle.health(300) return flash_mixtral_awq_handle.client @pytest.mark.asyncio async def test_flash_mixtral_awq(flash_mixtral_awq, response_snapshot): response = await flash_mixtral_awq.generate( "What is deep learning?", max_new_tokens=10, decoder_input_details=True ) assert response.details.generated_tokens == 10 assert ( response.generated_text == "\n\nDeep learning is a subset of machine learning" ) assert response == response_snapshot @pytest.mark.asyncio async def test_flash_mixtral_awq_all_params(flash_mixtral_awq, response_snapshot): response = await flash_mixtral_awq.generate( "What is deep learning?", max_new_tokens=10, repetition_penalty=1.2, return_full_text=True, stop_sequences=["test"], temperature=0.5, top_p=0.9, top_k=10, truncate=5, typical_p=0.9, watermark=True, decoder_input_details=True, seed=0, ) assert response.details.generated_tokens == 10 assert ( response.generated_text == "What is deep learning?\nDeep Learning is a subset of Machine Learning," ) assert response == response_snapshot @pytest.mark.asyncio async def test_flash_mixtral_awq_load( flash_mixtral_awq, generate_load, response_snapshot ): responses = await generate_load( flash_mixtral_awq, "What is deep learning?", max_new_tokens=10, n=4 ) assert len(responses) == 4 assert responses[0].details.generated_tokens == 10 assert ( responses[0].generated_text == "\n\nDeep learning is a subset of machine learning" ) assert all( [r.generated_text == responses[0].generated_text for r in responses] ), f"{[r.generated_text for r in responses]}" assert responses == response_snapshot
text-generation-inference/integration-tests/models/test_flash_mixtral_awq.py/0
{ "file_path": "text-generation-inference/integration-tests/models/test_flash_mixtral_awq.py", "repo_id": "text-generation-inference", "token_count": 898 }
311
import pytest import json from text_generation.types import GrammarType @pytest.fixture(scope="module") def non_flash_llama_grammar_handle(launcher): with launcher( "TinyLlama/TinyLlama-1.1B-Chat-v1.0", num_shard=1, disable_grammar_support=False, use_flash_attention=False, ) as handle: yield handle @pytest.fixture(scope="module") async def non_flash_llama_grammar(non_flash_llama_grammar_handle): await non_flash_llama_grammar_handle.health(300) return non_flash_llama_grammar_handle.client @pytest.mark.release @pytest.mark.skip @pytest.mark.asyncio async def test_non_flash_llama_grammar_json(non_flash_llama_grammar, response_snapshot): response = await non_flash_llama_grammar.generate( "info: david holtz like trees and has two cats. ", max_new_tokens=100, decoder_input_details=True, seed=0, grammar={ "type": GrammarType.Json, "value": json.dumps( { "type": "object", "$id": "https://example.com/person.schema.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "Person", "properties": { "firstName": { "type": "string", "description": "The person'''s first name.", }, "lastName": { "type": "string", "description": "The person'''s last name.", }, "hobby": { "description": "The person'''s hobby.", "type": "string", }, "numCats": { "description": "The number of cats the person has.", "type": "integer", "minimum": 0, }, }, "required": ["firstName", "lastName", "hobby", "numCats"], } ), }, ) assert response.details.generated_tokens == 30 assert ( response.generated_text == '{"firstName":"David","hobby":"Trees","lastName":"Holtz","numCats":2}' ) assert response == response_snapshot
text-generation-inference/integration-tests/models/test_grammar_llama.py/0
{ "file_path": "text-generation-inference/integration-tests/models/test_grammar_llama.py", "repo_id": "text-generation-inference", "token_count": 1346 }
312
import pytest @pytest.fixture(scope="module") def t5_sharded_handle(launcher): with launcher("google/flan-t5-xxl", num_shard=4) as handle: yield handle @pytest.fixture(scope="module") async def t5_sharded(t5_sharded_handle): await t5_sharded_handle.health(300) return t5_sharded_handle.client @pytest.mark.release @pytest.mark.asyncio async def test_t5_sharded(t5_sharded, response_snapshot): response = await t5_sharded.generate( "Please answer the following question. What is the boiling point of Nitrogen?", max_new_tokens=10, decoder_input_details=True, ) assert response == response_snapshot @pytest.mark.release @pytest.mark.asyncio async def test_t5_sharded_load(t5_sharded, generate_load, response_snapshot): responses = await generate_load( t5_sharded, "Please answer the following question. What is the boiling point of Nitrogen?", max_new_tokens=10, n=4, ) assert len(responses) == 4 assert all([r.generated_text == responses[0].generated_text for r in responses]) assert responses == response_snapshot
text-generation-inference/integration-tests/models/test_t5_sharded.py/0
{ "file_path": "text-generation-inference/integration-tests/models/test_t5_sharded.py", "repo_id": "text-generation-inference", "token_count": 443 }
313
import argparse import datetime import json import os import traceback from typing import Dict, Tuple, List import GPUtil import docker from docker.models.containers import Container from loguru import logger import pandas as pd class InferenceEngineRunner: def __init__(self, model: str): self.model = model def run(self, parameters: list[tuple], gpus: int = 0): NotImplementedError("This method should be implemented by the subclass") def stop(self): NotImplementedError("This method should be implemented by the subclass") class TGIDockerRunner(InferenceEngineRunner): def __init__( self, model: str, image: str = "ghcr.io/huggingface/text-generation-inference:latest", volumes=None, ): super().__init__(model) if volumes is None: volumes = [] self.container = None self.image = image self.volumes = volumes def run(self, parameters: list[tuple], gpus: int = 0): params = f"--model-id {self.model} --port 8080" for p in parameters: params += f" --{p[0]} {str(p[1])}" logger.info(f"Running TGI with parameters: {params}") volumes = {} for v in self.volumes: volumes[v[0]] = {"bind": v[1], "mode": "rw"} self.container = run_docker( self.image, params, "Connected", "ERROR", volumes=volumes, gpus=gpus, ports={"8080/tcp": 8080}, ) def stop(self): if self.container: self.container.stop() class BenchmarkRunner: def __init__( self, image: str = "ghcr.io/huggingface/text-generation-inference-benchmark:latest", volumes: List[Tuple[str, str]] = None, ): if volumes is None: volumes = [] self.container = None self.image = image self.volumes = volumes def run(self, parameters: list[tuple], network_mode): params = "text-generation-inference-benchmark" for p in parameters: params += f" --{p[0]} {str(p[1])}" if p[1] is not None else f" --{p[0]}" logger.info( f"Running text-generation-inference-benchmarks with parameters: {params}" ) volumes = {} for v in self.volumes: volumes[v[0]] = {"bind": v[1], "mode": "rw"} self.container = run_docker( self.image, params, "Benchmark finished", "Fatal:", volumes=volumes, extra_env={ "RUST_LOG": "text_generation_inference_benchmark=info", "RUST_BACKTRACE": "full", }, network_mode=network_mode, ) def stop(self): if self.container: self.container.stop() def run_docker( image: str, args: str, success_sentinel: str, error_sentinel: str, ports: Dict[str, int] = None, volumes=None, network_mode: str = "bridge", gpus: int = 0, extra_env: Dict[str, str] = None, ) -> Container: if ports is None: ports = {} if volumes is None: volumes = {} if extra_env is None: extra_env = {} client = docker.from_env(timeout=300) # retrieve the GPU devices from CUDA_VISIBLE_DEVICES devices = [f"{i}" for i in range(get_num_gpus())][:gpus] environment = {"HF_TOKEN": os.environ.get("HF_TOKEN")} environment.update(extra_env) container = client.containers.run( image, args, detach=True, device_requests=( [docker.types.DeviceRequest(device_ids=devices, capabilities=[["gpu"]])] if gpus > 0 else None ), volumes=volumes, shm_size="1g", ports=ports, network_mode=network_mode, environment=environment, ) for line in container.logs(stream=True): print(line.decode("utf-8"), end="") if success_sentinel.encode("utf-8") in line: break if error_sentinel.encode("utf-8") in line: container.stop() raise Exception(f"Error starting container: {line}") return container def get_gpu_names() -> str: gpus = GPUtil.getGPUs() if len(gpus) == 0: return "" return f'{len(gpus)}x{gpus[0].name if gpus else "No GPU available"}' def get_gpu_name() -> str: gpus = GPUtil.getGPUs() if len(gpus) == 0: return "" return gpus[0].name def get_num_gpus() -> int: return len(GPUtil.getGPUs()) def build_df(model: str, data_files: dict[str, str]) -> pd.DataFrame: df = pd.DataFrame() now = datetime.datetime.now(datetime.timezone.utc) created_at = now.isoformat() # '2024-10-02T11:53:17.026215+00:00' # Load the results for key, filename in data_files.items(): with open(filename, "r") as f: data = json.load(f) for result in data["results"]: entry = result [config] = pd.json_normalize(result["config"]).to_dict(orient="records") entry.update(config) entry["engine"] = data["config"]["meta"]["engine"] entry["tp"] = data["config"]["meta"]["tp"] entry["version"] = data["config"]["meta"]["version"] entry["model"] = model entry["created_at"] = created_at del entry["config"] df = pd.concat([df, pd.DataFrame(entry, index=[0])]) return df def main(sha, results_file): results_dir = "results" # get absolute path results_dir = os.path.join(os.path.dirname(__file__), results_dir) logger.info("Starting benchmark") models = [ ("meta-llama/Llama-3.1-8B-Instruct", 1), # ('meta-llama/Llama-3.1-70B-Instruct', 4), # ('mistralai/Mixtral-8x7B-Instruct-v0.1', 2), ] success = True for model in models: tgi_runner = TGIDockerRunner(model[0]) # create results directory model_dir = os.path.join( results_dir, f'{model[0].replace("/", "_").replace(".", "_")}' ) os.makedirs(model_dir, exist_ok=True) runner = BenchmarkRunner( volumes=[(model_dir, "/opt/text-generation-inference-benchmark/results")] ) try: tgi_runner.run([("max-concurrent-requests", 512)], gpus=model[1]) logger.info(f"TGI started for model {model[0]}") parameters = [ ("tokenizer-name", model[0]), ("max-vus", 800), ("url", "http://localhost:8080"), ("duration", "120s"), ("warmup", "30s"), ("benchmark-kind", "rate"), ( "prompt-options", "num_tokens=200,max_tokens=220,min_tokens=180,variance=10", ), ( "decode-options", "num_tokens=200,max_tokens=220,min_tokens=180,variance=10", ), ( "extra-meta", f'"engine=TGI,tp={model[1]},version={sha},gpu={get_gpu_name()}"', ), ("no-console", None), ] rates = [("rates", f"{r / 10.}") for r in list(range(8, 248, 8))] parameters.extend(rates) runner.run(parameters, f"container:{tgi_runner.container.id}") except Exception as e: logger.error(f"Error running benchmark for model {model[0]}: {e}") # print the stack trace print(traceback.format_exc()) success = False finally: tgi_runner.stop() runner.stop() if not success: logger.error("Some benchmarks failed") exit(1) df = pd.DataFrame() # list recursively directories directories = [ f"{results_dir}/{d}" for d in os.listdir(results_dir) if os.path.isdir(f"{results_dir}/{d}") ] logger.info(f"Found result directories: {directories}") for directory in directories: data_files = {} for filename in os.listdir(directory): if filename.endswith(".json"): data_files[filename.split(".")[-2]] = f"{directory}/{filename}" logger.info(f"Processing directory {directory}") df = pd.concat([df, build_df(directory.split("/")[-1], data_files)]) df["device"] = get_gpu_name() df["error_rate"] = ( df["failed_requests"] / (df["failed_requests"] + df["successful_requests"]) * 100.0 ) df.to_parquet(results_file) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--sha", help="SHA of the commit to add to the results", required=True ) parser.add_argument( "--results-file", help="The file where to store the results, can be a local file or a s3 path", ) args = parser.parse_args() if args.results_file is None: results_file = f"{args.sha}.parquet" else: results_file = args.results_file main(args.sha, results_file)
text-generation-inference/load_tests/benchmarks.py/0
{ "file_path": "text-generation-inference/load_tests/benchmarks.py", "repo_id": "text-generation-inference", "token_count": 4444 }
314
use crate::infer::Infer; use crate::server::{generate_internal, ComputeType}; use crate::{ChatRequest, ErrorResponse, GenerateParameters, GenerateRequest}; use axum::extract::Extension; use axum::http::{HeaderMap, StatusCode}; use axum::response::{IntoResponse, Response}; use axum::Json; use serde::{Deserialize, Serialize}; use tracing::instrument; use tracing_opentelemetry::OpenTelemetrySpanExt; use utoipa::ToSchema; #[derive(Clone, Deserialize, ToSchema)] #[cfg_attr(test, derive(Debug, PartialEq))] pub(crate) struct GenerateVertexInstance { #[schema(example = "What is Deep Learning?")] pub inputs: String, #[schema(nullable = true, default = "null", example = "null")] pub parameters: Option<GenerateParameters>, } #[derive(Clone, Deserialize, ToSchema)] #[cfg_attr(test, derive(Debug, PartialEq))] #[serde(untagged)] pub(crate) enum VertexInstance { Generate(GenerateVertexInstance), Chat(ChatRequest), } #[derive(Deserialize, ToSchema)] #[cfg_attr(test, derive(Debug, PartialEq))] pub(crate) struct VertexRequest { #[serde(rename = "instances")] pub instances: Vec<VertexInstance>, } #[derive(Clone, Deserialize, ToSchema, Serialize)] pub(crate) struct VertexResponse { pub predictions: Vec<String>, } /// Generate tokens from Vertex request #[utoipa::path( post, tag = "Text Generation Inference", path = "/vertex", request_body = VertexRequest, responses( (status = 200, description = "Generated Text", body = VertexResponse), (status = 424, description = "Generation Error", body = ErrorResponse, example = json ! ({"error": "Request failed during generation"})), (status = 429, description = "Model is overloaded", body = ErrorResponse, example = json ! ({"error": "Model is overloaded"})), (status = 422, description = "Input validation error", body = ErrorResponse, example = json ! ({"error": "Input validation error"})), (status = 500, description = "Incomplete generation", body = ErrorResponse, example = json ! ({"error": "Incomplete generation"})), ) )] #[instrument( skip_all, fields( total_time, validation_time, queue_time, inference_time, time_per_token, seed, ) )] pub(crate) async fn vertex_compatibility( Extension(infer): Extension<Infer>, Extension(compute_type): Extension<ComputeType>, Extension(context): Extension<Option<opentelemetry::Context>>, Json(req): Json<VertexRequest>, ) -> Result<Response, (StatusCode, Json<ErrorResponse>)> { let span = tracing::Span::current(); if let Some(context) = context { span.set_parent(context); } metrics::counter!("tgi_request_count").increment(1); // check that theres at least one instance if req.instances.is_empty() { return Err(( StatusCode::UNPROCESSABLE_ENTITY, Json(ErrorResponse { error: "Input validation error".to_string(), error_type: "Input validation error".to_string(), }), )); } // Prepare futures for all instances let mut futures = Vec::with_capacity(req.instances.len()); for instance in req.instances.into_iter() { let generate_request = match instance { VertexInstance::Generate(instance) => GenerateRequest { inputs: instance.inputs.clone(), add_special_tokens: true, parameters: GenerateParameters { do_sample: true, max_new_tokens: instance.parameters.as_ref().and_then(|p| p.max_new_tokens), seed: instance.parameters.as_ref().and_then(|p| p.seed), details: true, decoder_input_details: true, ..Default::default() }, }, VertexInstance::Chat(instance) => { let (generate_request, _using_tools): (GenerateRequest, bool) = instance.try_into_generate(&infer)?; generate_request } }; let infer_clone = infer.clone(); let compute_type_clone = compute_type.clone(); let span_clone = span.clone(); futures.push(async move { generate_internal( Extension(infer_clone), compute_type_clone, Json(generate_request), span_clone, ) .await .map(|(_, _, Json(generation))| generation.generated_text) .map_err(|_| { ( StatusCode::INTERNAL_SERVER_ERROR, Json(ErrorResponse { error: "Incomplete generation".into(), error_type: "Incomplete generation".into(), }), ) }) }); } // execute all futures in parallel, collect results, returning early if any error occurs let results = futures::future::join_all(futures).await; let predictions: Result<Vec<_>, _> = results.into_iter().collect(); let predictions = predictions?; let response = VertexResponse { predictions }; Ok((HeaderMap::new(), Json(response)).into_response()) } #[cfg(test)] mod tests { use super::*; use crate::{Message, MessageBody, MessageContent}; #[test] fn vertex_deserialization() { let string = serde_json::json!({ "instances": [ { "messages": [{"role": "user", "content": "What's Deep Learning?"}], "max_tokens": 128, "top_p": 0.95, "temperature": 0.7 } ] }); let request: VertexRequest = serde_json::from_value(string).expect("Can deserialize"); assert_eq!( request, VertexRequest { instances: vec![VertexInstance::Chat(ChatRequest { messages: vec![Message { name: None, role: "user".to_string(), body: MessageBody::Content { content: MessageContent::SingleText( "What's Deep Learning?".to_string() ) }, },], max_tokens: Some(128), top_p: Some(0.95), temperature: Some(0.7), ..Default::default() })] } ); } }
text-generation-inference/router/src/vertex.rs/0
{ "file_path": "text-generation-inference/router/src/vertex.rs", "repo_id": "text-generation-inference", "token_count": 2983 }
315
from setuptools import setup from torch.utils.cpp_extension import BuildExtension, CUDAExtension import torch extra_cuda_cflags = [] extra_cflags = [] if torch.version.hip: extra_cflags = ["-DLEGACY_HIPBLAS_DIRECT=ON"] extra_cuda_cflags = ["-DLEGACY_HIPBLAS_DIRECT=ON"] extra_compile_args = { "cxx": extra_cflags, "nvcc": extra_cuda_cflags, } setup( name="exllama_kernels", ext_modules=[ CUDAExtension( name="exllama_kernels", sources=[ "exllama_kernels/exllama_ext.cpp", "exllama_kernels/cuda_buffers.cu", "exllama_kernels/cuda_func/column_remap.cu", "exllama_kernels/cuda_func/q4_matmul.cu", "exllama_kernels/cuda_func/q4_matrix.cu", ], extra_compile_args=extra_compile_args, ) ], cmdclass={"build_ext": BuildExtension}, )
text-generation-inference/server/exllama_kernels/setup.py/0
{ "file_path": "text-generation-inference/server/exllama_kernels/setup.py", "repo_id": "text-generation-inference", "token_count": 470 }
316
#ifndef _qdq_8_cuh #define _qdq_8_cuh #include "qdq_util.cuh" #include "../../config.h" #if QMODE_8BIT == 1 // Not implemented #else __forceinline__ __device__ void shuffle_8bit_4 ( uint32_t* q, int stride ) { } __forceinline__ __device__ void dequant_8bit_8 ( const uint32_t q_0, const uint32_t q_1, half2 (&dq)[4], int stride ) { half dqh[8]; for (int i = 0; i < 4; i++) dqh[i ] = dq_ns(exb(q_0, i * 8, 0xff), 128); for (int i = 0; i < 4; i++) dqh[i + 4] = dq_ns(exb(q_1, i * 8, 0xff), 128); for (int i = 0; i < 4; i++) dq[i] = __halves2half2(dqh[i * 2], dqh[i * 2 + 1]); } #endif #endif
text-generation-inference/server/exllamav2_kernels/exllamav2_kernels/cuda/quant/qdq_8.cuh/0
{ "file_path": "text-generation-inference/server/exllamav2_kernels/exllamav2_kernels/cuda/quant/qdq_8.cuh", "repo_id": "text-generation-inference", "token_count": 337 }
317
import pytest from text_generation_server.pb import generate_pb2 from text_generation_server.models.causal_lm import CausalLMBatch, CausalLM @pytest.fixture(scope="session") def default_santacoder(): return CausalLM.fallback(model_id="bigcode/santacoder") @pytest.fixture def default_pb_request(default_pb_parameters, default_pb_stop_parameters): return generate_pb2.Request( id=0, inputs="def", input_chunks=generate_pb2.Input(chunks=[generate_pb2.InputChunk(text="def")]), prefill_logprobs=True, truncate=100, parameters=default_pb_parameters, stopping_parameters=default_pb_stop_parameters, ) @pytest.fixture def default_pb_batch(default_pb_request): return generate_pb2.Batch(id=0, requests=[default_pb_request], size=1) @pytest.fixture def default_fim_pb_request(default_pb_parameters, default_pb_stop_parameters): return generate_pb2.Request( id=0, inputs="<fim-prefix>def<fim-suffix>world<fim-middle>", input_chunks=generate_pb2.Input( chunks=[ generate_pb2.InputChunk( text="<fim-prefix>def<fim-suffix>world<fim-middle>" ) ] ), prefill_logprobs=True, truncate=100, parameters=default_pb_parameters, stopping_parameters=default_pb_stop_parameters, ) @pytest.fixture def default_fim_pb_batch(default_fim_pb_request): return generate_pb2.Batch(id=0, requests=[default_fim_pb_request], size=1) @pytest.mark.skip def test_santacoder_generate_token_completion(default_santacoder, default_pb_batch): batch = CausalLMBatch.from_pb( default_pb_batch, default_santacoder.tokenizer, default_santacoder.dtype, default_santacoder.device, ) next_batch = batch for _ in range(batch.stopping_criterias[0].max_new_tokens - 1): generations, next_batch, _ = default_santacoder.generate_token(next_batch) assert len(generations) == len(next_batch) generations, next_batch, _ = default_santacoder.generate_token(next_batch) assert next_batch is None assert len(generations) == 1 assert generations[0].generated_text.text == " test_get_all_users_with_" assert generations[0].request_id == batch.requests[0].id assert ( generations[0].generated_text.generated_tokens == batch.stopping_criterias[0].max_new_tokens ) @pytest.mark.skip def test_fim_santacoder_generate_token_completion( default_santacoder, default_fim_pb_batch ): batch = CausalLMBatch.from_pb( default_fim_pb_batch, default_santacoder.tokenizer, default_santacoder.dtype, default_santacoder.device, ) next_batch = batch for _ in range(batch.stopping_criterias[0].max_new_tokens - 1): generations, next_batch, _ = default_santacoder.generate_token(next_batch) assert len(generations) == len(next_batch) generations, next_batch, _ = default_santacoder.generate_token(next_batch) assert next_batch is None assert len(generations) == 1 assert ( generations[0].generated_text.text == """ineProperty(exports, "__esModule", { value""" ) assert generations[0].request_id == batch.requests[0].id assert ( generations[0].generated_text.generated_tokens == batch.stopping_criterias[0].max_new_tokens )
text-generation-inference/server/tests/models/test_santacoder.py/0
{ "file_path": "text-generation-inference/server/tests/models/test_santacoder.py", "repo_id": "text-generation-inference", "token_count": 1480 }
318
import torch import grpc from google.rpc import status_pb2, code_pb2 from grpc_status import rpc_status from grpc_interceptor.server import AsyncServerInterceptor from loguru import logger from typing import Callable, Any class ExceptionInterceptor(AsyncServerInterceptor): def __init__(self, shutdown_callback): self.shutdown_callback = shutdown_callback async def intercept( self, method: Callable, request_or_iterator: Any, context: grpc.ServicerContext, method_name: str, ) -> Any: try: response = method(request_or_iterator, context) return await response except Exception as err: method_name = method_name.split("/")[-1] logger.exception(f"Method {method_name} encountered an error.") # Runtime Error cannot be recovered from if isinstance(err, RuntimeError): self.shutdown_callback() if torch.cuda.is_available(): torch.cuda.empty_cache() await context.abort_with_status( rpc_status.to_status( status_pb2.Status(code=code_pb2.INTERNAL, message=str(err)) ) )
text-generation-inference/server/text_generation_server/interceptor.py/0
{ "file_path": "text-generation-inference/server/text_generation_server/interceptor.py", "repo_id": "text-generation-inference", "token_count": 545 }
319
from typing import Any, Dict, List, Union from compressed_tensors import QuantizationConfig, QuantizationStatus from compressed_tensors.config import CompressionFormat from compressed_tensors.quantization import ( QuantizationScheme, QuantizationType, find_name_or_class_matches, ) from loguru import logger from pydantic import ValidationError from torch import nn from text_generation_server.layers.compressed_tensors.w8an_fp import W8ANFpLoader from text_generation_server.layers.compressed_tensors.w8a8_int import W8A8IntLoader from text_generation_server.layers.compressed_tensors.wna16_int_24 import ( WNA16Int24Loader, ) from text_generation_server.layers.compressed_tensors.wna16_int import WNA16IntLoader from text_generation_server.utils.log import log_once from text_generation_server.utils.weights import ( DefaultWeightsLoader, UnquantizedWeight, Weights, WeightsLoader, ) # compressed-tensors can match modules as quantization targets. However, # they need to be objects rather than classes or class names. Since we # need to match `Linear` targets, make an instance that can be re-used. _EMPTY_LINEAR: nn.Module = nn.Linear(0, 0) class CompressedTensorsLoader(WeightsLoader): """Loader for checkpoints stored in the compressed-tensors format.""" def __init__(self, config: Dict[str, Any]): quantization_config_raw = config.get("quantization_config") if quantization_config_raw is None: # `compression_config` was renamed to `quantization_config`; support # retained for backward compatibility. quantization_config_raw = config.get("compression_config") if quantization_config_raw is None: raise ValueError( "Checkpoint does not have compressed-tensors configuration" ) try: quantization_config = QuantizationConfig.model_validate( quantization_config_raw ) except ValidationError as e: raise ValueError("Cannot parse compressed-tensors configuration") from e if quantization_config.quantization_status not in ( QuantizationStatus.COMPRESSED, QuantizationStatus.FROZEN, ): raise ValueError( f"Model quantization was not finished, status was: {quantization_config.quantization_status}" ) self.ignore = ( quantization_config.ignore if quantization_config.ignore is not None else [] ) self.loaders = self._get_target_loaders(quantization_config) for target, loader in self.loaders.items(): log_once( logger.info, f"Using {loader} for compressed-tensors target '{target}'", ) def get_weights(self, weights: Weights, prefix: str): loader = self._lookup_loader(prefix) return loader.get_weights(weights, prefix) def get_weights_col_packed( self, weights: "Weights", prefix: str, block_sizes: Union[int, List[int]], ): loader = self._lookup_loader(prefix) return loader.get_weights_col_packed(weights, prefix, block_sizes) def get_multi_weights_col(self, weights: Weights, prefixes: List[str], dim: int): loader = self._lookup_loader(prefixes[0]) return loader.get_multi_weights_col(weights, prefixes, dim) def get_weights_row(self, weights: Weights, prefix: str): loader = self._lookup_loader(prefix) return loader.get_weights_row(weights, prefix) def _get_target_loaders( self, quantization_config: QuantizationConfig ) -> Dict[str, WeightsLoader]: """ A compressed-tensors checkpoint can use different quantizations for different targets. This method returns a dictionary with a loader per target. """ loaders: Dict[str, WeightsLoader] = {} format = quantization_config.format for group_name, group in quantization_config.config_groups.items(): # The group configuration can be a string, but does that ever # happen in a serialized quantization config? assert isinstance(group, QuantizationScheme) loader = self._create_loader_for_group(format, group_name, group) # A quantized parameter group can have multiple targets, add the # loader for all the targets. for target in group.targets: if target in loaders: raise ValueError( f"Target '{target} has multiple configured loaders'" ) loaders[target] = loader return loaders def _create_loader_for_group( self, format: str, group_name: str, group: QuantizationScheme ) -> WeightsLoader: """ Find and create a loader for the group with the given quantization scheme. """ # NOTE: we ignore group.output_activations because we don't support # output quantization yet. input_activations = group.input_activations weights = group.weights if ( format in { CompressionFormat.float_quantized.value, CompressionFormat.naive_quantized.value, } and weights is not None and weights.type == QuantizationType.FLOAT and weights.num_bits == 8 ): # FP W8A8 or W8A16. return W8ANFpLoader(input_activations=input_activations, weights=weights) elif ( format == CompressionFormat.pack_quantized.value and weights is not None and weights.type == QuantizationType.INT and weights.num_bits in (4, 8) ): # INT W4A16 or W8A16 (GPTQ/AWQ-like). return WNA16IntLoader(weights) elif ( format == CompressionFormat.marlin_24.value and weights is not None and weights.type == QuantizationType.INT and weights.num_bits in (4, 8) ): return WNA16Int24Loader(weights) elif ( format in { CompressionFormat.int_quantized.value, CompressionFormat.naive_quantized.value, } and weights is not None and weights.type == QuantizationType.INT and weights.num_bits == 8 ): return W8A8IntLoader(input_args=input_activations, weight_args=weights) else: raise ValueError( f"Group '{group_name}' has unsupported compressed-tensors configurtion" ) def _lookup_loader(self, prefix: str) -> WeightsLoader: """ Look up the loader to use for a given parameter name (prefix). """ if len(find_name_or_class_matches(prefix, _EMPTY_LINEAR, self.ignore)) > 0: return DefaultWeightsLoader(UnquantizedWeight) # We currently only handle linear layers, so unconditionally pass # a `Linear` instance. targets = find_name_or_class_matches(prefix, _EMPTY_LINEAR, self.loaders.keys()) if len(targets) == 0: raise ValueError( f"Cannot find compressed-tensors target for prefix: {prefix}" ) return self.loaders[targets[0]]
text-generation-inference/server/text_generation_server/layers/compressed_tensors/loader.py/0
{ "file_path": "text-generation-inference/server/text_generation_server/layers/compressed_tensors/loader.py", "repo_id": "text-generation-inference", "token_count": 3149 }
320
# coding=utf-8 # Copyright 2025 The HuggingFace Inc. 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. from typing import List, Union from transformers.image_utils import ImageInput, is_valid_image, is_pil_image def is_valid_list_of_images(images: List): return images and all(is_valid_image(image) for image in images) def make_nested_list_of_images( images: Union[List[ImageInput], ImageInput], ) -> ImageInput: """ Ensure that the output is a nested list of images. Args: images (`Union[List[ImageInput], ImageInput]`): The input image. Returns: list: A list of list of images or a list of 4d array of images. """ # If it's a list of batches, it's already in the right format if ( isinstance(images, (list, tuple)) and all(isinstance(images_i, (list, tuple)) for images_i in images) and all(is_valid_list_of_images(images_i) for images_i in images) ): return images # If it's a list of images, it's a single batch, so convert it to a list of lists if isinstance(images, (list, tuple)) and is_valid_list_of_images(images): if is_pil_image(images[0]) or images[0].ndim == 3: return [images] if images[0].ndim == 4: return [list(image) for image in images] # If it's a single image, convert it to a list of lists if is_valid_image(images): if is_pil_image(images) or images.ndim == 3: return [[images]] if images.ndim == 4: return [list(images)] raise ValueError( "Invalid input type. Must be a single image, a list of images, or a list of batches of images." )
text-generation-inference/server/text_generation_server/models/custom_modeling/gemma3/utils.py/0
{ "file_path": "text-generation-inference/server/text_generation_server/models/custom_modeling/gemma3/utils.py", "repo_id": "text-generation-inference", "token_count": 792 }
321
import torch from abc import ABC, abstractmethod from dataclasses import dataclass from typing import List, Optional from transformers import PreTrainedTokenizerBase from text_generation_server.pb import generate_pb2 from text_generation_server.pb.generate_pb2 import FinishReason class Batch(ABC): @abstractmethod def to_pb(self) -> generate_pb2.CachedBatch: raise NotImplementedError @classmethod @abstractmethod def from_pb( cls, pb: generate_pb2.Batch, tokenizer: PreTrainedTokenizerBase, dtype: torch.dtype, device: torch.device, ) -> "Batch": raise NotImplementedError @abstractmethod def filter(self, request_ids: List[int]) -> "Batch": raise NotImplementedError @classmethod @abstractmethod def concatenate(cls, batches: List["Batch"]) -> "Batch": raise NotImplementedError @abstractmethod def __len__(self): raise NotImplementedError @dataclass class GeneratedText: text: str generated_tokens: int finish_reason: FinishReason seed: Optional[int] def to_pb(self) -> generate_pb2.GeneratedText: return generate_pb2.GeneratedText( text=self.text, generated_tokens=self.generated_tokens, finish_reason=self.finish_reason, seed=self.seed, ) @dataclass class Tokens: token_ids: List[int] logprobs: List[float] texts: List[str] is_special: List[bool] def to_pb(self) -> generate_pb2.Tokens: return generate_pb2.Tokens( ids=self.token_ids, logprobs=self.logprobs, texts=self.texts, is_special=self.is_special, ) def __len__(self): return len(self.token_ids) def __add__(self, other: "Tokens") -> "Tokens": return Tokens( self.token_ids + other.token_ids, self.logprobs + other.logprobs, self.texts + other.texts, self.is_special + other.is_special, ) @dataclass class Generation: request_id: int prefill_tokens: Optional[Tokens] tokens: Tokens generated_text: Optional[GeneratedText] # Optional for now, since it's not yet supported for every model. top_tokens: Optional[List[Tokens]] def to_pb(self) -> generate_pb2.Generation: return generate_pb2.Generation( request_id=self.request_id, prefill_tokens=( self.prefill_tokens.to_pb() if self.prefill_tokens is not None else None ), tokens=self.tokens.to_pb(), generated_text=( self.generated_text.to_pb() if self.generated_text is not None else None ), top_tokens=( [top_tokens.to_pb() for top_tokens in self.top_tokens] if self.top_tokens is not None else None ), )
text-generation-inference/server/text_generation_server/models/types.py/0
{ "file_path": "text-generation-inference/server/text_generation_server/models/types.py", "repo_id": "text-generation-inference", "token_count": 1353 }
322
# coding=utf-8 # From: https://github.com/huggingface/peft/pull/1364 # Copyright 2024-present the HuggingFace Inc. team. # Modifications by Predibase, Inc. # # 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. from typing import Literal import torch def magnitude_based_pruning(tensor: torch.Tensor, density: float) -> torch.Tensor: """ Prune the smallest values of the task tensors and retain the top-k values based on the specified fraction `density`. Args: tensor (`torch.Tensor`):The tensor to prune. density (`float`):The fraction of values to preserve. Should be in [0,1]. """ mask = torch.zeros_like(tensor).reshape(-1) k = int(density * tensor.reshape(-1).shape[0]) top_k = torch.topk(tensor.abs().reshape(-1), k=k, largest=True) mask[top_k[1]] = 1 return tensor * mask.reshape(tensor.shape) def random_pruning(tensor: torch.Tensor, density: float, rescale: bool) -> torch.Tensor: """ Prune the smallest values of the task tensors and retain the top-k values based on the specified fraction `density`. Args: tensor (`torch.Tensor`):The tensor to prune. density (`float`):The fraction of values to preserve. Should be in [0,1]. rescale (`bool`):Whether to rescale the result to preserve the expected value of the original tensor. """ mask = torch.bernoulli(torch.full_like(input=tensor, fill_value=density)) pruned_tensor = tensor * mask if rescale: torch.div(input=pruned_tensor, other=density) return pruned_tensor def prune( tensor: torch.Tensor, density: float, method: Literal["magnitude", "random"], rescale: bool = False, ) -> torch.Tensor: """ Prune the values of task tensors based on the `method`. Args: tensor (`torch.Tensor`):The tensor to prune. density (`float`):The fraction of values to preserve. Should be in [0,1]. method (`str`):The method to use to prune. Should be one of ["magnitude", "random"]. rescale (`bool`):Whether to rescale the result to preserve the expected value of the original tensor. """ if density >= 1: return tensor elif density < 0: raise ValueError("Density should be >= 0, got {density}") if method == "magnitude": return magnitude_based_pruning(tensor, density) elif method == "random": return random_pruning(tensor, density, rescale=rescale) else: raise ValueError(f"Unknown method {method}") def calculate_majority_sign_mask( tensor: torch.Tensor, method: Literal["total", "frequency"] = "total" ): """ Get the mask of the majority sign across the task tensors. Task tensors are stacked on dimension 0. Args: tensor (`torch.Tensor`):The tensor to get the mask from. method (`str`):The method to use to get the mask. Should be one of ["total", "frequency"]. """ sign = tensor.sign() if method == "total": sign_magnitude = (sign * tensor.abs()).sum(dim=0) elif method == "frequency": sign_magnitude = sign.sum(dim=0) else: raise RuntimeError(f'Unimplemented mask method "{method}"') majority_sign = torch.where(sign_magnitude >= 0, 1, -1) return sign == majority_sign def disjoint_merge(task_tensors, majority_sign_mask): mixed_task_tensors = (task_tensors * majority_sign_mask).sum(dim=0) num_params_preserved = majority_sign_mask.sum(dim=0) return mixed_task_tensors / torch.clamp(num_params_preserved, min=1.0)
text-generation-inference/server/text_generation_server/utils/merges/utils.py/0
{ "file_path": "text-generation-inference/server/text_generation_server/utils/merges/utils.py", "repo_id": "text-generation-inference", "token_count": 1422 }
323
[target.aarch64-unknown-linux-musl] linker = "aarch64-linux-musl-gcc" rustflags = ["-C", "target-feature=-crt-static"]
tokenizers/bindings/node/.cargo/config.toml/0
{ "file_path": "tokenizers/bindings/node/.cargo/config.toml", "repo_id": "tokenizers", "token_count": 50 }
324
/* tslint:disable */ /* eslint-disable */ /* auto-generated by NAPI-RS */ export function bpeDecoder(suffix?: string | undefined | null): Decoder export function byteFallbackDecoder(): Decoder export function ctcDecoder( padToken?: string = '<pad>', wordDelimiterToken?: string | undefined | null, cleanup?: boolean | undefined | null, ): Decoder export function fuseDecoder(): Decoder export function metaspaceDecoder( replacement?: string = '▁', prependScheme?: prepend_scheme = 'always', split?: split = true, ): Decoder export function replaceDecoder(pattern: string, content: string): Decoder export function sequenceDecoder(decoders: Array<Decoder>): Decoder export function stripDecoder(content: string, left: number, right: number): Decoder export function wordPieceDecoder(prefix?: string = '##', cleanup?: bool = true): Decoder export const enum TruncationDirection { Left = 'Left', Right = 'Right', } export const enum TruncationStrategy { LongestFirst = 'LongestFirst', OnlyFirst = 'OnlyFirst', OnlySecond = 'OnlySecond', } export interface BpeOptions { cacheCapacity?: number dropout?: number unkToken?: string continuingSubwordPrefix?: string endOfWordSuffix?: string fuseUnk?: boolean byteFallback?: boolean } export interface WordPieceOptions { unkToken?: string continuingSubwordPrefix?: string maxInputCharsPerWord?: number } export interface WordLevelOptions { unkToken?: string } export interface UnigramOptions { unkId?: number byteFallback?: boolean } export function prependNormalizer(prepend: string): Normalizer export function stripAccentsNormalizer(): Normalizer export interface BertNormalizerOptions { cleanText?: boolean handleChineseChars?: boolean stripAccents?: boolean lowercase?: boolean } /** * bert_normalizer(options?: { * cleanText?: bool = true, * handleChineseChars?: bool = true, * stripAccents?: bool = true, * lowercase?: bool = true * }) */ export function bertNormalizer(options?: BertNormalizerOptions | undefined | null): Normalizer export function nfdNormalizer(): Normalizer export function nfkdNormalizer(): Normalizer export function nfcNormalizer(): Normalizer export function nfkcNormalizer(): Normalizer export function stripNormalizer(left?: boolean | undefined | null, right?: boolean | undefined | null): Normalizer export function sequenceNormalizer(normalizers: Array<Normalizer>): Normalizer export function lowercase(): Normalizer export function replace(pattern: string, content: string): Normalizer export function nmt(): Normalizer export function precompiled(bytes: Array<number>): Normalizer export const enum JsSplitDelimiterBehavior { Removed = 'Removed', Isolated = 'Isolated', MergedWithPrevious = 'MergedWithPrevious', MergedWithNext = 'MergedWithNext', Contiguous = 'Contiguous', } /** byte_level(addPrefixSpace: bool = true, useRegex: bool = true) */ export function byteLevelPreTokenizer( addPrefixSpace?: boolean | undefined | null, useRegex?: boolean | undefined | null, ): PreTokenizer export function byteLevelAlphabet(): Array<string> export function whitespacePreTokenizer(): PreTokenizer export function whitespaceSplitPreTokenizer(): PreTokenizer export function bertPreTokenizer(): PreTokenizer export function metaspacePreTokenizer( replacement?: string = '▁', prependScheme?: prepend_scheme = 'always', split?: split = true, ): PreTokenizer export function splitPreTokenizer(pattern: string, behavior: string, invert?: boolean | undefined | null): PreTokenizer export function punctuationPreTokenizer(behavior?: string | undefined | null): PreTokenizer export function sequencePreTokenizer(preTokenizers: Array<PreTokenizer>): PreTokenizer export function charDelimiterSplit(delimiter: string): PreTokenizer export function digitsPreTokenizer(individualDigits?: boolean | undefined | null): PreTokenizer export function bertProcessing(sep: [string, number], cls: [string, number]): Processor export function robertaProcessing( sep: [string, number], cls: [string, number], trimOffsets?: boolean | undefined | null, addPrefixSpace?: boolean | undefined | null, ): Processor export function byteLevelProcessing(trimOffsets?: boolean | undefined | null): Processor export function templateProcessing( single: string, pair?: string | undefined | null, specialTokens?: Array<[string, number]> | undefined | null, ): Processor export function sequenceProcessing(processors: Array<Processor>): Processor export const enum PaddingDirection { Left = 0, Right = 1, } export interface PaddingOptions { maxLength?: number direction?: string | PaddingDirection padToMultipleOf?: number padId?: number padTypeId?: number padToken?: string } export interface EncodeOptions { isPretokenized?: boolean addSpecialTokens?: boolean } export interface TruncationOptions { maxLength?: number strategy?: TruncationStrategy direction?: string | TruncationDirection stride?: number } export interface AddedTokenOptions { singleWord?: boolean leftStrip?: boolean rightStrip?: boolean normalized?: boolean } export interface JsFromPretrainedParameters { revision?: string authToken?: string } export function slice(s: string, beginIndex?: number | undefined | null, endIndex?: number | undefined | null): string export function mergeEncodings(encodings: Array<Encoding>, growingOffsets?: boolean | undefined | null): Encoding /** Decoder */ export class Decoder { decode(tokens: Array<string>): string } export type JsEncoding = Encoding export class Encoding { constructor() getLength(): number getNSequences(): number getIds(): Array<number> getTypeIds(): Array<number> getAttentionMask(): Array<number> getSpecialTokensMask(): Array<number> getTokens(): Array<string> getOffsets(): Array<Array<number>> getWordIds(): Array<number | undefined | null> charToToken(pos: number, seqId?: number | undefined | null): number | null charToWord(pos: number, seqId?: number | undefined | null): number | null pad(length: number, options?: PaddingOptions | undefined | null): void truncate( length: number, stride?: number | undefined | null, direction?: string | TruncationDirection | undefined | null, ): void wordToTokens(word: number, seqId?: number | undefined | null): [number, number] | null | undefined wordToChars(word: number, seqId?: number | undefined | null): [number, number] | null | undefined tokenToChars(token: number): [number, [number, number]] | null | undefined tokenToWord(token: number): number | null getOverflowing(): Array<Encoding> getSequenceIds(): Array<number | undefined | null> tokenToSequence(token: number): number | null } export class Model {} export type Bpe = BPE export class BPE { static empty(): Model static init(vocab: Vocab, merges: Merges, options?: BpeOptions | undefined | null): Model static fromFile(vocab: string, merges: string, options?: BpeOptions | undefined | null): Promise<Model> } export class WordPiece { static init(vocab: Vocab, options?: WordPieceOptions | undefined | null): Model static empty(): WordPiece static fromFile(vocab: string, options?: WordPieceOptions | undefined | null): Promise<Model> } export class WordLevel { static init(vocab: Vocab, options?: WordLevelOptions | undefined | null): Model static empty(): WordLevel static fromFile(vocab: string, options?: WordLevelOptions | undefined | null): Promise<Model> } export class Unigram { static init(vocab: Array<[string, number]>, options?: UnigramOptions | undefined | null): Model static empty(): Model } /** Normalizer */ export class Normalizer { normalizeString(sequence: string): string } /** PreTokenizers */ export class PreTokenizer { preTokenizeString(sequence: string): [string, [number, number]][] } export class Processor {} export class AddedToken { constructor(token: string, isSpecial: boolean, options?: AddedTokenOptions | undefined | null) getContent(): string } export class Tokenizer { constructor(model: Model) setPreTokenizer(preTokenizer: PreTokenizer): void setDecoder(decoder: Decoder): void setModel(model: Model): void setPostProcessor(postProcessor: Processor): void setNormalizer(normalizer: Normalizer): void save(path: string, pretty?: boolean | undefined | null): void addAddedTokens(tokens: Array<AddedToken>): number addTokens(tokens: Array<string>): number encode( sentence: InputSequence, pair?: InputSequence | null, encodeOptions?: EncodeOptions | undefined | null, ): Promise<JsEncoding> encodeBatch(sentences: EncodeInput[], encodeOptions?: EncodeOptions | undefined | null): Promise<JsEncoding[]> decode(ids: Array<number>, skipSpecialTokens: boolean): Promise<string> decodeBatch(ids: Array<Array<number>>, skipSpecialTokens: boolean): Promise<string[]> static fromString(s: string): Tokenizer static fromFile(file: string): Tokenizer addSpecialTokens(tokens: Array<string>): void setTruncation(maxLength: number, options?: TruncationOptions | undefined | null): void disableTruncation(): void setPadding(options?: PaddingOptions | undefined | null): void disablePadding(): void getDecoder(): Decoder | null getNormalizer(): Normalizer | null getPreTokenizer(): PreTokenizer | null getPostProcessor(): Processor | null getVocab(withAddedTokens?: boolean | undefined | null): Record<string, number> getVocabSize(withAddedTokens?: boolean | undefined | null): number idToToken(id: number): string | null tokenToId(token: string): number | null train(files: Array<string>): void runningTasks(): number postProcess( encoding: Encoding, pair?: Encoding | undefined | null, addSpecialTokens?: boolean | undefined | null, ): Encoding } export class Trainer {}
tokenizers/bindings/node/index.d.ts/0
{ "file_path": "tokenizers/bindings/node/index.d.ts", "repo_id": "tokenizers", "token_count": 2753 }
325
# `tokenizers-android-arm64` This is the **aarch64-linux-android** binary for `tokenizers`
tokenizers/bindings/node/npm/android-arm64/README.md/0
{ "file_path": "tokenizers/bindings/node/npm/android-arm64/README.md", "repo_id": "tokenizers", "token_count": 31 }
326
# `tokenizers-linux-x64-musl` This is the **x86_64-unknown-linux-musl** binary for `tokenizers`
tokenizers/bindings/node/npm/linux-x64-musl/README.md/0
{ "file_path": "tokenizers/bindings/node/npm/linux-x64-musl/README.md", "repo_id": "tokenizers", "token_count": 38 }
327
use crate::arc_rwlock_serde; use napi::bindgen_prelude::*; use napi_derive::napi; use serde::{Deserialize, Serialize}; use std::sync::{Arc, RwLock}; use tk::pre_tokenizers::PreTokenizerWrapper; use tk::PreTokenizedString; use tk::SplitDelimiterBehavior; use tokenizers as tk; #[napi(string_enum)] pub enum JsSplitDelimiterBehavior { Removed, Isolated, MergedWithPrevious, MergedWithNext, Contiguous, } impl TryFrom<String> for JsSplitDelimiterBehavior { type Error = Error; fn try_from(value: String) -> Result<Self> { match &value[..] { "removed" => Ok(JsSplitDelimiterBehavior::Removed), "isolated" => Ok(JsSplitDelimiterBehavior::Isolated), "mergedWithPrevious" => Ok(JsSplitDelimiterBehavior::MergedWithPrevious), "mergedWithNext" => Ok(JsSplitDelimiterBehavior::MergedWithNext), "contiguous" => Ok(JsSplitDelimiterBehavior::Contiguous), _ => Err(Error::from_reason( "Wrong value for SplitDelimiterBehavior, expected one of: \ `removed, isolated, mergedWithPrevious, mergedWithNext, contiguous`" .to_string(), )), } } } impl From<JsSplitDelimiterBehavior> for SplitDelimiterBehavior { fn from(value: JsSplitDelimiterBehavior) -> Self { match value { JsSplitDelimiterBehavior::Removed => SplitDelimiterBehavior::Removed, JsSplitDelimiterBehavior::Isolated => SplitDelimiterBehavior::Isolated, JsSplitDelimiterBehavior::MergedWithPrevious => SplitDelimiterBehavior::MergedWithPrevious, JsSplitDelimiterBehavior::MergedWithNext => SplitDelimiterBehavior::MergedWithNext, JsSplitDelimiterBehavior::Contiguous => SplitDelimiterBehavior::Contiguous, } } } /// PreTokenizers #[derive(Clone, Debug, Serialize, Deserialize)] #[napi] pub struct PreTokenizer { #[serde(flatten, with = "arc_rwlock_serde")] pretok: Option<Arc<RwLock<PreTokenizerWrapper>>>, } impl tk::PreTokenizer for PreTokenizer { fn pre_tokenize(&self, pretokenized: &mut PreTokenizedString) -> tk::Result<()> { self .pretok .as_ref() .ok_or("Uninitialized PreTokenizer")? .read() .unwrap() .pre_tokenize(pretokenized)?; Ok(()) } } #[napi] impl PreTokenizer { #[napi(ts_return_type = "[string, [number, number]][]")] pub fn pre_tokenize_string(&self, sequence: String, env: Env) -> Result<Vec<Array>> { use tk::PreTokenizer; let mut pretokenized = PreTokenizedString::from(sequence); self .pre_tokenize(&mut pretokenized) .map_err(|e| Error::from_reason(format!("{e}")))?; pretokenized .get_splits(tk::OffsetReferential::Original, tk::OffsetType::Char) .into_iter() .map(|(s, (start, end), _)| -> Result<Array> { let mut arr = env.create_array(2)?; let mut offset = env.create_array(2)?; offset.set(0, env.create_uint32(start as u32)?)?; offset.set(1, env.create_uint32(end as u32)?)?; arr.set(0, env.create_string(s)?)?; arr.set(1, offset)?; Ok(arr) }) .collect::<Result<Vec<_>>>() } } /// byte_level(addPrefixSpace: bool = true, useRegex: bool = true) #[napi] pub fn byte_level_pre_tokenizer( add_prefix_space: Option<bool>, use_regex: Option<bool>, ) -> PreTokenizer { let mut byte_level = tk::pre_tokenizers::byte_level::ByteLevel::default(); if let Some(add_prefix_space) = add_prefix_space { byte_level = byte_level.add_prefix_space(add_prefix_space); } if let Some(use_regex) = use_regex { byte_level = byte_level.use_regex(use_regex); } PreTokenizer { pretok: Some(Arc::new(RwLock::new(byte_level.into()))), } } #[napi] pub fn byte_level_alphabet() -> Vec<String> { tk::pre_tokenizers::byte_level::ByteLevel::alphabet() .into_iter() .map(|c| c.to_string()) .collect::<Vec<_>>() } #[napi] pub fn whitespace_pre_tokenizer() -> PreTokenizer { PreTokenizer { pretok: Some(Arc::new(RwLock::new( tk::pre_tokenizers::whitespace::Whitespace.into(), ))), } } #[napi] pub fn whitespace_split_pre_tokenizer() -> PreTokenizer { PreTokenizer { pretok: Some(Arc::new(RwLock::new( tk::pre_tokenizers::whitespace::WhitespaceSplit.into(), ))), } } #[napi] pub fn bert_pre_tokenizer() -> PreTokenizer { PreTokenizer { pretok: Some(Arc::new(RwLock::new( tk::pre_tokenizers::bert::BertPreTokenizer.into(), ))), } } #[napi] pub fn metaspace_pre_tokenizer( #[napi(ts_arg_type = "string = '▁'")] replacement: Option<String>, #[napi(ts_arg_type = "prepend_scheme = 'always'")] prepend_scheme: Option<String>, #[napi(ts_arg_type = "split = true")] split: Option<bool>, ) -> Result<PreTokenizer> { use tk::pre_tokenizers::metaspace::PrependScheme; let split = split.unwrap_or(true); let replacement = replacement.unwrap_or("▁".to_string()); if replacement.chars().count() != 1 { return Err(Error::from_reason( "replacement is supposed to be a single char", )); } let replacement = replacement.chars().next().unwrap(); let prepend_scheme: PrependScheme = match prepend_scheme.unwrap_or(String::from("always")).as_str() { "always" => PrependScheme::Always, "first" => PrependScheme::First, "never" => PrependScheme::Never, _ => { return Err(Error::from_reason( "prepend_scheme is supposed to be either 'always', 'first' or 'never'", )); } }; Ok(PreTokenizer { pretok: Some(Arc::new(RwLock::new( tk::pre_tokenizers::metaspace::Metaspace::new(replacement, prepend_scheme, split).into(), ))), }) } #[napi] pub fn split_pre_tokenizer( pattern: String, behavior: String, invert: Option<bool>, ) -> Result<PreTokenizer> { let behavior: JsSplitDelimiterBehavior = behavior.try_into()?; let invert = invert.unwrap_or(false); Ok(PreTokenizer { pretok: Some(Arc::new(RwLock::new( tk::pre_tokenizers::split::Split::new(pattern, behavior.into(), invert) .map_err(|e| Error::from_reason(e.to_string()))? .into(), ))), }) } #[napi] pub fn punctuation_pre_tokenizer(behavior: Option<String>) -> Result<PreTokenizer> { let behavior = match behavior { Some(behavior) => behavior.try_into()?, None => JsSplitDelimiterBehavior::Isolated, }; Ok(PreTokenizer { pretok: Some(Arc::new(RwLock::new( tk::pre_tokenizers::punctuation::Punctuation::new(behavior.into()).into(), ))), }) } #[napi] pub fn sequence_pre_tokenizer(pre_tokenizers: Vec<&PreTokenizer>) -> PreTokenizer { let mut sequence: Vec<PreTokenizerWrapper> = Vec::with_capacity(pre_tokenizers.len()); pre_tokenizers.into_iter().for_each(|pre_tokenizer| { if let Some(pre_tokenizer) = &pre_tokenizer.pretok { sequence.push((**pre_tokenizer).read().unwrap().clone()) } }); PreTokenizer { pretok: Some(Arc::new(RwLock::new(PreTokenizerWrapper::Sequence( tk::pre_tokenizers::sequence::Sequence::new(sequence), )))), } } #[napi] pub fn char_delimiter_split(delimiter: String) -> Result<PreTokenizer> { if delimiter.chars().count() != 1 { return Err(Error::from_reason( "delimiter is supposed to be a single char", )); } let delimiter = delimiter.chars().next().unwrap(); Ok(PreTokenizer { pretok: Some(Arc::new(RwLock::new( tk::pre_tokenizers::delimiter::CharDelimiterSplit::new(delimiter).into(), ))), }) } #[napi] pub fn digits_pre_tokenizer(individual_digits: Option<bool>) -> PreTokenizer { let individual_digits = individual_digits.unwrap_or(false); PreTokenizer { pretok: Some(Arc::new(RwLock::new( tk::pre_tokenizers::digits::Digits::new(individual_digits).into(), ))), } }
tokenizers/bindings/node/src/pre_tokenizers.rs/0
{ "file_path": "tokenizers/bindings/node/src/pre_tokenizers.rs", "repo_id": "tokenizers", "token_count": 3151 }
328
.PHONY: style check-style test DATA_DIR = data dir_guard=@mkdir -p $(@D) check_dirs := examples py_src/tokenizers tests # Format source code automatically style: python stub.py ruff check $(check_dirs) --fix ruff format $(check_dirs) # Check the source code is formatted correctly check-style: python stub.py --check ruff check $(check_dirs) ruff format --check $(check_dirs) TESTS_RESOURCES = $(DATA_DIR)/small.txt $(DATA_DIR)/roberta.json # Launch the test suite test: $(TESTS_RESOURCES) pip install pytest requests setuptools_rust numpy pyarrow datasets python -m pytest -s -v tests cargo test --no-default-features $(DATA_DIR)/big.txt : $(dir_guard) wget https://norvig.com/big.txt -O $@ $(DATA_DIR)/small.txt : $(DATA_DIR)/big.txt head -100 $(DATA_DIR)/big.txt > $@ $(DATA_DIR)/roberta.json : $(dir_guard) wget https://huggingface.co/roberta-large/raw/main/tokenizer.json -O $@
tokenizers/bindings/python/Makefile/0
{ "file_path": "tokenizers/bindings/python/Makefile", "repo_id": "tokenizers", "token_count": 349 }
329
from typing import Dict, Iterator, List, Optional, Union from tokenizers import AddedToken, Tokenizer, decoders, trainers from tokenizers.models import WordPiece from tokenizers.normalizers import BertNormalizer from tokenizers.pre_tokenizers import BertPreTokenizer from tokenizers.processors import BertProcessing from .base_tokenizer import BaseTokenizer class BertWordPieceTokenizer(BaseTokenizer): """Bert WordPiece Tokenizer""" def __init__( self, vocab: Optional[Union[str, Dict[str, int]]] = None, unk_token: Union[str, AddedToken] = "[UNK]", sep_token: Union[str, AddedToken] = "[SEP]", cls_token: Union[str, AddedToken] = "[CLS]", pad_token: Union[str, AddedToken] = "[PAD]", mask_token: Union[str, AddedToken] = "[MASK]", clean_text: bool = True, handle_chinese_chars: bool = True, strip_accents: Optional[bool] = None, lowercase: bool = True, wordpieces_prefix: str = "##", ): if vocab is not None: tokenizer = Tokenizer(WordPiece(vocab, unk_token=str(unk_token))) else: tokenizer = Tokenizer(WordPiece(unk_token=str(unk_token))) # Let the tokenizer know about special tokens if they are part of the vocab if tokenizer.token_to_id(str(unk_token)) is not None: tokenizer.add_special_tokens([str(unk_token)]) if tokenizer.token_to_id(str(sep_token)) is not None: tokenizer.add_special_tokens([str(sep_token)]) if tokenizer.token_to_id(str(cls_token)) is not None: tokenizer.add_special_tokens([str(cls_token)]) if tokenizer.token_to_id(str(pad_token)) is not None: tokenizer.add_special_tokens([str(pad_token)]) if tokenizer.token_to_id(str(mask_token)) is not None: tokenizer.add_special_tokens([str(mask_token)]) tokenizer.normalizer = BertNormalizer( clean_text=clean_text, handle_chinese_chars=handle_chinese_chars, strip_accents=strip_accents, lowercase=lowercase, ) tokenizer.pre_tokenizer = BertPreTokenizer() if vocab is not None: sep_token_id = tokenizer.token_to_id(str(sep_token)) if sep_token_id is None: raise TypeError("sep_token not found in the vocabulary") cls_token_id = tokenizer.token_to_id(str(cls_token)) if cls_token_id is None: raise TypeError("cls_token not found in the vocabulary") tokenizer.post_processor = BertProcessing((str(sep_token), sep_token_id), (str(cls_token), cls_token_id)) tokenizer.decoder = decoders.WordPiece(prefix=wordpieces_prefix) parameters = { "model": "BertWordPiece", "unk_token": unk_token, "sep_token": sep_token, "cls_token": cls_token, "pad_token": pad_token, "mask_token": mask_token, "clean_text": clean_text, "handle_chinese_chars": handle_chinese_chars, "strip_accents": strip_accents, "lowercase": lowercase, "wordpieces_prefix": wordpieces_prefix, } super().__init__(tokenizer, parameters) @staticmethod def from_file(vocab: str, **kwargs): vocab = WordPiece.read_file(vocab) return BertWordPieceTokenizer(vocab, **kwargs) def train( self, files: Union[str, List[str]], vocab_size: int = 30000, min_frequency: int = 2, limit_alphabet: int = 1000, initial_alphabet: List[str] = [], special_tokens: List[Union[str, AddedToken]] = [ "[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]", ], show_progress: bool = True, wordpieces_prefix: str = "##", ): """Train the model using the given files""" trainer = trainers.WordPieceTrainer( vocab_size=vocab_size, min_frequency=min_frequency, limit_alphabet=limit_alphabet, initial_alphabet=initial_alphabet, special_tokens=special_tokens, show_progress=show_progress, continuing_subword_prefix=wordpieces_prefix, ) if isinstance(files, str): files = [files] self._tokenizer.train(files, trainer=trainer) def train_from_iterator( self, iterator: Union[Iterator[str], Iterator[Iterator[str]]], vocab_size: int = 30000, min_frequency: int = 2, limit_alphabet: int = 1000, initial_alphabet: List[str] = [], special_tokens: List[Union[str, AddedToken]] = [ "[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]", ], show_progress: bool = True, wordpieces_prefix: str = "##", length: Optional[int] = None, ): """Train the model using the given iterator""" trainer = trainers.WordPieceTrainer( vocab_size=vocab_size, min_frequency=min_frequency, limit_alphabet=limit_alphabet, initial_alphabet=initial_alphabet, special_tokens=special_tokens, show_progress=show_progress, continuing_subword_prefix=wordpieces_prefix, ) self._tokenizer.train_from_iterator( iterator, trainer=trainer, length=length, )
tokenizers/bindings/python/py_src/tokenizers/implementations/bert_wordpiece.py/0
{ "file_path": "tokenizers/bindings/python/py_src/tokenizers/implementations/bert_wordpiece.py", "repo_id": "tokenizers", "token_count": 2637 }
330
# Generated content DO NOT EDIT from .. import trainers Trainer = trainers.Trainer BpeTrainer = trainers.BpeTrainer UnigramTrainer = trainers.UnigramTrainer WordLevelTrainer = trainers.WordLevelTrainer WordPieceTrainer = trainers.WordPieceTrainer
tokenizers/bindings/python/py_src/tokenizers/trainers/__init__.py/0
{ "file_path": "tokenizers/bindings/python/py_src/tokenizers/trainers/__init__.py", "repo_id": "tokenizers", "token_count": 74 }
331
use pyo3::prelude::*; use tk::Token; #[pyclass(module = "tokenizers", name = "Token")] #[derive(Clone)] pub struct PyToken { token: Token, } impl From<Token> for PyToken { fn from(token: Token) -> Self { Self { token } } } impl From<PyToken> for Token { fn from(token: PyToken) -> Self { token.token } } #[pymethods] impl PyToken { #[new] #[pyo3(text_signature = None)] fn new(id: u32, value: String, offsets: (usize, usize)) -> PyToken { Token::new(id, value, offsets).into() } #[getter] fn get_id(&self) -> u32 { self.token.id } #[getter] fn get_value(&self) -> &str { &self.token.value } #[getter] fn get_offsets(&self) -> (usize, usize) { self.token.offsets } fn as_tuple(&self) -> (u32, &str, (usize, usize)) { (self.token.id, &self.token.value, self.token.offsets) } }
tokenizers/bindings/python/src/token.rs/0
{ "file_path": "tokenizers/bindings/python/src/token.rs", "repo_id": "tokenizers", "token_count": 439 }
332
import pickle import pytest from tokenizers import NormalizedString from tokenizers.normalizers import ( BertNormalizer, Lowercase, Normalizer, Precompiled, Sequence, Strip, Prepend, Replace, ) class TestBertNormalizer: def test_instantiate(self): assert isinstance(BertNormalizer(), Normalizer) assert isinstance(BertNormalizer(), BertNormalizer) assert isinstance(pickle.loads(pickle.dumps(BertNormalizer())), BertNormalizer) def test_strip_accents(self): normalizer = BertNormalizer(strip_accents=True, lowercase=False, handle_chinese_chars=False, clean_text=False) output = normalizer.normalize_str("Héllò") assert output == "Hello" def test_handle_chinese_chars(self): normalizer = BertNormalizer(strip_accents=False, lowercase=False, handle_chinese_chars=True, clean_text=False) output = normalizer.normalize_str("你好") assert output == " 你 好 " def test_clean_text(self): normalizer = BertNormalizer(strip_accents=False, lowercase=False, handle_chinese_chars=False, clean_text=True) output = normalizer.normalize_str("\ufeffHello") assert output == "Hello" def test_lowercase(self): normalizer = BertNormalizer(strip_accents=False, lowercase=True, handle_chinese_chars=False, clean_text=False) output = normalizer.normalize_str("Héllò") assert output == "héllò" def test_can_modify(self): normalizer = BertNormalizer(clean_text=True, handle_chinese_chars=True, strip_accents=True, lowercase=True) assert normalizer.clean_text == True assert normalizer.handle_chinese_chars == True assert normalizer.strip_accents == True assert normalizer.lowercase == True # Modify these normalizer.clean_text = False assert normalizer.clean_text == False normalizer.handle_chinese_chars = False assert normalizer.handle_chinese_chars == False normalizer.strip_accents = None assert normalizer.strip_accents == None normalizer.lowercase = False assert normalizer.lowercase == False class TestSequence: def test_instantiate(self): assert isinstance(Sequence([]), Normalizer) assert isinstance(Sequence([]), Sequence) assert isinstance(pickle.loads(pickle.dumps(Sequence([]))), Sequence) def test_can_make_sequences(self): normalizer = Sequence([Lowercase(), Strip()]) output = normalizer.normalize_str(" HELLO ") assert output == "hello" def test_set_item(self): normalizers = Sequence( [ BertNormalizer(True, True), Prepend(prepend="test"), ] ) assert normalizers[0].__class__ == BertNormalizer assert normalizers[1].__class__ == Prepend normalizers[1] = Strip() assert normalizers[1].__class__ == Strip with pytest.raises(IndexError): print(normalizers[2]) def test_item_getters_and_setters(self): normalizers = Sequence( [ BertNormalizer(clean_text=True, handle_chinese_chars=True, strip_accents=True, lowercase=True), Strip(left=True, right=True), Prepend(prepend="_"), Replace(pattern="something", content="else"), ] ) assert normalizers[0].__class__ == BertNormalizer normalizers[0].clean_text = False normalizers[0].handle_chinese_chars = False normalizers[0].strip_accents = False normalizers[0].lowercase = False assert not normalizers[0].clean_text assert not normalizers[0].handle_chinese_chars assert not normalizers[0].strip_accents assert not normalizers[0].lowercase assert normalizers[1].__class__ == Strip normalizers[1].left = False normalizers[1].right = False assert not normalizers[1].left assert not normalizers[1].right assert normalizers[2].__class__ == Prepend normalizers[2].prepend = " " assert normalizers[2].prepend == " " assert normalizers[3].__class__ == Replace with pytest.raises(Exception): normalizers[3].pattern = "test" with pytest.raises(Exception): print(normalizers[3].pattern) normalizers[3].content = "test" assert normalizers[3].content == "test" class TestLowercase: def test_instantiate(self): assert isinstance(Lowercase(), Normalizer) assert isinstance(Lowercase(), Lowercase) assert isinstance(pickle.loads(pickle.dumps(Lowercase())), Lowercase) def test_lowercase(self): normalizer = Lowercase() output = normalizer.normalize_str("HELLO") assert output == "hello" class TestStrip: def test_instantiate(self): assert isinstance(Strip(), Normalizer) assert isinstance(Strip(), Strip) assert isinstance(pickle.loads(pickle.dumps(Strip())), Strip) def test_left_strip(self): normalizer = Strip(left=True, right=False) output = normalizer.normalize_str(" hello ") assert output == "hello " def test_right_strip(self): normalizer = Strip(left=False, right=True) output = normalizer.normalize_str(" hello ") assert output == " hello" def test_full_strip(self): normalizer = Strip(left=True, right=True) output = normalizer.normalize_str(" hello ") assert output == "hello" def test_can_modify(self): normalizer = Strip(left=True, right=True) assert normalizer.left == True assert normalizer.right == True # Modify these normalizer.left = False assert normalizer.left == False normalizer.right = False assert normalizer.right == False class TestPrepend: def test_instantiate(self): assert isinstance(Prepend("▁"), Normalizer) assert isinstance(Prepend("▁"), Prepend) assert isinstance(pickle.loads(pickle.dumps(Prepend("▁"))), Prepend) def test_prepend(self): normalizer = Prepend(prepend="▁") output = normalizer.normalize_str("hello") assert output == "▁hello" def test_can_modify(self): normalizer = Prepend("▁") assert normalizer.prepend == "▁" # Modify these normalizer.prepend = "-" assert normalizer.prepend == "-" class TestCustomNormalizer: class BadCustomNormalizer: def normalize(self, normalized, wrong): pass class GoodCustomNormalizer: def normalize(self, normalized): self.kept_normalized = normalized normalized.replace("there", "you") def use_after_normalize(self): self.kept_normalized.replace("something", "else") def test_instantiate(self): bad = Normalizer.custom(TestCustomNormalizer.BadCustomNormalizer()) good_custom = TestCustomNormalizer.GoodCustomNormalizer() good = Normalizer.custom(good_custom) assert isinstance(bad, Normalizer) assert isinstance(good, Normalizer) with pytest.raises(Exception, match="TypeError:.*normalize()"): bad.normalize_str("Hey there!") assert good.normalize_str("Hey there!") == "Hey you!" with pytest.raises(Exception, match="Cannot use a NormalizedStringRefMut outside `normalize`"): good_custom.use_after_normalize() def test_normalizer_interface(self): normalizer = Normalizer.custom(TestCustomNormalizer.GoodCustomNormalizer()) normalized = NormalizedString("Hey there!") normalizer.normalize(normalized) assert repr(normalized) == 'NormalizedString(original="Hey there!", normalized="Hey you!")' assert str(normalized) == "Hey you!"
tokenizers/bindings/python/tests/bindings/test_normalizers.py/0
{ "file_path": "tokenizers/bindings/python/tests/bindings/test_normalizers.py", "repo_id": "tokenizers", "token_count": 3243 }
333
import multiprocessing as mp import os import pytest import requests DATA_PATH = os.path.join("tests", "data") def download(url, with_filename=None): filename = with_filename if with_filename is not None else url.rsplit("/")[-1] filepath = os.path.join(DATA_PATH, filename) if not os.path.exists(filepath): with open(filepath, "wb") as f: response = requests.get(url, stream=True) response.raise_for_status() for chunk in response.iter_content(1024): f.write(chunk) return filepath @pytest.fixture(scope="session") def data_dir(): assert os.getcwd().endswith("python") exist = os.path.exists(DATA_PATH) and os.path.isdir(DATA_PATH) if not exist: os.mkdir(DATA_PATH) @pytest.fixture(scope="session") def roberta_files(data_dir): return { "vocab": download("https://s3.amazonaws.com/models.huggingface.co/bert/roberta-base-vocab.json"), "merges": download("https://s3.amazonaws.com/models.huggingface.co/bert/roberta-base-merges.txt"), } @pytest.fixture(scope="session") def bert_files(data_dir): return { "vocab": download("https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt"), } @pytest.fixture(scope="session") def openai_files(data_dir): return { "vocab": download("https://s3.amazonaws.com/models.huggingface.co/bert/openai-gpt-vocab.json"), "merges": download("https://s3.amazonaws.com/models.huggingface.co/bert/openai-gpt-merges.txt"), } @pytest.fixture(scope="session") def train_files(data_dir): big = download("https://norvig.com/big.txt") small = os.path.join(DATA_PATH, "small.txt") with open(small, "w") as f: with open(big, "r") as g: for i, line in enumerate(g): f.write(line) if i > 100: break return { "small": small, "big": big, } @pytest.fixture(scope="session") def albert_base(data_dir): return download("https://s3.amazonaws.com/models.huggingface.co/bert/albert-base-v1-tokenizer.json") @pytest.fixture(scope="session") def doc_wiki_tokenizer(data_dir): return download( "https://s3.amazonaws.com/models.huggingface.co/bert/anthony/doc-quicktour/tokenizer.json", "tokenizer-wiki.json", ) @pytest.fixture(scope="session") def doc_pipeline_bert_tokenizer(data_dir): return download( "https://s3.amazonaws.com/models.huggingface.co/bert/anthony/doc-pipeline/tokenizer.json", "bert-wiki.json", ) # On MacOS Python 3.8+ the default was modified to `spawn`, we need `fork` in tests. mp.set_start_method("fork") def multiprocessing_with_parallelism(tokenizer, enabled: bool): """ This helper can be used to test that disabling parallelism avoids dead locks when the same tokenizer is used after forking. """ # It's essential to this test that we call 'encode' or 'encode_batch' # before the fork. This causes the main process to "lock" some resources # provided by the Rust "rayon" crate that are needed for parallel processing. tokenizer.encode("Hi") tokenizer.encode_batch(["hi", "there"]) def encode(tokenizer): tokenizer.encode("Hi") tokenizer.encode_batch(["hi", "there"]) # Make sure this environment variable is set before the fork happens os.environ["TOKENIZERS_PARALLELISM"] = str(enabled) p = mp.Process(target=encode, args=(tokenizer,)) p.start() p.join(timeout=1) # At this point the process should have successfully exited, depending on whether parallelism # was activated or not. So we check the status and kill it if needed alive = p.is_alive() if alive: p.terminate() assert (alive and mp.get_start_method() == "fork") == enabled
tokenizers/bindings/python/tests/utils.py/0
{ "file_path": "tokenizers/bindings/python/tests/utils.py", "repo_id": "tokenizers", "token_count": 1569 }
334
Documentation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The node API has not been documented yet.
tokenizers/docs/source/api/node.inc/0
{ "file_path": "tokenizers/docs/source/api/node.inc", "repo_id": "tokenizers", "token_count": 22 }
335
[package] authors = ["Anthony MOI <m.anthony.moi@gmail.com>", "Nicolas Patry <patry.nicolas@protonmail.com>"] edition = "2018" name = "tokenizers" version = "0.21.4-dev.0" homepage = "https://github.com/huggingface/tokenizers" repository = "https://github.com/huggingface/tokenizers" documentation = "https://docs.rs/tokenizers/" license = "Apache-2.0" keywords = ["tokenizer", "NLP", "huggingface", "BPE", "WordPiece"] readme = "./README.md" description = """ Provides an implementation of today's most used tokenizers, with a focus on performances and versatility. """ exclude = [ "rust-toolchain", "target/*", "Cargo.lock", "benches/*.txt", "benches/*.json", "data/*" ] [lib] name = "tokenizers" path = "src/lib.rs" bench = false [[bench]] name = "bpe_benchmark" harness = false [[bench]] name = "bert_benchmark" harness = false [[bench]] name = "layout_benchmark" harness = false [[bench]] name = "unigram_benchmark" harness = false [[bench]] name = "llama3_benchmark" harness = false [dependencies] rand = "0.9" onig = { version = "6.5.1", default-features = false, optional = true } regex = "1.10" regex-syntax = "0.8" rayon = "1.10" rayon-cond = "0.4" serde = { version = "1.0", features = [ "derive" ] } serde_json = "1.0" unicode-normalization-alignments = "0.1" unicode_categories = "0.1" unicode-segmentation = "1.11" indicatif = {version = "0.17", optional = true} itertools = "0.14" log = "0.4" derive_builder = "0.20" spm_precompiled = "0.1.3" hf-hub = { version = "0.4.1", features = ["ureq"], default-features = false, optional = true } aho-corasick = "1.1" paste = "1.0.14" macro_rules_attribute = "0.2.0" thiserror = "2" fancy-regex = { version = "0.14", optional = true} getrandom = { version = "0.3" } esaxx-rs = { version = "0.1.10", default-features = false, features=[]} monostate = "0.1.12" ahash = { version = "0.8.11", features = ["serde"] } dary_heap = { version = "0.3.6", features = ["serde"] } compact_str = { version = "0.9", features = ["serde"] } [features] default = ["progressbar", "onig", "esaxx_fast"] esaxx_fast = ["esaxx-rs/cpp"] progressbar = ["indicatif"] http = ["hf-hub"] unstable_wasm = ["fancy-regex", "getrandom/wasm_js"] rustls-tls = ["hf-hub?/rustls-tls"] [dev-dependencies] criterion = "0.6" tempfile = "3.10" assert_approx_eq = "1.1" tracing = "0.1" tracing-subscriber = "0.3.18" [profile.release] lto = "fat" [[example]] name = "encode_batch" required-features = ["http"]
tokenizers/tokenizers/Cargo.toml/0
{ "file_path": "tokenizers/tokenizers/Cargo.toml", "repo_id": "tokenizers", "token_count": 993 }
336
mod utils; use tokenizers::models::bpe::{Vocab, BPE}; use tokenizers::Tokenizer; use wasm_bindgen::prelude::*; // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global // allocator. #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; #[wasm_bindgen] pub fn tokenize(string: &str) -> Vec<u32> { let vocab: Vocab = vec![ ("a".to_string(), 0), ("##b".to_string(), 1), ("##c".to_string(), 2), ("ab".to_string(), 3), ("abc".to_string(), 4), ] .into_iter() .collect(); let merges = vec![ ("a".to_string(), "##b".to_string()), ("ab".to_string(), "##c".to_string()), ]; let bpe = BPE::builder() .vocab_and_merges(vocab, merges) .unk_token("[UNK]".to_string()) .continuing_subword_prefix("##".to_string()) .build() .unwrap(); let tokenizer = Tokenizer::new(bpe); tokenizer .encode(string, false) .unwrap() .get_ids() .into_iter() .cloned() .collect() }
tokenizers/tokenizers/examples/unstable_wasm/src/lib.rs/0
{ "file_path": "tokenizers/tokenizers/examples/unstable_wasm/src/lib.rs", "repo_id": "tokenizers", "token_count": 543 }
337
use crate::tokenizer::{Decoder, Result}; use serde::{Deserialize, Serialize}; #[derive(Deserialize, Clone, Debug, Serialize)] /// Allows decoding Original BPE by joining all the tokens and then replacing /// the suffix used to identify end-of-words by whitespaces #[serde(tag = "type")] #[non_exhaustive] pub struct BPEDecoder { pub suffix: String, } impl BPEDecoder { pub fn new(suffix: String) -> Self { Self { suffix } } } impl Default for BPEDecoder { fn default() -> Self { Self::new("</w>".into()) } } impl Decoder for BPEDecoder { fn decode_chain(&self, tokens: Vec<String>) -> Result<Vec<String>> { let n = tokens.len() - 1; Ok(tokens .into_iter() .enumerate() .map(|(i, token)| { let replacement = if i == n { "" } else { " " }; token.replace(&self.suffix, replacement) }) .collect()) } }
tokenizers/tokenizers/src/decoders/bpe.rs/0
{ "file_path": "tokenizers/tokenizers/src/decoders/bpe.rs", "repo_id": "tokenizers", "token_count": 419 }
338
//! [Unigram](https://arxiv.org/abs/1804.10959) model. mod lattice; mod model; mod serialization; mod trainer; mod trie; pub use lattice::*; pub use model::*; pub use trainer::*;
tokenizers/tokenizers/src/models/unigram/mod.rs/0
{ "file_path": "tokenizers/tokenizers/src/models/unigram/mod.rs", "repo_id": "tokenizers", "token_count": 72 }
339
use crate::tokenizer::pattern::Pattern; use crate::tokenizer::Decoder; use crate::tokenizer::{NormalizedString, Normalizer, Result}; use crate::utils::SysRegex; use serde::{Deserialize, Serialize}; /// Represents the different patterns that `Replace` can use #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq)] pub enum ReplacePattern { String(String), Regex(String), } impl From<String> for ReplacePattern { fn from(v: String) -> Self { Self::String(v) } } impl From<&str> for ReplacePattern { fn from(v: &str) -> Self { Self::String(v.to_owned()) } } /// We use this custom deserializer to provide the value for `regex` for `Replace` #[doc(hidden)] #[derive(Deserialize)] #[serde(tag = "type")] struct ReplaceDeserializer { pattern: ReplacePattern, content: String, } impl std::convert::TryFrom<ReplaceDeserializer> for Replace { type Error = Box<dyn std::error::Error + Send + Sync>; fn try_from(v: ReplaceDeserializer) -> Result<Self> { Self::new(v.pattern, v.content) } } /// This normalizer will take a `pattern` (for now only a String) /// and replace every occurrence with `content`. #[derive(Debug, Serialize, Deserialize)] #[serde(tag = "type", try_from = "ReplaceDeserializer")] pub struct Replace { pattern: ReplacePattern, pub content: String, #[serde(skip)] regex: SysRegex, } impl Clone for Replace { fn clone(&self) -> Self { Self::new(self.pattern.clone(), &self.content).unwrap() } } impl PartialEq for Replace { fn eq(&self, other: &Self) -> bool { self.pattern == other.pattern && self.content == other.content } } impl Replace { pub fn new<I: Into<ReplacePattern>, C: Into<String>>(pattern: I, content: C) -> Result<Self> { let pattern: ReplacePattern = pattern.into(); let regex = match &pattern { ReplacePattern::String(s) => SysRegex::new(&regex::escape(s))?, ReplacePattern::Regex(r) => SysRegex::new(r)?, }; Ok(Self { pattern, content: content.into(), regex, }) } } impl Normalizer for Replace { fn normalize(&self, normalized: &mut NormalizedString) -> Result<()> { normalized.replace(&self.regex, &self.content) } } impl Decoder for Replace { fn decode_chain(&self, tokens: Vec<String>) -> Result<Vec<String>> { tokens .into_iter() .map(|token| -> Result<String> { let mut new_token = "".to_string(); for ((start, stop), is_match) in (&self.regex).find_matches(&token)? { if is_match { new_token.push_str(&self.content); } else { new_token.push_str(&token[start..stop]); } } Ok(new_token) }) .collect() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_replace() { let original = "This is a ''test''"; let normalized = "This is a \"test\""; let mut n = NormalizedString::from(original); Replace::new("''", "\"").unwrap().normalize(&mut n).unwrap(); assert_eq!(&n.get(), &normalized); } #[test] fn test_replace_regex() { let original = "This is a test"; let normalized = "This is a test"; let mut n = NormalizedString::from(original); Replace::new(ReplacePattern::Regex(r"\s+".into()), ' ') .unwrap() .normalize(&mut n) .unwrap(); assert_eq!(&n.get(), &normalized); } #[test] fn serialization() { let replace = Replace::new("Hello", "Hey").unwrap(); let replace_s = r#"{"type":"Replace","pattern":{"String":"Hello"},"content":"Hey"}"#; assert_eq!(serde_json::to_string(&replace).unwrap(), replace_s); assert_eq!(serde_json::from_str::<Replace>(replace_s).unwrap(), replace); let replace = Replace::new(ReplacePattern::Regex(r"\s+".into()), ' ').unwrap(); let replace_s = r#"{"type":"Replace","pattern":{"Regex":"\\s+"},"content":" "}"#; assert_eq!(serde_json::to_string(&replace).unwrap(), replace_s); assert_eq!(serde_json::from_str::<Replace>(replace_s).unwrap(), replace); } #[test] fn test_replace_decode() { let original = vec!["hello".to_string(), "_hello".to_string()]; let replace = Replace::new("_", " ").unwrap(); assert_eq!( replace.decode_chain(original).unwrap(), vec!["hello", " hello"] ); } }
tokenizers/tokenizers/src/normalizers/replace.rs/0
{ "file_path": "tokenizers/tokenizers/src/normalizers/replace.rs", "repo_id": "tokenizers", "token_count": 2049 }
340
// Generated by modified Perl script at https://github.com/google/sentencepiece/blob/master/data/gen_unicode_scripts_code.pl // Unicode scripts : https://gist.github.com/Narsil/07556f26dc84a6baeff4d499e68d3cd2 // Rust adaptation : https://gist.github.com/Narsil/1df9fbbf5296a8d4d62de55dcb2fe700 #[derive(PartialEq, Debug, Clone, Copy, Eq)] pub enum Script { Any, Adlam, Ahom, AnatolianHieroglyphs, Arabic, Armenian, Avestan, Balinese, Bamum, BassaVah, Batak, Bengali, Bhaiksuki, Bopomofo, Brahmi, Braille, Buginese, Buhid, CanadianAboriginal, Carian, CaucasianAlbanian, Chakma, Cham, Cherokee, Common, Coptic, Cuneiform, Cypriot, Cyrillic, Deseret, Devanagari, Duployan, EgyptianHieroglyphs, Elbasan, Ethiopic, Georgian, Glagolitic, Gothic, Grantha, Greek, Gujarati, Gurmukhi, Han, Hangul, Hanunoo, Hatran, Hebrew, Hiragana, ImperialAramaic, Inherited, InscriptionalPahlavi, InscriptionalParthian, Javanese, Kaithi, Kannada, Katakana, KayahLi, Kharoshthi, Khmer, Khojki, Khudawadi, Lao, Latin, Lepcha, Limbu, LinearA, LinearB, Lisu, Lycian, Lydian, Mahajani, Malayalam, Mandaic, Manichaean, Marchen, MeeteiMayek, MendeKikakui, MeroiticCursive, MeroiticHieroglyphs, Miao, Modi, Mongolian, Mro, Multani, Myanmar, Nabataean, NewTaiLue, Newa, Nko, Ogham, OlChiki, OldHungarian, OldItalic, OldNorthArabian, OldPermic, OldPersian, OldSouthArabian, OldTurkic, Oriya, Osage, Osmanya, PahawhHmong, Palmyrene, PauCinHau, PhagsPa, Phoenician, PsalterPahlavi, Rejang, Runic, Samaritan, Saurashtra, Sharada, Shavian, Siddham, SignWriting, Sinhala, SoraSompeng, Sundanese, SylotiNagri, Syriac, Tagalog, Tagbanwa, TaiLe, TaiTham, TaiViet, Takri, Tamil, Tangut, Telugu, Thaana, Thai, Tibetan, Tifinagh, Tirhuta, Ugaritic, Vai, WarangCiti, Yi, } pub fn get_script(c: char) -> Script { match c as u32 { 0x0000..=0x001F => Script::Common, 0x0020 => Script::Common, 0x0021..=0x0023 => Script::Common, 0x0024 => Script::Common, 0x0025..=0x0027 => Script::Common, 0x0028 => Script::Common, 0x0029 => Script::Common, 0x002A => Script::Common, 0x002B => Script::Common, 0x002C => Script::Common, 0x002D => Script::Common, 0x002E..=0x002F => Script::Common, 0x0030..=0x0039 => Script::Common, 0x003A..=0x003B => Script::Common, 0x003C..=0x003E => Script::Common, 0x003F..=0x0040 => Script::Common, 0x005B => Script::Common, 0x005C => Script::Common, 0x005D => Script::Common, 0x005E => Script::Common, 0x005F => Script::Common, 0x0060 => Script::Common, 0x007B => Script::Common, 0x007C => Script::Common, 0x007D => Script::Common, 0x007E => Script::Common, 0x007F..=0x009F => Script::Common, 0x00A0 => Script::Common, 0x00A1 => Script::Common, 0x00A2..=0x00A5 => Script::Common, 0x00A6 => Script::Common, 0x00A7 => Script::Common, 0x00A8 => Script::Common, 0x00A9 => Script::Common, 0x00AB => Script::Common, 0x00AC => Script::Common, 0x00AD => Script::Common, 0x00AE => Script::Common, 0x00AF => Script::Common, 0x00B0 => Script::Common, 0x00B1 => Script::Common, 0x00B2..=0x00B3 => Script::Common, 0x00B4 => Script::Common, 0x00B5 => Script::Common, 0x00B6..=0x00B7 => Script::Common, 0x00B8 => Script::Common, 0x00B9 => Script::Common, 0x00BB => Script::Common, 0x00BC..=0x00BE => Script::Common, 0x00BF => Script::Common, 0x00D7 => Script::Common, 0x00F7 => Script::Common, 0x02B9..=0x02C1 => Script::Common, 0x02C2..=0x02C5 => Script::Common, 0x02C6..=0x02D1 => Script::Common, 0x02D2..=0x02DF => Script::Common, 0x02E5..=0x02E9 => Script::Common, 0x02EC => Script::Common, 0x02ED => Script::Common, 0x02EE => Script::Common, 0x02EF..=0x02FF => Script::Common, 0x0374 => Script::Common, 0x037E => Script::Common, 0x0385 => Script::Common, 0x0387 => Script::Common, 0x0589 => Script::Common, 0x0605 => Script::Common, 0x060C => Script::Common, 0x061B => Script::Common, 0x061C => Script::Common, 0x061F => Script::Common, 0x0640 => Script::Common, 0x06DD => Script::Common, 0x08E2 => Script::Common, 0x0964..=0x0965 => Script::Common, 0x0E3F => Script::Common, 0x0FD5..=0x0FD8 => Script::Common, 0x10FB => Script::Common, 0x16EB..=0x16ED => Script::Common, 0x1735..=0x1736 => Script::Common, 0x1802..=0x1803 => Script::Common, 0x1805 => Script::Common, 0x1CD3 => Script::Common, 0x1CE1 => Script::Common, 0x1CE9..=0x1CEC => Script::Common, 0x1CEE..=0x1CF1 => Script::Common, 0x1CF2..=0x1CF3 => Script::Common, 0x1CF5..=0x1CF6 => Script::Common, 0x2000..=0x200A => Script::Common, 0x200B => Script::Common, 0x200E..=0x200F => Script::Common, 0x2010..=0x2015 => Script::Common, 0x2016..=0x2017 => Script::Common, 0x2018 => Script::Common, 0x2019 => Script::Common, 0x201A => Script::Common, 0x201B..=0x201C => Script::Common, 0x201D => Script::Common, 0x201E => Script::Common, 0x201F => Script::Common, 0x2020..=0x2027 => Script::Common, 0x2028 => Script::Common, 0x2029 => Script::Common, 0x202A..=0x202E => Script::Common, 0x202F => Script::Common, 0x2030..=0x2038 => Script::Common, 0x2039 => Script::Common, 0x203A => Script::Common, 0x203B..=0x203E => Script::Common, 0x203F..=0x2040 => Script::Common, 0x2041..=0x2043 => Script::Common, 0x2044 => Script::Common, 0x2045 => Script::Common, 0x2046 => Script::Common, 0x2047..=0x2051 => Script::Common, 0x2052 => Script::Common, 0x2053 => Script::Common, 0x2054 => Script::Common, 0x2055..=0x205E => Script::Common, 0x205F => Script::Common, 0x2060..=0x2064 => Script::Common, 0x2066..=0x206F => Script::Common, 0x2070 => Script::Common, 0x2074..=0x2079 => Script::Common, 0x207A..=0x207C => Script::Common, 0x207D => Script::Common, 0x207E => Script::Common, 0x2080..=0x2089 => Script::Common, 0x208A..=0x208C => Script::Common, 0x208D => Script::Common, 0x208E => Script::Common, 0x20A0..=0x20BE => Script::Common, 0x2100..=0x2101 => Script::Common, 0x2102 => Script::Common, 0x2103..=0x2106 => Script::Common, 0x2107 => Script::Common, 0x2108..=0x2109 => Script::Common, 0x210A..=0x2113 => Script::Common, 0x2114 => Script::Common, 0x2115 => Script::Common, 0x2116..=0x2117 => Script::Common, 0x2118 => Script::Common, 0x2119..=0x211D => Script::Common, 0x211E..=0x2123 => Script::Common, 0x2124 => Script::Common, 0x2125 => Script::Common, 0x2127 => Script::Common, 0x2128 => Script::Common, 0x2129 => Script::Common, 0x212C..=0x212D => Script::Common, 0x212E => Script::Common, 0x212F..=0x2131 => Script::Common, 0x2133..=0x2134 => Script::Common, 0x2135..=0x2138 => Script::Common, 0x2139 => Script::Common, 0x213A..=0x213B => Script::Common, 0x213C..=0x213F => Script::Common, 0x2140..=0x2144 => Script::Common, 0x2145..=0x2149 => Script::Common, 0x214A => Script::Common, 0x214B => Script::Common, 0x214C..=0x214D => Script::Common, 0x214F => Script::Common, 0x2150..=0x215F => Script::Common, 0x2189 => Script::Common, 0x218A..=0x218B => Script::Common, 0x2190..=0x2194 => Script::Common, 0x2195..=0x2199 => Script::Common, 0x219A..=0x219B => Script::Common, 0x219C..=0x219F => Script::Common, 0x21A0 => Script::Common, 0x21A1..=0x21A2 => Script::Common, 0x21A3 => Script::Common, 0x21A4..=0x21A5 => Script::Common, 0x21A6 => Script::Common, 0x21A7..=0x21AD => Script::Common, 0x21AE => Script::Common, 0x21AF..=0x21CD => Script::Common, 0x21CE..=0x21CF => Script::Common, 0x21D0..=0x21D1 => Script::Common, 0x21D2 => Script::Common, 0x21D3 => Script::Common, 0x21D4 => Script::Common, 0x21D5..=0x21F3 => Script::Common, 0x21F4..=0x22FF => Script::Common, 0x2300..=0x2307 => Script::Common, 0x2308 => Script::Common, 0x2309 => Script::Common, 0x230A => Script::Common, 0x230B => Script::Common, 0x230C..=0x231F => Script::Common, 0x2320..=0x2321 => Script::Common, 0x2322..=0x2328 => Script::Common, 0x2329 => Script::Common, 0x232A => Script::Common, 0x232B..=0x237B => Script::Common, 0x237C => Script::Common, 0x237D..=0x239A => Script::Common, 0x239B..=0x23B3 => Script::Common, 0x23B4..=0x23DB => Script::Common, 0x23DC..=0x23E1 => Script::Common, 0x23E2..=0x23FE => Script::Common, 0x2400..=0x2426 => Script::Common, 0x2440..=0x244A => Script::Common, 0x2460..=0x249B => Script::Common, 0x249C..=0x24E9 => Script::Common, 0x24EA..=0x24FF => Script::Common, 0x2500..=0x25B6 => Script::Common, 0x25B7 => Script::Common, 0x25B8..=0x25C0 => Script::Common, 0x25C1 => Script::Common, 0x25C2..=0x25F7 => Script::Common, 0x25F8..=0x25FF => Script::Common, 0x2600..=0x266E => Script::Common, 0x266F => Script::Common, 0x2670..=0x2767 => Script::Common, 0x2768 => Script::Common, 0x2769 => Script::Common, 0x276A => Script::Common, 0x276B => Script::Common, 0x276C => Script::Common, 0x276D => Script::Common, 0x276E => Script::Common, 0x276F => Script::Common, 0x2770 => Script::Common, 0x2771 => Script::Common, 0x2772 => Script::Common, 0x2773 => Script::Common, 0x2774 => Script::Common, 0x2775 => Script::Common, 0x2776..=0x2793 => Script::Common, 0x2794..=0x27BF => Script::Common, 0x27C0..=0x27C4 => Script::Common, 0x27C5 => Script::Common, 0x27C6 => Script::Common, 0x27C7..=0x27E5 => Script::Common, 0x27E6 => Script::Common, 0x27E7 => Script::Common, 0x27E8 => Script::Common, 0x27E9 => Script::Common, 0x27EA => Script::Common, 0x27EB => Script::Common, 0x27EC => Script::Common, 0x27ED => Script::Common, 0x27EE => Script::Common, 0x27EF => Script::Common, 0x27F0..=0x27FF => Script::Common, 0x2900..=0x2982 => Script::Common, 0x2983 => Script::Common, 0x2984 => Script::Common, 0x2985 => Script::Common, 0x2986 => Script::Common, 0x2987 => Script::Common, 0x2988 => Script::Common, 0x2989 => Script::Common, 0x298A => Script::Common, 0x298B => Script::Common, 0x298C => Script::Common, 0x298D => Script::Common, 0x298E => Script::Common, 0x298F => Script::Common, 0x2990 => Script::Common, 0x2991 => Script::Common, 0x2992 => Script::Common, 0x2993 => Script::Common, 0x2994 => Script::Common, 0x2995 => Script::Common, 0x2996 => Script::Common, 0x2997 => Script::Common, 0x2998 => Script::Common, 0x2999..=0x29D7 => Script::Common, 0x29D8 => Script::Common, 0x29D9 => Script::Common, 0x29DA => Script::Common, 0x29DB => Script::Common, 0x29DC..=0x29FB => Script::Common, 0x29FC => Script::Common, 0x29FD => Script::Common, 0x29FE..=0x2AFF => Script::Common, 0x2B00..=0x2B2F => Script::Common, 0x2B30..=0x2B44 => Script::Common, 0x2B45..=0x2B46 => Script::Common, 0x2B47..=0x2B4C => Script::Common, 0x2B4D..=0x2B73 => Script::Common, 0x2B76..=0x2B95 => Script::Common, 0x2B98..=0x2BB9 => Script::Common, 0x2BBD..=0x2BC8 => Script::Common, 0x2BCA..=0x2BD1 => Script::Common, 0x2BEC..=0x2BEF => Script::Common, 0x2E00..=0x2E01 => Script::Common, 0x2E02 => Script::Common, 0x2E03 => Script::Common, 0x2E04 => Script::Common, 0x2E05 => Script::Common, 0x2E06..=0x2E08 => Script::Common, 0x2E09 => Script::Common, 0x2E0A => Script::Common, 0x2E0B => Script::Common, 0x2E0C => Script::Common, 0x2E0D => Script::Common, 0x2E0E..=0x2E16 => Script::Common, 0x2E17 => Script::Common, 0x2E18..=0x2E19 => Script::Common, 0x2E1A => Script::Common, 0x2E1B => Script::Common, 0x2E1C => Script::Common, 0x2E1D => Script::Common, 0x2E1E..=0x2E1F => Script::Common, 0x2E20 => Script::Common, 0x2E21 => Script::Common, 0x2E22 => Script::Common, 0x2E23 => Script::Common, 0x2E24 => Script::Common, 0x2E25 => Script::Common, 0x2E26 => Script::Common, 0x2E27 => Script::Common, 0x2E28 => Script::Common, 0x2E29 => Script::Common, 0x2E2A..=0x2E2E => Script::Common, 0x2E2F => Script::Common, 0x2E30..=0x2E39 => Script::Common, 0x2E3A..=0x2E3B => Script::Common, 0x2E3C..=0x2E3F => Script::Common, 0x2E40 => Script::Common, 0x2E41 => Script::Common, 0x2E42 => Script::Common, 0x2E43..=0x2E44 => Script::Common, 0x2FF0..=0x2FFB => Script::Common, 0x3000 => Script::Common, 0x3001..=0x3003 => Script::Common, 0x3004 => Script::Common, 0x3006 => Script::Common, 0x3008 => Script::Common, 0x3009 => Script::Common, 0x300A => Script::Common, 0x300B => Script::Common, 0x300C => Script::Common, 0x300D => Script::Common, 0x300E => Script::Common, 0x300F => Script::Common, 0x3010 => Script::Common, 0x3011 => Script::Common, 0x3012..=0x3013 => Script::Common, 0x3014 => Script::Common, 0x3015 => Script::Common, 0x3016 => Script::Common, 0x3017 => Script::Common, 0x3018 => Script::Common, 0x3019 => Script::Common, 0x301A => Script::Common, 0x301B => Script::Common, 0x301C => Script::Common, 0x301D => Script::Common, 0x301E..=0x301F => Script::Common, 0x3020 => Script::Common, 0x3030 => Script::Common, 0x3031..=0x3035 => Script::Common, 0x3036..=0x3037 => Script::Common, 0x303C => Script::Common, 0x303D => Script::Common, 0x303E..=0x303F => Script::Common, 0x309B..=0x309C => Script::Common, 0x30A0 => Script::Common, 0x30FB => Script::Common, 0x30FC => Script::Common, 0x3190..=0x3191 => Script::Common, 0x3192..=0x3195 => Script::Common, 0x3196..=0x319F => Script::Common, 0x31C0..=0x31E3 => Script::Common, 0x3220..=0x3229 => Script::Common, 0x322A..=0x3247 => Script::Common, 0x3248..=0x324F => Script::Common, 0x3250 => Script::Common, 0x3251..=0x325F => Script::Common, 0x327F => Script::Common, 0x3280..=0x3289 => Script::Common, 0x328A..=0x32B0 => Script::Common, 0x32B1..=0x32BF => Script::Common, 0x32C0..=0x32CF => Script::Common, 0x3358..=0x33FF => Script::Common, 0x4DC0..=0x4DFF => Script::Common, 0xA700..=0xA716 => Script::Common, 0xA717..=0xA71F => Script::Common, 0xA720..=0xA721 => Script::Common, 0xA788 => Script::Common, 0xA789..=0xA78A => Script::Common, 0xA830..=0xA835 => Script::Common, 0xA836..=0xA837 => Script::Common, 0xA838 => Script::Common, 0xA839 => Script::Common, 0xA92E => Script::Common, 0xA9CF => Script::Common, 0xAB5B => Script::Common, 0xFD3E => Script::Common, 0xFD3F => Script::Common, 0xFE10..=0xFE16 => Script::Common, 0xFE17 => Script::Common, 0xFE18 => Script::Common, 0xFE19 => Script::Common, 0xFE30 => Script::Common, 0xFE31..=0xFE32 => Script::Common, 0xFE33..=0xFE34 => Script::Common, 0xFE35 => Script::Common, 0xFE36 => Script::Common, 0xFE37 => Script::Common, 0xFE38 => Script::Common, 0xFE39 => Script::Common, 0xFE3A => Script::Common, 0xFE3B => Script::Common, 0xFE3C => Script::Common, 0xFE3D => Script::Common, 0xFE3E => Script::Common, 0xFE3F => Script::Common, 0xFE40 => Script::Common, 0xFE41 => Script::Common, 0xFE42 => Script::Common, 0xFE43 => Script::Common, 0xFE44 => Script::Common, 0xFE45..=0xFE46 => Script::Common, 0xFE47 => Script::Common, 0xFE48 => Script::Common, 0xFE49..=0xFE4C => Script::Common, 0xFE4D..=0xFE4F => Script::Common, 0xFE50..=0xFE52 => Script::Common, 0xFE54..=0xFE57 => Script::Common, 0xFE58 => Script::Common, 0xFE59 => Script::Common, 0xFE5A => Script::Common, 0xFE5B => Script::Common, 0xFE5C => Script::Common, 0xFE5D => Script::Common, 0xFE5E => Script::Common, 0xFE5F..=0xFE61 => Script::Common, 0xFE62 => Script::Common, 0xFE63 => Script::Common, 0xFE64..=0xFE66 => Script::Common, 0xFE68 => Script::Common, 0xFE69 => Script::Common, 0xFE6A..=0xFE6B => Script::Common, 0xFEFF => Script::Common, 0xFF01..=0xFF03 => Script::Common, 0xFF04 => Script::Common, 0xFF05..=0xFF07 => Script::Common, 0xFF08 => Script::Common, 0xFF09 => Script::Common, 0xFF0A => Script::Common, 0xFF0B => Script::Common, 0xFF0C => Script::Common, 0xFF0D => Script::Common, 0xFF0E..=0xFF0F => Script::Common, 0xFF10..=0xFF19 => Script::Common, 0xFF1A..=0xFF1B => Script::Common, 0xFF1C..=0xFF1E => Script::Common, 0xFF1F..=0xFF20 => Script::Common, 0xFF3B => Script::Common, 0xFF3C => Script::Common, 0xFF3D => Script::Common, 0xFF3E => Script::Common, 0xFF3F => Script::Common, 0xFF40 => Script::Common, 0xFF5B => Script::Common, 0xFF5C => Script::Common, 0xFF5D => Script::Common, 0xFF5E => Script::Common, 0xFF5F => Script::Common, 0xFF60 => Script::Common, 0xFF61 => Script::Common, 0xFF62 => Script::Common, 0xFF63 => Script::Common, 0xFF64..=0xFF65 => Script::Common, 0xFF70 => Script::Common, 0xFF9E..=0xFF9F => Script::Common, 0xFFE0..=0xFFE1 => Script::Common, 0xFFE2 => Script::Common, 0xFFE3 => Script::Common, 0xFFE4 => Script::Common, 0xFFE5..=0xFFE6 => Script::Common, 0xFFE8 => Script::Common, 0xFFE9..=0xFFEC => Script::Common, 0xFFED..=0xFFEE => Script::Common, 0xFFF9..=0xFFFB => Script::Common, 0xFFFC..=0xFFFD => Script::Common, 0x10100..=0x10102 => Script::Common, 0x10107..=0x10133 => Script::Common, 0x10137..=0x1013F => Script::Common, 0x10190..=0x1019B => Script::Common, 0x101D0..=0x101FC => Script::Common, 0x102E1..=0x102FB => Script::Common, 0x1BCA0..=0x1BCA3 => Script::Common, 0x1D000..=0x1D0F5 => Script::Common, 0x1D100..=0x1D126 => Script::Common, 0x1D129..=0x1D164 => Script::Common, 0x1D165..=0x1D166 => Script::Common, 0x1D16A..=0x1D16C => Script::Common, 0x1D16D..=0x1D172 => Script::Common, 0x1D173..=0x1D17A => Script::Common, 0x1D183..=0x1D184 => Script::Common, 0x1D18C..=0x1D1A9 => Script::Common, 0x1D1AE..=0x1D1E8 => Script::Common, 0x1D300..=0x1D356 => Script::Common, 0x1D360..=0x1D371 => Script::Common, 0x1D400..=0x1D454 => Script::Common, 0x1D456..=0x1D49C => Script::Common, 0x1D49E..=0x1D49F => Script::Common, 0x1D4A2 => Script::Common, 0x1D4A5..=0x1D4A6 => Script::Common, 0x1D4A9..=0x1D4AC => Script::Common, 0x1D4AE..=0x1D4B9 => Script::Common, 0x1D4BB => Script::Common, 0x1D4BD..=0x1D4C3 => Script::Common, 0x1D4C5..=0x1D505 => Script::Common, 0x1D507..=0x1D50A => Script::Common, 0x1D50D..=0x1D514 => Script::Common, 0x1D516..=0x1D51C => Script::Common, 0x1D51E..=0x1D539 => Script::Common, 0x1D53B..=0x1D53E => Script::Common, 0x1D540..=0x1D544 => Script::Common, 0x1D546 => Script::Common, 0x1D54A..=0x1D550 => Script::Common, 0x1D552..=0x1D6A5 => Script::Common, 0x1D6A8..=0x1D6C0 => Script::Common, 0x1D6C1 => Script::Common, 0x1D6C2..=0x1D6DA => Script::Common, 0x1D6DB => Script::Common, 0x1D6DC..=0x1D6FA => Script::Common, 0x1D6FB => Script::Common, 0x1D6FC..=0x1D714 => Script::Common, 0x1D715 => Script::Common, 0x1D716..=0x1D734 => Script::Common, 0x1D735 => Script::Common, 0x1D736..=0x1D74E => Script::Common, 0x1D74F => Script::Common, 0x1D750..=0x1D76E => Script::Common, 0x1D76F => Script::Common, 0x1D770..=0x1D788 => Script::Common, 0x1D789 => Script::Common, 0x1D78A..=0x1D7A8 => Script::Common, 0x1D7A9 => Script::Common, 0x1D7AA..=0x1D7C2 => Script::Common, 0x1D7C3 => Script::Common, 0x1D7C4..=0x1D7CB => Script::Common, 0x1D7CE..=0x1D7FF => Script::Common, 0x1F000..=0x1F02B => Script::Common, 0x1F030..=0x1F093 => Script::Common, 0x1F0A0..=0x1F0AE => Script::Common, 0x1F0B1..=0x1F0BF => Script::Common, 0x1F0C1..=0x1F0CF => Script::Common, 0x1F0D1..=0x1F0F5 => Script::Common, 0x1F100..=0x1F10C => Script::Common, 0x1F110..=0x1F12E => Script::Common, 0x1F130..=0x1F16B => Script::Common, 0x1F170..=0x1F1AC => Script::Common, 0x1F1E6..=0x1F1FF => Script::Common, 0x1F201..=0x1F202 => Script::Common, 0x1F210..=0x1F23B => Script::Common, 0x1F240..=0x1F248 => Script::Common, 0x1F250..=0x1F251 => Script::Common, 0x1F300..=0x1F3FA => Script::Common, 0x1F3FB..=0x1F3FF => Script::Common, 0x1F400..=0x1F6D2 => Script::Common, 0x1F6E0..=0x1F6EC => Script::Common, 0x1F6F0..=0x1F6F6 => Script::Common, 0x1F700..=0x1F773 => Script::Common, 0x1F780..=0x1F7D4 => Script::Common, 0x1F800..=0x1F80B => Script::Common, 0x1F810..=0x1F847 => Script::Common, 0x1F850..=0x1F859 => Script::Common, 0x1F860..=0x1F887 => Script::Common, 0x1F890..=0x1F8AD => Script::Common, 0x1F910..=0x1F91E => Script::Common, 0x1F920..=0x1F927 => Script::Common, 0x1F930 => Script::Common, 0x1F933..=0x1F93E => Script::Common, 0x1F940..=0x1F94B => Script::Common, 0x1F950..=0x1F95E => Script::Common, 0x1F980..=0x1F991 => Script::Common, 0x1F9C0 => Script::Common, 0xE0001 => Script::Common, 0xE0020..=0xE007F => Script::Common, 0x0041..=0x005A => Script::Latin, 0x0061..=0x007A => Script::Latin, 0x00AA => Script::Latin, 0x00BA => Script::Latin, 0x00C0..=0x00D6 => Script::Latin, 0x00D8..=0x00F6 => Script::Latin, 0x00F8..=0x01BA => Script::Latin, 0x01BB => Script::Latin, 0x01BC..=0x01BF => Script::Latin, 0x01C0..=0x01C3 => Script::Latin, 0x01C4..=0x0293 => Script::Latin, 0x0294 => Script::Latin, 0x0295..=0x02AF => Script::Latin, 0x02B0..=0x02B8 => Script::Latin, 0x02E0..=0x02E4 => Script::Latin, 0x1D00..=0x1D25 => Script::Latin, 0x1D2C..=0x1D5C => Script::Latin, 0x1D62..=0x1D65 => Script::Latin, 0x1D6B..=0x1D77 => Script::Latin, 0x1D79..=0x1D9A => Script::Latin, 0x1D9B..=0x1DBE => Script::Latin, 0x1E00..=0x1EFF => Script::Latin, 0x2071 => Script::Latin, 0x207F => Script::Latin, 0x2090..=0x209C => Script::Latin, 0x212A..=0x212B => Script::Latin, 0x2132 => Script::Latin, 0x214E => Script::Latin, 0x2160..=0x2182 => Script::Latin, 0x2183..=0x2184 => Script::Latin, 0x2185..=0x2188 => Script::Latin, 0x2C60..=0x2C7B => Script::Latin, 0x2C7C..=0x2C7D => Script::Latin, 0x2C7E..=0x2C7F => Script::Latin, 0xA722..=0xA76F => Script::Latin, 0xA770 => Script::Latin, 0xA771..=0xA787 => Script::Latin, 0xA78B..=0xA78E => Script::Latin, 0xA78F => Script::Latin, 0xA790..=0xA7AE => Script::Latin, 0xA7B0..=0xA7B7 => Script::Latin, 0xA7F7 => Script::Latin, 0xA7F8..=0xA7F9 => Script::Latin, 0xA7FA => Script::Latin, 0xA7FB..=0xA7FF => Script::Latin, 0xAB30..=0xAB5A => Script::Latin, 0xAB5C..=0xAB5F => Script::Latin, 0xAB60..=0xAB64 => Script::Latin, 0xFB00..=0xFB06 => Script::Latin, 0xFF21..=0xFF3A => Script::Latin, 0xFF41..=0xFF5A => Script::Latin, 0x0370..=0x0373 => Script::Greek, 0x0375 => Script::Greek, 0x0376..=0x0377 => Script::Greek, 0x037A => Script::Greek, 0x037B..=0x037D => Script::Greek, 0x037F => Script::Greek, 0x0384 => Script::Greek, 0x0386 => Script::Greek, 0x0388..=0x038A => Script::Greek, 0x038C => Script::Greek, 0x038E..=0x03A1 => Script::Greek, 0x03A3..=0x03E1 => Script::Greek, 0x03F0..=0x03F5 => Script::Greek, 0x03F6 => Script::Greek, 0x03F7..=0x03FF => Script::Greek, 0x1D26..=0x1D2A => Script::Greek, 0x1D5D..=0x1D61 => Script::Greek, 0x1D66..=0x1D6A => Script::Greek, 0x1DBF => Script::Greek, 0x1F00..=0x1F15 => Script::Greek, 0x1F18..=0x1F1D => Script::Greek, 0x1F20..=0x1F45 => Script::Greek, 0x1F48..=0x1F4D => Script::Greek, 0x1F50..=0x1F57 => Script::Greek, 0x1F59 => Script::Greek, 0x1F5B => Script::Greek, 0x1F5D => Script::Greek, 0x1F5F..=0x1F7D => Script::Greek, 0x1F80..=0x1FB4 => Script::Greek, 0x1FB6..=0x1FBC => Script::Greek, 0x1FBD => Script::Greek, 0x1FBE => Script::Greek, 0x1FBF..=0x1FC1 => Script::Greek, 0x1FC2..=0x1FC4 => Script::Greek, 0x1FC6..=0x1FCC => Script::Greek, 0x1FCD..=0x1FCF => Script::Greek, 0x1FD0..=0x1FD3 => Script::Greek, 0x1FD6..=0x1FDB => Script::Greek, 0x1FDD..=0x1FDF => Script::Greek, 0x1FE0..=0x1FEC => Script::Greek, 0x1FED..=0x1FEF => Script::Greek, 0x1FF2..=0x1FF4 => Script::Greek, 0x1FF6..=0x1FFC => Script::Greek, 0x1FFD..=0x1FFE => Script::Greek, 0x2126 => Script::Greek, 0xAB65 => Script::Greek, 0x10140..=0x10174 => Script::Greek, 0x10175..=0x10178 => Script::Greek, 0x10179..=0x10189 => Script::Greek, 0x1018A..=0x1018B => Script::Greek, 0x1018C..=0x1018E => Script::Greek, 0x101A0 => Script::Greek, 0x1D200..=0x1D241 => Script::Greek, 0x1D242..=0x1D244 => Script::Greek, 0x1D245 => Script::Greek, 0x0400..=0x0481 => Script::Cyrillic, 0x0482 => Script::Cyrillic, 0x0483..=0x0484 => Script::Cyrillic, 0x0487 => Script::Cyrillic, 0x0488..=0x0489 => Script::Cyrillic, 0x048A..=0x052F => Script::Cyrillic, 0x1C80..=0x1C88 => Script::Cyrillic, 0x1D2B => Script::Cyrillic, 0x1D78 => Script::Cyrillic, 0x2DE0..=0x2DFF => Script::Cyrillic, 0xA640..=0xA66D => Script::Cyrillic, 0xA66E => Script::Cyrillic, 0xA66F => Script::Cyrillic, 0xA670..=0xA672 => Script::Cyrillic, 0xA673 => Script::Cyrillic, 0xA674..=0xA67D => Script::Cyrillic, 0xA67E => Script::Cyrillic, 0xA67F => Script::Cyrillic, 0xA680..=0xA69B => Script::Cyrillic, 0xA69C..=0xA69D => Script::Cyrillic, 0xA69E..=0xA69F => Script::Cyrillic, 0xFE2E..=0xFE2F => Script::Cyrillic, 0x0531..=0x0556 => Script::Armenian, 0x0559 => Script::Armenian, 0x055A..=0x055F => Script::Armenian, 0x0561..=0x0587 => Script::Armenian, 0x058A => Script::Armenian, 0x058D..=0x058E => Script::Armenian, 0x058F => Script::Armenian, 0xFB13..=0xFB17 => Script::Armenian, 0x0591..=0x05BD => Script::Hebrew, 0x05BE => Script::Hebrew, 0x05BF => Script::Hebrew, 0x05C0 => Script::Hebrew, 0x05C1..=0x05C2 => Script::Hebrew, 0x05C3 => Script::Hebrew, 0x05C4..=0x05C5 => Script::Hebrew, 0x05C6 => Script::Hebrew, 0x05C7 => Script::Hebrew, 0x05D0..=0x05EA => Script::Hebrew, 0x05F0..=0x05F2 => Script::Hebrew, 0x05F3..=0x05F4 => Script::Hebrew, 0xFB1D => Script::Hebrew, 0xFB1E => Script::Hebrew, 0xFB1F..=0xFB28 => Script::Hebrew, 0xFB29 => Script::Hebrew, 0xFB2A..=0xFB36 => Script::Hebrew, 0xFB38..=0xFB3C => Script::Hebrew, 0xFB3E => Script::Hebrew, 0xFB40..=0xFB41 => Script::Hebrew, 0xFB43..=0xFB44 => Script::Hebrew, 0xFB46..=0xFB4F => Script::Hebrew, 0x0600..=0x0604 => Script::Arabic, 0x0606..=0x0608 => Script::Arabic, 0x0609..=0x060A => Script::Arabic, 0x060B => Script::Arabic, 0x060D => Script::Arabic, 0x060E..=0x060F => Script::Arabic, 0x0610..=0x061A => Script::Arabic, 0x061E => Script::Arabic, 0x0620..=0x063F => Script::Arabic, 0x0641..=0x064A => Script::Arabic, 0x0656..=0x065F => Script::Arabic, 0x0660..=0x0669 => Script::Arabic, 0x066A..=0x066D => Script::Arabic, 0x066E..=0x066F => Script::Arabic, 0x0671..=0x06D3 => Script::Arabic, 0x06D4 => Script::Arabic, 0x06D5 => Script::Arabic, 0x06D6..=0x06DC => Script::Arabic, 0x06DE => Script::Arabic, 0x06DF..=0x06E4 => Script::Arabic, 0x06E5..=0x06E6 => Script::Arabic, 0x06E7..=0x06E8 => Script::Arabic, 0x06E9 => Script::Arabic, 0x06EA..=0x06ED => Script::Arabic, 0x06EE..=0x06EF => Script::Arabic, 0x06F0..=0x06F9 => Script::Arabic, 0x06FA..=0x06FC => Script::Arabic, 0x06FD..=0x06FE => Script::Arabic, 0x06FF => Script::Arabic, 0x0750..=0x077F => Script::Arabic, 0x08A0..=0x08B4 => Script::Arabic, 0x08B6..=0x08BD => Script::Arabic, 0x08D4..=0x08E1 => Script::Arabic, 0x08E3..=0x08FF => Script::Arabic, 0xFB50..=0xFBB1 => Script::Arabic, 0xFBB2..=0xFBC1 => Script::Arabic, 0xFBD3..=0xFD3D => Script::Arabic, 0xFD50..=0xFD8F => Script::Arabic, 0xFD92..=0xFDC7 => Script::Arabic, 0xFDF0..=0xFDFB => Script::Arabic, 0xFDFC => Script::Arabic, 0xFDFD => Script::Arabic, 0xFE70..=0xFE74 => Script::Arabic, 0xFE76..=0xFEFC => Script::Arabic, 0x10E60..=0x10E7E => Script::Arabic, 0x1EE00..=0x1EE03 => Script::Arabic, 0x1EE05..=0x1EE1F => Script::Arabic, 0x1EE21..=0x1EE22 => Script::Arabic, 0x1EE24 => Script::Arabic, 0x1EE27 => Script::Arabic, 0x1EE29..=0x1EE32 => Script::Arabic, 0x1EE34..=0x1EE37 => Script::Arabic, 0x1EE39 => Script::Arabic, 0x1EE3B => Script::Arabic, 0x1EE42 => Script::Arabic, 0x1EE47 => Script::Arabic, 0x1EE49 => Script::Arabic, 0x1EE4B => Script::Arabic, 0x1EE4D..=0x1EE4F => Script::Arabic, 0x1EE51..=0x1EE52 => Script::Arabic, 0x1EE54 => Script::Arabic, 0x1EE57 => Script::Arabic, 0x1EE59 => Script::Arabic, 0x1EE5B => Script::Arabic, 0x1EE5D => Script::Arabic, 0x1EE5F => Script::Arabic, 0x1EE61..=0x1EE62 => Script::Arabic, 0x1EE64 => Script::Arabic, 0x1EE67..=0x1EE6A => Script::Arabic, 0x1EE6C..=0x1EE72 => Script::Arabic, 0x1EE74..=0x1EE77 => Script::Arabic, 0x1EE79..=0x1EE7C => Script::Arabic, 0x1EE7E => Script::Arabic, 0x1EE80..=0x1EE89 => Script::Arabic, 0x1EE8B..=0x1EE9B => Script::Arabic, 0x1EEA1..=0x1EEA3 => Script::Arabic, 0x1EEA5..=0x1EEA9 => Script::Arabic, 0x1EEAB..=0x1EEBB => Script::Arabic, 0x1EEF0..=0x1EEF1 => Script::Arabic, 0x0700..=0x070D => Script::Syriac, 0x070F => Script::Syriac, 0x0710 => Script::Syriac, 0x0711 => Script::Syriac, 0x0712..=0x072F => Script::Syriac, 0x0730..=0x074A => Script::Syriac, 0x074D..=0x074F => Script::Syriac, 0x0780..=0x07A5 => Script::Thaana, 0x07A6..=0x07B0 => Script::Thaana, 0x07B1 => Script::Thaana, 0x0900..=0x0902 => Script::Devanagari, 0x0903 => Script::Devanagari, 0x0904..=0x0939 => Script::Devanagari, 0x093A => Script::Devanagari, 0x093B => Script::Devanagari, 0x093C => Script::Devanagari, 0x093D => Script::Devanagari, 0x093E..=0x0940 => Script::Devanagari, 0x0941..=0x0948 => Script::Devanagari, 0x0949..=0x094C => Script::Devanagari, 0x094D => Script::Devanagari, 0x094E..=0x094F => Script::Devanagari, 0x0950 => Script::Devanagari, 0x0953..=0x0957 => Script::Devanagari, 0x0958..=0x0961 => Script::Devanagari, 0x0962..=0x0963 => Script::Devanagari, 0x0966..=0x096F => Script::Devanagari, 0x0970 => Script::Devanagari, 0x0971 => Script::Devanagari, 0x0972..=0x097F => Script::Devanagari, 0xA8E0..=0xA8F1 => Script::Devanagari, 0xA8F2..=0xA8F7 => Script::Devanagari, 0xA8F8..=0xA8FA => Script::Devanagari, 0xA8FB => Script::Devanagari, 0xA8FC => Script::Devanagari, 0xA8FD => Script::Devanagari, 0x0980 => Script::Bengali, 0x0981 => Script::Bengali, 0x0982..=0x0983 => Script::Bengali, 0x0985..=0x098C => Script::Bengali, 0x098F..=0x0990 => Script::Bengali, 0x0993..=0x09A8 => Script::Bengali, 0x09AA..=0x09B0 => Script::Bengali, 0x09B2 => Script::Bengali, 0x09B6..=0x09B9 => Script::Bengali, 0x09BC => Script::Bengali, 0x09BD => Script::Bengali, 0x09BE..=0x09C0 => Script::Bengali, 0x09C1..=0x09C4 => Script::Bengali, 0x09C7..=0x09C8 => Script::Bengali, 0x09CB..=0x09CC => Script::Bengali, 0x09CD => Script::Bengali, 0x09CE => Script::Bengali, 0x09D7 => Script::Bengali, 0x09DC..=0x09DD => Script::Bengali, 0x09DF..=0x09E1 => Script::Bengali, 0x09E2..=0x09E3 => Script::Bengali, 0x09E6..=0x09EF => Script::Bengali, 0x09F0..=0x09F1 => Script::Bengali, 0x09F2..=0x09F3 => Script::Bengali, 0x09F4..=0x09F9 => Script::Bengali, 0x09FA => Script::Bengali, 0x09FB => Script::Bengali, 0x0A01..=0x0A02 => Script::Gurmukhi, 0x0A03 => Script::Gurmukhi, 0x0A05..=0x0A0A => Script::Gurmukhi, 0x0A0F..=0x0A10 => Script::Gurmukhi, 0x0A13..=0x0A28 => Script::Gurmukhi, 0x0A2A..=0x0A30 => Script::Gurmukhi, 0x0A32..=0x0A33 => Script::Gurmukhi, 0x0A35..=0x0A36 => Script::Gurmukhi, 0x0A38..=0x0A39 => Script::Gurmukhi, 0x0A3C => Script::Gurmukhi, 0x0A3E..=0x0A40 => Script::Gurmukhi, 0x0A41..=0x0A42 => Script::Gurmukhi, 0x0A47..=0x0A48 => Script::Gurmukhi, 0x0A4B..=0x0A4D => Script::Gurmukhi, 0x0A51 => Script::Gurmukhi, 0x0A59..=0x0A5C => Script::Gurmukhi, 0x0A5E => Script::Gurmukhi, 0x0A66..=0x0A6F => Script::Gurmukhi, 0x0A70..=0x0A71 => Script::Gurmukhi, 0x0A72..=0x0A74 => Script::Gurmukhi, 0x0A75 => Script::Gurmukhi, 0x0A81..=0x0A82 => Script::Gujarati, 0x0A83 => Script::Gujarati, 0x0A85..=0x0A8D => Script::Gujarati, 0x0A8F..=0x0A91 => Script::Gujarati, 0x0A93..=0x0AA8 => Script::Gujarati, 0x0AAA..=0x0AB0 => Script::Gujarati, 0x0AB2..=0x0AB3 => Script::Gujarati, 0x0AB5..=0x0AB9 => Script::Gujarati, 0x0ABC => Script::Gujarati, 0x0ABD => Script::Gujarati, 0x0ABE..=0x0AC0 => Script::Gujarati, 0x0AC1..=0x0AC5 => Script::Gujarati, 0x0AC7..=0x0AC8 => Script::Gujarati, 0x0AC9 => Script::Gujarati, 0x0ACB..=0x0ACC => Script::Gujarati, 0x0ACD => Script::Gujarati, 0x0AD0 => Script::Gujarati, 0x0AE0..=0x0AE1 => Script::Gujarati, 0x0AE2..=0x0AE3 => Script::Gujarati, 0x0AE6..=0x0AEF => Script::Gujarati, 0x0AF0 => Script::Gujarati, 0x0AF1 => Script::Gujarati, 0x0AF9 => Script::Gujarati, 0x0B01 => Script::Oriya, 0x0B02..=0x0B03 => Script::Oriya, 0x0B05..=0x0B0C => Script::Oriya, 0x0B0F..=0x0B10 => Script::Oriya, 0x0B13..=0x0B28 => Script::Oriya, 0x0B2A..=0x0B30 => Script::Oriya, 0x0B32..=0x0B33 => Script::Oriya, 0x0B35..=0x0B39 => Script::Oriya, 0x0B3C => Script::Oriya, 0x0B3D => Script::Oriya, 0x0B3E => Script::Oriya, 0x0B3F => Script::Oriya, 0x0B40 => Script::Oriya, 0x0B41..=0x0B44 => Script::Oriya, 0x0B47..=0x0B48 => Script::Oriya, 0x0B4B..=0x0B4C => Script::Oriya, 0x0B4D => Script::Oriya, 0x0B56 => Script::Oriya, 0x0B57 => Script::Oriya, 0x0B5C..=0x0B5D => Script::Oriya, 0x0B5F..=0x0B61 => Script::Oriya, 0x0B62..=0x0B63 => Script::Oriya, 0x0B66..=0x0B6F => Script::Oriya, 0x0B70 => Script::Oriya, 0x0B71 => Script::Oriya, 0x0B72..=0x0B77 => Script::Oriya, 0x0B82 => Script::Tamil, 0x0B83 => Script::Tamil, 0x0B85..=0x0B8A => Script::Tamil, 0x0B8E..=0x0B90 => Script::Tamil, 0x0B92..=0x0B95 => Script::Tamil, 0x0B99..=0x0B9A => Script::Tamil, 0x0B9C => Script::Tamil, 0x0B9E..=0x0B9F => Script::Tamil, 0x0BA3..=0x0BA4 => Script::Tamil, 0x0BA8..=0x0BAA => Script::Tamil, 0x0BAE..=0x0BB9 => Script::Tamil, 0x0BBE..=0x0BBF => Script::Tamil, 0x0BC0 => Script::Tamil, 0x0BC1..=0x0BC2 => Script::Tamil, 0x0BC6..=0x0BC8 => Script::Tamil, 0x0BCA..=0x0BCC => Script::Tamil, 0x0BCD => Script::Tamil, 0x0BD0 => Script::Tamil, 0x0BD7 => Script::Tamil, 0x0BE6..=0x0BEF => Script::Tamil, 0x0BF0..=0x0BF2 => Script::Tamil, 0x0BF3..=0x0BF8 => Script::Tamil, 0x0BF9 => Script::Tamil, 0x0BFA => Script::Tamil, 0x0C00 => Script::Telugu, 0x0C01..=0x0C03 => Script::Telugu, 0x0C05..=0x0C0C => Script::Telugu, 0x0C0E..=0x0C10 => Script::Telugu, 0x0C12..=0x0C28 => Script::Telugu, 0x0C2A..=0x0C39 => Script::Telugu, 0x0C3D => Script::Telugu, 0x0C3E..=0x0C40 => Script::Telugu, 0x0C41..=0x0C44 => Script::Telugu, 0x0C46..=0x0C48 => Script::Telugu, 0x0C4A..=0x0C4D => Script::Telugu, 0x0C55..=0x0C56 => Script::Telugu, 0x0C58..=0x0C5A => Script::Telugu, 0x0C60..=0x0C61 => Script::Telugu, 0x0C62..=0x0C63 => Script::Telugu, 0x0C66..=0x0C6F => Script::Telugu, 0x0C78..=0x0C7E => Script::Telugu, 0x0C7F => Script::Telugu, 0x0C80 => Script::Kannada, 0x0C81 => Script::Kannada, 0x0C82..=0x0C83 => Script::Kannada, 0x0C85..=0x0C8C => Script::Kannada, 0x0C8E..=0x0C90 => Script::Kannada, 0x0C92..=0x0CA8 => Script::Kannada, 0x0CAA..=0x0CB3 => Script::Kannada, 0x0CB5..=0x0CB9 => Script::Kannada, 0x0CBC => Script::Kannada, 0x0CBD => Script::Kannada, 0x0CBE => Script::Kannada, 0x0CBF => Script::Kannada, 0x0CC0..=0x0CC4 => Script::Kannada, 0x0CC6 => Script::Kannada, 0x0CC7..=0x0CC8 => Script::Kannada, 0x0CCA..=0x0CCB => Script::Kannada, 0x0CCC..=0x0CCD => Script::Kannada, 0x0CD5..=0x0CD6 => Script::Kannada, 0x0CDE => Script::Kannada, 0x0CE0..=0x0CE1 => Script::Kannada, 0x0CE2..=0x0CE3 => Script::Kannada, 0x0CE6..=0x0CEF => Script::Kannada, 0x0CF1..=0x0CF2 => Script::Kannada, 0x0D01 => Script::Malayalam, 0x0D02..=0x0D03 => Script::Malayalam, 0x0D05..=0x0D0C => Script::Malayalam, 0x0D0E..=0x0D10 => Script::Malayalam, 0x0D12..=0x0D3A => Script::Malayalam, 0x0D3D => Script::Malayalam, 0x0D3E..=0x0D40 => Script::Malayalam, 0x0D41..=0x0D44 => Script::Malayalam, 0x0D46..=0x0D48 => Script::Malayalam, 0x0D4A..=0x0D4C => Script::Malayalam, 0x0D4D => Script::Malayalam, 0x0D4E => Script::Malayalam, 0x0D4F => Script::Malayalam, 0x0D54..=0x0D56 => Script::Malayalam, 0x0D57 => Script::Malayalam, 0x0D58..=0x0D5E => Script::Malayalam, 0x0D5F..=0x0D61 => Script::Malayalam, 0x0D62..=0x0D63 => Script::Malayalam, 0x0D66..=0x0D6F => Script::Malayalam, 0x0D70..=0x0D78 => Script::Malayalam, 0x0D79 => Script::Malayalam, 0x0D7A..=0x0D7F => Script::Malayalam, 0x0D82..=0x0D83 => Script::Sinhala, 0x0D85..=0x0D96 => Script::Sinhala, 0x0D9A..=0x0DB1 => Script::Sinhala, 0x0DB3..=0x0DBB => Script::Sinhala, 0x0DBD => Script::Sinhala, 0x0DC0..=0x0DC6 => Script::Sinhala, 0x0DCA => Script::Sinhala, 0x0DCF..=0x0DD1 => Script::Sinhala, 0x0DD2..=0x0DD4 => Script::Sinhala, 0x0DD6 => Script::Sinhala, 0x0DD8..=0x0DDF => Script::Sinhala, 0x0DE6..=0x0DEF => Script::Sinhala, 0x0DF2..=0x0DF3 => Script::Sinhala, 0x0DF4 => Script::Sinhala, 0x111E1..=0x111F4 => Script::Sinhala, 0x0E01..=0x0E30 => Script::Thai, 0x0E31 => Script::Thai, 0x0E32..=0x0E33 => Script::Thai, 0x0E34..=0x0E3A => Script::Thai, 0x0E40..=0x0E45 => Script::Thai, 0x0E46 => Script::Thai, 0x0E47..=0x0E4E => Script::Thai, 0x0E4F => Script::Thai, 0x0E50..=0x0E59 => Script::Thai, 0x0E5A..=0x0E5B => Script::Thai, 0x0E81..=0x0E82 => Script::Lao, 0x0E84 => Script::Lao, 0x0E87..=0x0E88 => Script::Lao, 0x0E8A => Script::Lao, 0x0E8D => Script::Lao, 0x0E94..=0x0E97 => Script::Lao, 0x0E99..=0x0E9F => Script::Lao, 0x0EA1..=0x0EA3 => Script::Lao, 0x0EA5 => Script::Lao, 0x0EA7 => Script::Lao, 0x0EAA..=0x0EAB => Script::Lao, 0x0EAD..=0x0EB0 => Script::Lao, 0x0EB1 => Script::Lao, 0x0EB2..=0x0EB3 => Script::Lao, 0x0EB4..=0x0EB9 => Script::Lao, 0x0EBB..=0x0EBC => Script::Lao, 0x0EBD => Script::Lao, 0x0EC0..=0x0EC4 => Script::Lao, 0x0EC6 => Script::Lao, 0x0EC8..=0x0ECD => Script::Lao, 0x0ED0..=0x0ED9 => Script::Lao, 0x0EDC..=0x0EDF => Script::Lao, 0x0F00 => Script::Tibetan, 0x0F01..=0x0F03 => Script::Tibetan, 0x0F04..=0x0F12 => Script::Tibetan, 0x0F13 => Script::Tibetan, 0x0F14 => Script::Tibetan, 0x0F15..=0x0F17 => Script::Tibetan, 0x0F18..=0x0F19 => Script::Tibetan, 0x0F1A..=0x0F1F => Script::Tibetan, 0x0F20..=0x0F29 => Script::Tibetan, 0x0F2A..=0x0F33 => Script::Tibetan, 0x0F34 => Script::Tibetan, 0x0F35 => Script::Tibetan, 0x0F36 => Script::Tibetan, 0x0F37 => Script::Tibetan, 0x0F38 => Script::Tibetan, 0x0F39 => Script::Tibetan, 0x0F3A => Script::Tibetan, 0x0F3B => Script::Tibetan, 0x0F3C => Script::Tibetan, 0x0F3D => Script::Tibetan, 0x0F3E..=0x0F3F => Script::Tibetan, 0x0F40..=0x0F47 => Script::Tibetan, 0x0F49..=0x0F6C => Script::Tibetan, 0x0F71..=0x0F7E => Script::Tibetan, 0x0F7F => Script::Tibetan, 0x0F80..=0x0F84 => Script::Tibetan, 0x0F85 => Script::Tibetan, 0x0F86..=0x0F87 => Script::Tibetan, 0x0F88..=0x0F8C => Script::Tibetan, 0x0F8D..=0x0F97 => Script::Tibetan, 0x0F99..=0x0FBC => Script::Tibetan, 0x0FBE..=0x0FC5 => Script::Tibetan, 0x0FC6 => Script::Tibetan, 0x0FC7..=0x0FCC => Script::Tibetan, 0x0FCE..=0x0FCF => Script::Tibetan, 0x0FD0..=0x0FD4 => Script::Tibetan, 0x0FD9..=0x0FDA => Script::Tibetan, 0x1000..=0x102A => Script::Myanmar, 0x102B..=0x102C => Script::Myanmar, 0x102D..=0x1030 => Script::Myanmar, 0x1031 => Script::Myanmar, 0x1032..=0x1037 => Script::Myanmar, 0x1038 => Script::Myanmar, 0x1039..=0x103A => Script::Myanmar, 0x103B..=0x103C => Script::Myanmar, 0x103D..=0x103E => Script::Myanmar, 0x103F => Script::Myanmar, 0x1040..=0x1049 => Script::Myanmar, 0x104A..=0x104F => Script::Myanmar, 0x1050..=0x1055 => Script::Myanmar, 0x1056..=0x1057 => Script::Myanmar, 0x1058..=0x1059 => Script::Myanmar, 0x105A..=0x105D => Script::Myanmar, 0x105E..=0x1060 => Script::Myanmar, 0x1061 => Script::Myanmar, 0x1062..=0x1064 => Script::Myanmar, 0x1065..=0x1066 => Script::Myanmar, 0x1067..=0x106D => Script::Myanmar, 0x106E..=0x1070 => Script::Myanmar, 0x1071..=0x1074 => Script::Myanmar, 0x1075..=0x1081 => Script::Myanmar, 0x1082 => Script::Myanmar, 0x1083..=0x1084 => Script::Myanmar, 0x1085..=0x1086 => Script::Myanmar, 0x1087..=0x108C => Script::Myanmar, 0x108D => Script::Myanmar, 0x108E => Script::Myanmar, 0x108F => Script::Myanmar, 0x1090..=0x1099 => Script::Myanmar, 0x109A..=0x109C => Script::Myanmar, 0x109D => Script::Myanmar, 0x109E..=0x109F => Script::Myanmar, 0xA9E0..=0xA9E4 => Script::Myanmar, 0xA9E5 => Script::Myanmar, 0xA9E6 => Script::Myanmar, 0xA9E7..=0xA9EF => Script::Myanmar, 0xA9F0..=0xA9F9 => Script::Myanmar, 0xA9FA..=0xA9FE => Script::Myanmar, 0xAA60..=0xAA6F => Script::Myanmar, 0xAA70 => Script::Myanmar, 0xAA71..=0xAA76 => Script::Myanmar, 0xAA77..=0xAA79 => Script::Myanmar, 0xAA7A => Script::Myanmar, 0xAA7B => Script::Myanmar, 0xAA7C => Script::Myanmar, 0xAA7D => Script::Myanmar, 0xAA7E..=0xAA7F => Script::Myanmar, 0x10A0..=0x10C5 => Script::Georgian, 0x10C7 => Script::Georgian, 0x10CD => Script::Georgian, 0x10D0..=0x10FA => Script::Georgian, 0x10FC => Script::Georgian, 0x10FD..=0x10FF => Script::Georgian, 0x2D00..=0x2D25 => Script::Georgian, 0x2D27 => Script::Georgian, 0x2D2D => Script::Georgian, 0x1100..=0x11FF => Script::Hangul, 0x302E..=0x302F => Script::Hangul, 0x3131..=0x318E => Script::Hangul, 0x3200..=0x321E => Script::Hangul, 0x3260..=0x327E => Script::Hangul, 0xA960..=0xA97C => Script::Hangul, 0xAC00..=0xD7A3 => Script::Hangul, 0xD7B0..=0xD7C6 => Script::Hangul, 0xD7CB..=0xD7FB => Script::Hangul, 0xFFA0..=0xFFBE => Script::Hangul, 0xFFC2..=0xFFC7 => Script::Hangul, 0xFFCA..=0xFFCF => Script::Hangul, 0xFFD2..=0xFFD7 => Script::Hangul, 0xFFDA..=0xFFDC => Script::Hangul, 0x1200..=0x1248 => Script::Ethiopic, 0x124A..=0x124D => Script::Ethiopic, 0x1250..=0x1256 => Script::Ethiopic, 0x1258 => Script::Ethiopic, 0x125A..=0x125D => Script::Ethiopic, 0x1260..=0x1288 => Script::Ethiopic, 0x128A..=0x128D => Script::Ethiopic, 0x1290..=0x12B0 => Script::Ethiopic, 0x12B2..=0x12B5 => Script::Ethiopic, 0x12B8..=0x12BE => Script::Ethiopic, 0x12C0 => Script::Ethiopic, 0x12C2..=0x12C5 => Script::Ethiopic, 0x12C8..=0x12D6 => Script::Ethiopic, 0x12D8..=0x1310 => Script::Ethiopic, 0x1312..=0x1315 => Script::Ethiopic, 0x1318..=0x135A => Script::Ethiopic, 0x135D..=0x135F => Script::Ethiopic, 0x1360..=0x1368 => Script::Ethiopic, 0x1369..=0x137C => Script::Ethiopic, 0x1380..=0x138F => Script::Ethiopic, 0x1390..=0x1399 => Script::Ethiopic, 0x2D80..=0x2D96 => Script::Ethiopic, 0x2DA0..=0x2DA6 => Script::Ethiopic, 0x2DA8..=0x2DAE => Script::Ethiopic, 0x2DB0..=0x2DB6 => Script::Ethiopic, 0x2DB8..=0x2DBE => Script::Ethiopic, 0x2DC0..=0x2DC6 => Script::Ethiopic, 0x2DC8..=0x2DCE => Script::Ethiopic, 0x2DD0..=0x2DD6 => Script::Ethiopic, 0x2DD8..=0x2DDE => Script::Ethiopic, 0xAB01..=0xAB06 => Script::Ethiopic, 0xAB09..=0xAB0E => Script::Ethiopic, 0xAB11..=0xAB16 => Script::Ethiopic, 0xAB20..=0xAB26 => Script::Ethiopic, 0xAB28..=0xAB2E => Script::Ethiopic, 0x13A0..=0x13F5 => Script::Cherokee, 0x13F8..=0x13FD => Script::Cherokee, 0xAB70..=0xABBF => Script::Cherokee, 0x1400 => Script::CanadianAboriginal, 0x1401..=0x166C => Script::CanadianAboriginal, 0x166D..=0x166E => Script::CanadianAboriginal, 0x166F..=0x167F => Script::CanadianAboriginal, 0x18B0..=0x18F5 => Script::CanadianAboriginal, 0x1680 => Script::Ogham, 0x1681..=0x169A => Script::Ogham, 0x169B => Script::Ogham, 0x169C => Script::Ogham, 0x16A0..=0x16EA => Script::Runic, 0x16EE..=0x16F0 => Script::Runic, 0x16F1..=0x16F8 => Script::Runic, 0x1780..=0x17B3 => Script::Khmer, 0x17B4..=0x17B5 => Script::Khmer, 0x17B6 => Script::Khmer, 0x17B7..=0x17BD => Script::Khmer, 0x17BE..=0x17C5 => Script::Khmer, 0x17C6 => Script::Khmer, 0x17C7..=0x17C8 => Script::Khmer, 0x17C9..=0x17D3 => Script::Khmer, 0x17D4..=0x17D6 => Script::Khmer, 0x17D7 => Script::Khmer, 0x17D8..=0x17DA => Script::Khmer, 0x17DB => Script::Khmer, 0x17DC => Script::Khmer, 0x17DD => Script::Khmer, 0x17E0..=0x17E9 => Script::Khmer, 0x17F0..=0x17F9 => Script::Khmer, 0x19E0..=0x19FF => Script::Khmer, 0x1800..=0x1801 => Script::Mongolian, 0x1804 => Script::Mongolian, 0x1806 => Script::Mongolian, 0x1807..=0x180A => Script::Mongolian, 0x180B..=0x180D => Script::Mongolian, 0x180E => Script::Mongolian, 0x1810..=0x1819 => Script::Mongolian, 0x1820..=0x1842 => Script::Mongolian, 0x1843 => Script::Mongolian, 0x1844..=0x1877 => Script::Mongolian, 0x1880..=0x1884 => Script::Mongolian, 0x1885..=0x1886 => Script::Mongolian, 0x1887..=0x18A8 => Script::Mongolian, 0x18A9 => Script::Mongolian, 0x18AA => Script::Mongolian, 0x11660..=0x1166C => Script::Mongolian, 0x3041..=0x3096 => Script::Hiragana, 0x309D..=0x309E => Script::Hiragana, 0x309F => Script::Hiragana, 0x1B001 => Script::Hiragana, 0x1F200 => Script::Hiragana, 0x30A1..=0x30FA => Script::Katakana, 0x30FD..=0x30FE => Script::Katakana, 0x30FF => Script::Katakana, 0x31F0..=0x31FF => Script::Katakana, 0x32D0..=0x32FE => Script::Katakana, 0x3300..=0x3357 => Script::Katakana, 0xFF66..=0xFF6F => Script::Katakana, 0xFF71..=0xFF9D => Script::Katakana, 0x1B000 => Script::Katakana, 0x02EA..=0x02EB => Script::Bopomofo, 0x3105..=0x312D => Script::Bopomofo, 0x31A0..=0x31BA => Script::Bopomofo, 0x2E80..=0x2E99 => Script::Han, 0x2E9B..=0x2EF3 => Script::Han, 0x2F00..=0x2FD5 => Script::Han, 0x3005 => Script::Han, 0x3007 => Script::Han, 0x3021..=0x3029 => Script::Han, 0x3038..=0x303A => Script::Han, 0x303B => Script::Han, 0x3400..=0x4DB5 => Script::Han, 0x4E00..=0x9FD5 => Script::Han, 0xF900..=0xFA6D => Script::Han, 0xFA70..=0xFAD9 => Script::Han, 0x20000..=0x2A6D6 => Script::Han, 0x2A700..=0x2B734 => Script::Han, 0x2B740..=0x2B81D => Script::Han, 0x2B820..=0x2CEA1 => Script::Han, 0x2F800..=0x2FA1D => Script::Han, 0xA000..=0xA014 => Script::Yi, 0xA015 => Script::Yi, 0xA016..=0xA48C => Script::Yi, 0xA490..=0xA4C6 => Script::Yi, 0x10300..=0x1031F => Script::OldItalic, 0x10320..=0x10323 => Script::OldItalic, 0x10330..=0x10340 => Script::Gothic, 0x10341 => Script::Gothic, 0x10342..=0x10349 => Script::Gothic, 0x1034A => Script::Gothic, 0x10400..=0x1044F => Script::Deseret, 0x0300..=0x036F => Script::Inherited, 0x0485..=0x0486 => Script::Inherited, 0x064B..=0x0655 => Script::Inherited, 0x0670 => Script::Inherited, 0x0951..=0x0952 => Script::Inherited, 0x1AB0..=0x1ABD => Script::Inherited, 0x1ABE => Script::Inherited, 0x1CD0..=0x1CD2 => Script::Inherited, 0x1CD4..=0x1CE0 => Script::Inherited, 0x1CE2..=0x1CE8 => Script::Inherited, 0x1CED => Script::Inherited, 0x1CF4 => Script::Inherited, 0x1CF8..=0x1CF9 => Script::Inherited, 0x1DC0..=0x1DF5 => Script::Inherited, 0x1DFB..=0x1DFF => Script::Inherited, 0x200C..=0x200D => Script::Inherited, 0x20D0..=0x20DC => Script::Inherited, 0x20DD..=0x20E0 => Script::Inherited, 0x20E1 => Script::Inherited, 0x20E2..=0x20E4 => Script::Inherited, 0x20E5..=0x20F0 => Script::Inherited, 0x302A..=0x302D => Script::Inherited, 0x3099..=0x309A => Script::Inherited, 0xFE00..=0xFE0F => Script::Inherited, 0xFE20..=0xFE2D => Script::Inherited, 0x101FD => Script::Inherited, 0x102E0 => Script::Inherited, 0x1D167..=0x1D169 => Script::Inherited, 0x1D17B..=0x1D182 => Script::Inherited, 0x1D185..=0x1D18B => Script::Inherited, 0x1D1AA..=0x1D1AD => Script::Inherited, 0xE0100..=0xE01EF => Script::Inherited, 0x1700..=0x170C => Script::Tagalog, 0x170E..=0x1711 => Script::Tagalog, 0x1712..=0x1714 => Script::Tagalog, 0x1720..=0x1731 => Script::Hanunoo, 0x1732..=0x1734 => Script::Hanunoo, 0x1740..=0x1751 => Script::Buhid, 0x1752..=0x1753 => Script::Buhid, 0x1760..=0x176C => Script::Tagbanwa, 0x176E..=0x1770 => Script::Tagbanwa, 0x1772..=0x1773 => Script::Tagbanwa, 0x1900..=0x191E => Script::Limbu, 0x1920..=0x1922 => Script::Limbu, 0x1923..=0x1926 => Script::Limbu, 0x1927..=0x1928 => Script::Limbu, 0x1929..=0x192B => Script::Limbu, 0x1930..=0x1931 => Script::Limbu, 0x1932 => Script::Limbu, 0x1933..=0x1938 => Script::Limbu, 0x1939..=0x193B => Script::Limbu, 0x1940 => Script::Limbu, 0x1944..=0x1945 => Script::Limbu, 0x1946..=0x194F => Script::Limbu, 0x1950..=0x196D => Script::TaiLe, 0x1970..=0x1974 => Script::TaiLe, 0x10000..=0x1000B => Script::LinearB, 0x1000D..=0x10026 => Script::LinearB, 0x10028..=0x1003A => Script::LinearB, 0x1003C..=0x1003D => Script::LinearB, 0x1003F..=0x1004D => Script::LinearB, 0x10050..=0x1005D => Script::LinearB, 0x10080..=0x100FA => Script::LinearB, 0x10380..=0x1039D => Script::Ugaritic, 0x1039F => Script::Ugaritic, 0x10450..=0x1047F => Script::Shavian, 0x10480..=0x1049D => Script::Osmanya, 0x104A0..=0x104A9 => Script::Osmanya, 0x10800..=0x10805 => Script::Cypriot, 0x10808 => Script::Cypriot, 0x1080A..=0x10835 => Script::Cypriot, 0x10837..=0x10838 => Script::Cypriot, 0x1083C => Script::Cypriot, 0x1083F => Script::Cypriot, 0x2800..=0x28FF => Script::Braille, 0x1A00..=0x1A16 => Script::Buginese, 0x1A17..=0x1A18 => Script::Buginese, 0x1A19..=0x1A1A => Script::Buginese, 0x1A1B => Script::Buginese, 0x1A1E..=0x1A1F => Script::Buginese, 0x03E2..=0x03EF => Script::Coptic, 0x2C80..=0x2CE4 => Script::Coptic, 0x2CE5..=0x2CEA => Script::Coptic, 0x2CEB..=0x2CEE => Script::Coptic, 0x2CEF..=0x2CF1 => Script::Coptic, 0x2CF2..=0x2CF3 => Script::Coptic, 0x2CF9..=0x2CFC => Script::Coptic, 0x2CFD => Script::Coptic, 0x2CFE..=0x2CFF => Script::Coptic, 0x1980..=0x19AB => Script::NewTaiLue, 0x19B0..=0x19C9 => Script::NewTaiLue, 0x19D0..=0x19D9 => Script::NewTaiLue, 0x19DA => Script::NewTaiLue, 0x19DE..=0x19DF => Script::NewTaiLue, 0x2C00..=0x2C2E => Script::Glagolitic, 0x2C30..=0x2C5E => Script::Glagolitic, 0x1E000..=0x1E006 => Script::Glagolitic, 0x1E008..=0x1E018 => Script::Glagolitic, 0x1E01B..=0x1E021 => Script::Glagolitic, 0x1E023..=0x1E024 => Script::Glagolitic, 0x1E026..=0x1E02A => Script::Glagolitic, 0x2D30..=0x2D67 => Script::Tifinagh, 0x2D6F => Script::Tifinagh, 0x2D70 => Script::Tifinagh, 0x2D7F => Script::Tifinagh, 0xA800..=0xA801 => Script::SylotiNagri, 0xA802 => Script::SylotiNagri, 0xA803..=0xA805 => Script::SylotiNagri, 0xA806 => Script::SylotiNagri, 0xA807..=0xA80A => Script::SylotiNagri, 0xA80B => Script::SylotiNagri, 0xA80C..=0xA822 => Script::SylotiNagri, 0xA823..=0xA824 => Script::SylotiNagri, 0xA825..=0xA826 => Script::SylotiNagri, 0xA827 => Script::SylotiNagri, 0xA828..=0xA82B => Script::SylotiNagri, 0x103A0..=0x103C3 => Script::OldPersian, 0x103C8..=0x103CF => Script::OldPersian, 0x103D0 => Script::OldPersian, 0x103D1..=0x103D5 => Script::OldPersian, 0x10A00 => Script::Kharoshthi, 0x10A01..=0x10A03 => Script::Kharoshthi, 0x10A05..=0x10A06 => Script::Kharoshthi, 0x10A0C..=0x10A0F => Script::Kharoshthi, 0x10A10..=0x10A13 => Script::Kharoshthi, 0x10A15..=0x10A17 => Script::Kharoshthi, 0x10A19..=0x10A33 => Script::Kharoshthi, 0x10A38..=0x10A3A => Script::Kharoshthi, 0x10A3F => Script::Kharoshthi, 0x10A40..=0x10A47 => Script::Kharoshthi, 0x10A50..=0x10A58 => Script::Kharoshthi, 0x1B00..=0x1B03 => Script::Balinese, 0x1B04 => Script::Balinese, 0x1B05..=0x1B33 => Script::Balinese, 0x1B34 => Script::Balinese, 0x1B35 => Script::Balinese, 0x1B36..=0x1B3A => Script::Balinese, 0x1B3B => Script::Balinese, 0x1B3C => Script::Balinese, 0x1B3D..=0x1B41 => Script::Balinese, 0x1B42 => Script::Balinese, 0x1B43..=0x1B44 => Script::Balinese, 0x1B45..=0x1B4B => Script::Balinese, 0x1B50..=0x1B59 => Script::Balinese, 0x1B5A..=0x1B60 => Script::Balinese, 0x1B61..=0x1B6A => Script::Balinese, 0x1B6B..=0x1B73 => Script::Balinese, 0x1B74..=0x1B7C => Script::Balinese, 0x12000..=0x12399 => Script::Cuneiform, 0x12400..=0x1246E => Script::Cuneiform, 0x12470..=0x12474 => Script::Cuneiform, 0x12480..=0x12543 => Script::Cuneiform, 0x10900..=0x10915 => Script::Phoenician, 0x10916..=0x1091B => Script::Phoenician, 0x1091F => Script::Phoenician, 0xA840..=0xA873 => Script::PhagsPa, 0xA874..=0xA877 => Script::PhagsPa, 0x07C0..=0x07C9 => Script::Nko, 0x07CA..=0x07EA => Script::Nko, 0x07EB..=0x07F3 => Script::Nko, 0x07F4..=0x07F5 => Script::Nko, 0x07F6 => Script::Nko, 0x07F7..=0x07F9 => Script::Nko, 0x07FA => Script::Nko, 0x1B80..=0x1B81 => Script::Sundanese, 0x1B82 => Script::Sundanese, 0x1B83..=0x1BA0 => Script::Sundanese, 0x1BA1 => Script::Sundanese, 0x1BA2..=0x1BA5 => Script::Sundanese, 0x1BA6..=0x1BA7 => Script::Sundanese, 0x1BA8..=0x1BA9 => Script::Sundanese, 0x1BAA => Script::Sundanese, 0x1BAB..=0x1BAD => Script::Sundanese, 0x1BAE..=0x1BAF => Script::Sundanese, 0x1BB0..=0x1BB9 => Script::Sundanese, 0x1BBA..=0x1BBF => Script::Sundanese, 0x1CC0..=0x1CC7 => Script::Sundanese, 0x1C00..=0x1C23 => Script::Lepcha, 0x1C24..=0x1C2B => Script::Lepcha, 0x1C2C..=0x1C33 => Script::Lepcha, 0x1C34..=0x1C35 => Script::Lepcha, 0x1C36..=0x1C37 => Script::Lepcha, 0x1C3B..=0x1C3F => Script::Lepcha, 0x1C40..=0x1C49 => Script::Lepcha, 0x1C4D..=0x1C4F => Script::Lepcha, 0x1C50..=0x1C59 => Script::OlChiki, 0x1C5A..=0x1C77 => Script::OlChiki, 0x1C78..=0x1C7D => Script::OlChiki, 0x1C7E..=0x1C7F => Script::OlChiki, 0xA500..=0xA60B => Script::Vai, 0xA60C => Script::Vai, 0xA60D..=0xA60F => Script::Vai, 0xA610..=0xA61F => Script::Vai, 0xA620..=0xA629 => Script::Vai, 0xA62A..=0xA62B => Script::Vai, 0xA880..=0xA881 => Script::Saurashtra, 0xA882..=0xA8B3 => Script::Saurashtra, 0xA8B4..=0xA8C3 => Script::Saurashtra, 0xA8C4..=0xA8C5 => Script::Saurashtra, 0xA8CE..=0xA8CF => Script::Saurashtra, 0xA8D0..=0xA8D9 => Script::Saurashtra, 0xA900..=0xA909 => Script::KayahLi, 0xA90A..=0xA925 => Script::KayahLi, 0xA926..=0xA92D => Script::KayahLi, 0xA92F => Script::KayahLi, 0xA930..=0xA946 => Script::Rejang, 0xA947..=0xA951 => Script::Rejang, 0xA952..=0xA953 => Script::Rejang, 0xA95F => Script::Rejang, 0x10280..=0x1029C => Script::Lycian, 0x102A0..=0x102D0 => Script::Carian, 0x10920..=0x10939 => Script::Lydian, 0x1093F => Script::Lydian, 0xAA00..=0xAA28 => Script::Cham, 0xAA29..=0xAA2E => Script::Cham, 0xAA2F..=0xAA30 => Script::Cham, 0xAA31..=0xAA32 => Script::Cham, 0xAA33..=0xAA34 => Script::Cham, 0xAA35..=0xAA36 => Script::Cham, 0xAA40..=0xAA42 => Script::Cham, 0xAA43 => Script::Cham, 0xAA44..=0xAA4B => Script::Cham, 0xAA4C => Script::Cham, 0xAA4D => Script::Cham, 0xAA50..=0xAA59 => Script::Cham, 0xAA5C..=0xAA5F => Script::Cham, 0x1A20..=0x1A54 => Script::TaiTham, 0x1A55 => Script::TaiTham, 0x1A56 => Script::TaiTham, 0x1A57 => Script::TaiTham, 0x1A58..=0x1A5E => Script::TaiTham, 0x1A60 => Script::TaiTham, 0x1A61 => Script::TaiTham, 0x1A62 => Script::TaiTham, 0x1A63..=0x1A64 => Script::TaiTham, 0x1A65..=0x1A6C => Script::TaiTham, 0x1A6D..=0x1A72 => Script::TaiTham, 0x1A73..=0x1A7C => Script::TaiTham, 0x1A7F => Script::TaiTham, 0x1A80..=0x1A89 => Script::TaiTham, 0x1A90..=0x1A99 => Script::TaiTham, 0x1AA0..=0x1AA6 => Script::TaiTham, 0x1AA7 => Script::TaiTham, 0x1AA8..=0x1AAD => Script::TaiTham, 0xAA80..=0xAAAF => Script::TaiViet, 0xAAB0 => Script::TaiViet, 0xAAB1 => Script::TaiViet, 0xAAB2..=0xAAB4 => Script::TaiViet, 0xAAB5..=0xAAB6 => Script::TaiViet, 0xAAB7..=0xAAB8 => Script::TaiViet, 0xAAB9..=0xAABD => Script::TaiViet, 0xAABE..=0xAABF => Script::TaiViet, 0xAAC0 => Script::TaiViet, 0xAAC1 => Script::TaiViet, 0xAAC2 => Script::TaiViet, 0xAADB..=0xAADC => Script::TaiViet, 0xAADD => Script::TaiViet, 0xAADE..=0xAADF => Script::TaiViet, 0x10B00..=0x10B35 => Script::Avestan, 0x10B39..=0x10B3F => Script::Avestan, 0x13000..=0x1342E => Script::EgyptianHieroglyphs, 0x0800..=0x0815 => Script::Samaritan, 0x0816..=0x0819 => Script::Samaritan, 0x081A => Script::Samaritan, 0x081B..=0x0823 => Script::Samaritan, 0x0824 => Script::Samaritan, 0x0825..=0x0827 => Script::Samaritan, 0x0828 => Script::Samaritan, 0x0829..=0x082D => Script::Samaritan, 0x0830..=0x083E => Script::Samaritan, 0xA4D0..=0xA4F7 => Script::Lisu, 0xA4F8..=0xA4FD => Script::Lisu, 0xA4FE..=0xA4FF => Script::Lisu, 0xA6A0..=0xA6E5 => Script::Bamum, 0xA6E6..=0xA6EF => Script::Bamum, 0xA6F0..=0xA6F1 => Script::Bamum, 0xA6F2..=0xA6F7 => Script::Bamum, 0x16800..=0x16A38 => Script::Bamum, 0xA980..=0xA982 => Script::Javanese, 0xA983 => Script::Javanese, 0xA984..=0xA9B2 => Script::Javanese, 0xA9B3 => Script::Javanese, 0xA9B4..=0xA9B5 => Script::Javanese, 0xA9B6..=0xA9B9 => Script::Javanese, 0xA9BA..=0xA9BB => Script::Javanese, 0xA9BC => Script::Javanese, 0xA9BD..=0xA9C0 => Script::Javanese, 0xA9C1..=0xA9CD => Script::Javanese, 0xA9D0..=0xA9D9 => Script::Javanese, 0xA9DE..=0xA9DF => Script::Javanese, 0xAAE0..=0xAAEA => Script::MeeteiMayek, 0xAAEB => Script::MeeteiMayek, 0xAAEC..=0xAAED => Script::MeeteiMayek, 0xAAEE..=0xAAEF => Script::MeeteiMayek, 0xAAF0..=0xAAF1 => Script::MeeteiMayek, 0xAAF2 => Script::MeeteiMayek, 0xAAF3..=0xAAF4 => Script::MeeteiMayek, 0xAAF5 => Script::MeeteiMayek, 0xAAF6 => Script::MeeteiMayek, 0xABC0..=0xABE2 => Script::MeeteiMayek, 0xABE3..=0xABE4 => Script::MeeteiMayek, 0xABE5 => Script::MeeteiMayek, 0xABE6..=0xABE7 => Script::MeeteiMayek, 0xABE8 => Script::MeeteiMayek, 0xABE9..=0xABEA => Script::MeeteiMayek, 0xABEB => Script::MeeteiMayek, 0xABEC => Script::MeeteiMayek, 0xABED => Script::MeeteiMayek, 0xABF0..=0xABF9 => Script::MeeteiMayek, 0x10840..=0x10855 => Script::ImperialAramaic, 0x10857 => Script::ImperialAramaic, 0x10858..=0x1085F => Script::ImperialAramaic, 0x10A60..=0x10A7C => Script::OldSouthArabian, 0x10A7D..=0x10A7E => Script::OldSouthArabian, 0x10A7F => Script::OldSouthArabian, 0x10B40..=0x10B55 => Script::InscriptionalParthian, 0x10B58..=0x10B5F => Script::InscriptionalParthian, 0x10B60..=0x10B72 => Script::InscriptionalPahlavi, 0x10B78..=0x10B7F => Script::InscriptionalPahlavi, 0x10C00..=0x10C48 => Script::OldTurkic, 0x11080..=0x11081 => Script::Kaithi, 0x11082 => Script::Kaithi, 0x11083..=0x110AF => Script::Kaithi, 0x110B0..=0x110B2 => Script::Kaithi, 0x110B3..=0x110B6 => Script::Kaithi, 0x110B7..=0x110B8 => Script::Kaithi, 0x110B9..=0x110BA => Script::Kaithi, 0x110BB..=0x110BC => Script::Kaithi, 0x110BD => Script::Kaithi, 0x110BE..=0x110C1 => Script::Kaithi, 0x1BC0..=0x1BE5 => Script::Batak, 0x1BE6 => Script::Batak, 0x1BE7 => Script::Batak, 0x1BE8..=0x1BE9 => Script::Batak, 0x1BEA..=0x1BEC => Script::Batak, 0x1BED => Script::Batak, 0x1BEE => Script::Batak, 0x1BEF..=0x1BF1 => Script::Batak, 0x1BF2..=0x1BF3 => Script::Batak, 0x1BFC..=0x1BFF => Script::Batak, 0x11000 => Script::Brahmi, 0x11001 => Script::Brahmi, 0x11002 => Script::Brahmi, 0x11003..=0x11037 => Script::Brahmi, 0x11038..=0x11046 => Script::Brahmi, 0x11047..=0x1104D => Script::Brahmi, 0x11052..=0x11065 => Script::Brahmi, 0x11066..=0x1106F => Script::Brahmi, 0x1107F => Script::Brahmi, 0x0840..=0x0858 => Script::Mandaic, 0x0859..=0x085B => Script::Mandaic, 0x085E => Script::Mandaic, 0x11100..=0x11102 => Script::Chakma, 0x11103..=0x11126 => Script::Chakma, 0x11127..=0x1112B => Script::Chakma, 0x1112C => Script::Chakma, 0x1112D..=0x11134 => Script::Chakma, 0x11136..=0x1113F => Script::Chakma, 0x11140..=0x11143 => Script::Chakma, 0x109A0..=0x109B7 => Script::MeroiticCursive, 0x109BC..=0x109BD => Script::MeroiticCursive, 0x109BE..=0x109BF => Script::MeroiticCursive, 0x109C0..=0x109CF => Script::MeroiticCursive, 0x109D2..=0x109FF => Script::MeroiticCursive, 0x10980..=0x1099F => Script::MeroiticHieroglyphs, 0x16F00..=0x16F44 => Script::Miao, 0x16F50 => Script::Miao, 0x16F51..=0x16F7E => Script::Miao, 0x16F8F..=0x16F92 => Script::Miao, 0x16F93..=0x16F9F => Script::Miao, 0x11180..=0x11181 => Script::Sharada, 0x11182 => Script::Sharada, 0x11183..=0x111B2 => Script::Sharada, 0x111B3..=0x111B5 => Script::Sharada, 0x111B6..=0x111BE => Script::Sharada, 0x111BF..=0x111C0 => Script::Sharada, 0x111C1..=0x111C4 => Script::Sharada, 0x111C5..=0x111C9 => Script::Sharada, 0x111CA..=0x111CC => Script::Sharada, 0x111CD => Script::Sharada, 0x111D0..=0x111D9 => Script::Sharada, 0x111DA => Script::Sharada, 0x111DB => Script::Sharada, 0x111DC => Script::Sharada, 0x111DD..=0x111DF => Script::Sharada, 0x110D0..=0x110E8 => Script::SoraSompeng, 0x110F0..=0x110F9 => Script::SoraSompeng, 0x11680..=0x116AA => Script::Takri, 0x116AB => Script::Takri, 0x116AC => Script::Takri, 0x116AD => Script::Takri, 0x116AE..=0x116AF => Script::Takri, 0x116B0..=0x116B5 => Script::Takri, 0x116B6 => Script::Takri, 0x116B7 => Script::Takri, 0x116C0..=0x116C9 => Script::Takri, 0x10530..=0x10563 => Script::CaucasianAlbanian, 0x1056F => Script::CaucasianAlbanian, 0x16AD0..=0x16AED => Script::BassaVah, 0x16AF0..=0x16AF4 => Script::BassaVah, 0x16AF5 => Script::BassaVah, 0x1BC00..=0x1BC6A => Script::Duployan, 0x1BC70..=0x1BC7C => Script::Duployan, 0x1BC80..=0x1BC88 => Script::Duployan, 0x1BC90..=0x1BC99 => Script::Duployan, 0x1BC9C => Script::Duployan, 0x1BC9D..=0x1BC9E => Script::Duployan, 0x1BC9F => Script::Duployan, 0x10500..=0x10527 => Script::Elbasan, 0x11300..=0x11301 => Script::Grantha, 0x11302..=0x11303 => Script::Grantha, 0x11305..=0x1130C => Script::Grantha, 0x1130F..=0x11310 => Script::Grantha, 0x11313..=0x11328 => Script::Grantha, 0x1132A..=0x11330 => Script::Grantha, 0x11332..=0x11333 => Script::Grantha, 0x11335..=0x11339 => Script::Grantha, 0x1133C => Script::Grantha, 0x1133D => Script::Grantha, 0x1133E..=0x1133F => Script::Grantha, 0x11340 => Script::Grantha, 0x11341..=0x11344 => Script::Grantha, 0x11347..=0x11348 => Script::Grantha, 0x1134B..=0x1134D => Script::Grantha, 0x11350 => Script::Grantha, 0x11357 => Script::Grantha, 0x1135D..=0x11361 => Script::Grantha, 0x11362..=0x11363 => Script::Grantha, 0x11366..=0x1136C => Script::Grantha, 0x11370..=0x11374 => Script::Grantha, 0x16B00..=0x16B2F => Script::PahawhHmong, 0x16B30..=0x16B36 => Script::PahawhHmong, 0x16B37..=0x16B3B => Script::PahawhHmong, 0x16B3C..=0x16B3F => Script::PahawhHmong, 0x16B40..=0x16B43 => Script::PahawhHmong, 0x16B44 => Script::PahawhHmong, 0x16B45 => Script::PahawhHmong, 0x16B50..=0x16B59 => Script::PahawhHmong, 0x16B5B..=0x16B61 => Script::PahawhHmong, 0x16B63..=0x16B77 => Script::PahawhHmong, 0x16B7D..=0x16B8F => Script::PahawhHmong, 0x11200..=0x11211 => Script::Khojki, 0x11213..=0x1122B => Script::Khojki, 0x1122C..=0x1122E => Script::Khojki, 0x1122F..=0x11231 => Script::Khojki, 0x11232..=0x11233 => Script::Khojki, 0x11234 => Script::Khojki, 0x11235 => Script::Khojki, 0x11236..=0x11237 => Script::Khojki, 0x11238..=0x1123D => Script::Khojki, 0x1123E => Script::Khojki, 0x10600..=0x10736 => Script::LinearA, 0x10740..=0x10755 => Script::LinearA, 0x10760..=0x10767 => Script::LinearA, 0x11150..=0x11172 => Script::Mahajani, 0x11173 => Script::Mahajani, 0x11174..=0x11175 => Script::Mahajani, 0x11176 => Script::Mahajani, 0x10AC0..=0x10AC7 => Script::Manichaean, 0x10AC8 => Script::Manichaean, 0x10AC9..=0x10AE4 => Script::Manichaean, 0x10AE5..=0x10AE6 => Script::Manichaean, 0x10AEB..=0x10AEF => Script::Manichaean, 0x10AF0..=0x10AF6 => Script::Manichaean, 0x1E800..=0x1E8C4 => Script::MendeKikakui, 0x1E8C7..=0x1E8CF => Script::MendeKikakui, 0x1E8D0..=0x1E8D6 => Script::MendeKikakui, 0x11600..=0x1162F => Script::Modi, 0x11630..=0x11632 => Script::Modi, 0x11633..=0x1163A => Script::Modi, 0x1163B..=0x1163C => Script::Modi, 0x1163D => Script::Modi, 0x1163E => Script::Modi, 0x1163F..=0x11640 => Script::Modi, 0x11641..=0x11643 => Script::Modi, 0x11644 => Script::Modi, 0x11650..=0x11659 => Script::Modi, 0x16A40..=0x16A5E => Script::Mro, 0x16A60..=0x16A69 => Script::Mro, 0x16A6E..=0x16A6F => Script::Mro, 0x10A80..=0x10A9C => Script::OldNorthArabian, 0x10A9D..=0x10A9F => Script::OldNorthArabian, 0x10880..=0x1089E => Script::Nabataean, 0x108A7..=0x108AF => Script::Nabataean, 0x10860..=0x10876 => Script::Palmyrene, 0x10877..=0x10878 => Script::Palmyrene, 0x10879..=0x1087F => Script::Palmyrene, 0x11AC0..=0x11AF8 => Script::PauCinHau, 0x10350..=0x10375 => Script::OldPermic, 0x10376..=0x1037A => Script::OldPermic, 0x10B80..=0x10B91 => Script::PsalterPahlavi, 0x10B99..=0x10B9C => Script::PsalterPahlavi, 0x10BA9..=0x10BAF => Script::PsalterPahlavi, 0x11580..=0x115AE => Script::Siddham, 0x115AF..=0x115B1 => Script::Siddham, 0x115B2..=0x115B5 => Script::Siddham, 0x115B8..=0x115BB => Script::Siddham, 0x115BC..=0x115BD => Script::Siddham, 0x115BE => Script::Siddham, 0x115BF..=0x115C0 => Script::Siddham, 0x115C1..=0x115D7 => Script::Siddham, 0x115D8..=0x115DB => Script::Siddham, 0x115DC..=0x115DD => Script::Siddham, 0x112B0..=0x112DE => Script::Khudawadi, 0x112DF => Script::Khudawadi, 0x112E0..=0x112E2 => Script::Khudawadi, 0x112E3..=0x112EA => Script::Khudawadi, 0x112F0..=0x112F9 => Script::Khudawadi, 0x11480..=0x114AF => Script::Tirhuta, 0x114B0..=0x114B2 => Script::Tirhuta, 0x114B3..=0x114B8 => Script::Tirhuta, 0x114B9 => Script::Tirhuta, 0x114BA => Script::Tirhuta, 0x114BB..=0x114BE => Script::Tirhuta, 0x114BF..=0x114C0 => Script::Tirhuta, 0x114C1 => Script::Tirhuta, 0x114C2..=0x114C3 => Script::Tirhuta, 0x114C4..=0x114C5 => Script::Tirhuta, 0x114C6 => Script::Tirhuta, 0x114C7 => Script::Tirhuta, 0x114D0..=0x114D9 => Script::Tirhuta, 0x118A0..=0x118DF => Script::WarangCiti, 0x118E0..=0x118E9 => Script::WarangCiti, 0x118EA..=0x118F2 => Script::WarangCiti, 0x118FF => Script::WarangCiti, 0x11700..=0x11719 => Script::Ahom, 0x1171D..=0x1171F => Script::Ahom, 0x11720..=0x11721 => Script::Ahom, 0x11722..=0x11725 => Script::Ahom, 0x11726 => Script::Ahom, 0x11727..=0x1172B => Script::Ahom, 0x11730..=0x11739 => Script::Ahom, 0x1173A..=0x1173B => Script::Ahom, 0x1173C..=0x1173E => Script::Ahom, 0x1173F => Script::Ahom, 0x14400..=0x14646 => Script::AnatolianHieroglyphs, 0x108E0..=0x108F2 => Script::Hatran, 0x108F4..=0x108F5 => Script::Hatran, 0x108FB..=0x108FF => Script::Hatran, 0x11280..=0x11286 => Script::Multani, 0x11288 => Script::Multani, 0x1128A..=0x1128D => Script::Multani, 0x1128F..=0x1129D => Script::Multani, 0x1129F..=0x112A8 => Script::Multani, 0x112A9 => Script::Multani, 0x10C80..=0x10CB2 => Script::OldHungarian, 0x10CC0..=0x10CF2 => Script::OldHungarian, 0x10CFA..=0x10CFF => Script::OldHungarian, 0x1D800..=0x1D9FF => Script::SignWriting, 0x1DA00..=0x1DA36 => Script::SignWriting, 0x1DA37..=0x1DA3A => Script::SignWriting, 0x1DA3B..=0x1DA6C => Script::SignWriting, 0x1DA6D..=0x1DA74 => Script::SignWriting, 0x1DA75 => Script::SignWriting, 0x1DA76..=0x1DA83 => Script::SignWriting, 0x1DA84 => Script::SignWriting, 0x1DA85..=0x1DA86 => Script::SignWriting, 0x1DA87..=0x1DA8B => Script::SignWriting, 0x1DA9B..=0x1DA9F => Script::SignWriting, 0x1DAA1..=0x1DAAF => Script::SignWriting, 0x1E900..=0x1E943 => Script::Adlam, 0x1E944..=0x1E94A => Script::Adlam, 0x1E950..=0x1E959 => Script::Adlam, 0x1E95E..=0x1E95F => Script::Adlam, 0x11C00..=0x11C08 => Script::Bhaiksuki, 0x11C0A..=0x11C2E => Script::Bhaiksuki, 0x11C2F => Script::Bhaiksuki, 0x11C30..=0x11C36 => Script::Bhaiksuki, 0x11C38..=0x11C3D => Script::Bhaiksuki, 0x11C3E => Script::Bhaiksuki, 0x11C3F => Script::Bhaiksuki, 0x11C40 => Script::Bhaiksuki, 0x11C41..=0x11C45 => Script::Bhaiksuki, 0x11C50..=0x11C59 => Script::Bhaiksuki, 0x11C5A..=0x11C6C => Script::Bhaiksuki, 0x11C70..=0x11C71 => Script::Marchen, 0x11C72..=0x11C8F => Script::Marchen, 0x11C92..=0x11CA7 => Script::Marchen, 0x11CA9 => Script::Marchen, 0x11CAA..=0x11CB0 => Script::Marchen, 0x11CB1 => Script::Marchen, 0x11CB2..=0x11CB3 => Script::Marchen, 0x11CB4 => Script::Marchen, 0x11CB5..=0x11CB6 => Script::Marchen, 0x11400..=0x11434 => Script::Newa, 0x11435..=0x11437 => Script::Newa, 0x11438..=0x1143F => Script::Newa, 0x11440..=0x11441 => Script::Newa, 0x11442..=0x11444 => Script::Newa, 0x11445 => Script::Newa, 0x11446 => Script::Newa, 0x11447..=0x1144A => Script::Newa, 0x1144B..=0x1144F => Script::Newa, 0x11450..=0x11459 => Script::Newa, 0x1145B => Script::Newa, 0x1145D => Script::Newa, 0x104B0..=0x104D3 => Script::Osage, 0x104D8..=0x104FB => Script::Osage, 0x16FE0 => Script::Tangut, 0x17000..=0x187EC => Script::Tangut, 0x18800..=0x18AF2 => Script::Tangut, _ => Script::Any, } } #[cfg(test)] mod tests { use super::*; #[test] fn test_unicode_script() { assert_eq!(Script::Han, get_script('京')); assert_eq!(Script::Han, get_script('太')); assert_eq!(Script::Hiragana, get_script('い')); assert_eq!(Script::Katakana, get_script('グ')); assert_eq!(Script::Common, get_script('ー')); assert_eq!(Script::Latin, get_script('a')); assert_eq!(Script::Latin, get_script('A')); assert_eq!(Script::Common, get_script('0')); assert_eq!(Script::Common, get_script('$')); assert_eq!(Script::Common, get_script('@')); assert_eq!(Script::Common, get_script('-')); assert_eq!(Script::Common, get_script(' ')); assert_eq!(Script::Common, get_script('�')); } }
tokenizers/tokenizers/src/pre_tokenizers/unicode_scripts/scripts.rs/0
{ "file_path": "tokenizers/tokenizers/src/pre_tokenizers/unicode_scripts/scripts.rs", "repo_id": "tokenizers", "token_count": 46440 }
341
use crate::Result; use hf_hub::{api::sync::ApiBuilder, Repo, RepoType}; use std::collections::HashMap; use std::path::PathBuf; /// Defines the additional parameters available for the `from_pretrained` function #[derive(Debug, Clone)] pub struct FromPretrainedParameters { pub revision: String, pub user_agent: HashMap<String, String>, pub token: Option<String>, } impl Default for FromPretrainedParameters { fn default() -> Self { Self { revision: "main".into(), user_agent: HashMap::new(), token: None, } } } /// Downloads and cache the identified tokenizer if it exists on /// the Hugging Face Hub, and returns a local path to the file pub fn from_pretrained<S: AsRef<str>>( identifier: S, params: Option<FromPretrainedParameters>, ) -> Result<PathBuf> { let identifier: String = identifier.as_ref().to_string(); let valid_chars = ['-', '_', '.', '/']; let is_valid_char = |x: char| x.is_alphanumeric() || valid_chars.contains(&x); let valid = identifier.chars().all(is_valid_char); let valid_chars_stringified = valid_chars .iter() .fold(vec![], |mut buf, x| { buf.push(format!("'{x}'")); buf }) .join(", "); // "'/', '-', '_', '.'" if !valid { return Err(format!( "Model \"{identifier}\" contains invalid characters, expected only alphanumeric or {valid_chars_stringified}" ) .into()); } let params = params.unwrap_or_default(); let revision = &params.revision; let valid_revision = revision.chars().all(is_valid_char); if !valid_revision { return Err(format!( "Revision \"{revision}\" contains invalid characters, expected only alphanumeric or {valid_chars_stringified}" ) .into()); } let mut builder = ApiBuilder::from_env(); if let Some(token) = params.token { builder = builder.with_token(Some(token)); } let api = builder.build()?; let repo = Repo::with_revision(identifier, RepoType::Model, params.revision); let api = api.repo(repo); Ok(api.get("tokenizer.json")?) }
tokenizers/tokenizers/src/utils/from_pretrained.rs/0
{ "file_path": "tokenizers/tokenizers/src/utils/from_pretrained.rs", "repo_id": "tokenizers", "token_count": 884 }
342
#[cfg(not(debug_assertions))] use assert_approx_eq::assert_approx_eq; use std::collections::HashMap; use std::fs::read_to_string; use std::path::Path; #[cfg(not(debug_assertions))] use tokenizers::models::unigram::Lattice; use tokenizers::models::unigram::Unigram; use tokenizers::models::unigram::UnigramTrainer; use tokenizers::tokenizer::Model; #[test] fn test_unigram_from_file() { let model = Unigram::load(Path::new("data/unigram.json")).unwrap(); let string = "吾輩《わがはい》は猫である。名前はまだ無い。"; assert_eq!( model .tokenize(string) .unwrap() .iter() .map(|tok| tok.value.clone()) .collect::<Vec<_>>(), vec![ "吾輩", "《", "わが", "はい", "》", "は", "猫", "である", "。", "名前", "はまだ", "無い", "。" ] ); } #[test] fn test_train_unigram_from_file() { let content = read_to_string("data/small.txt").unwrap(); let mut word_counts = HashMap::new(); content.split_whitespace().for_each(|word| { // This is important for the test of char vs u8 let word = format!("▁{word}"); *word_counts.entry(word).or_insert(0) += 1; }); // println!("Words counts {:?}", word_counts); let trainer = UnigramTrainer::builder() .show_progress(false) .unk_token(Some("<UNK>".into())) .build() .unwrap(); let mut model = Unigram::default(); let sentences: Vec<_> = word_counts .iter() .map(|(s, i)| (s.to_owned(), *i)) .collect(); trainer.do_train(sentences, &mut model).unwrap(); assert_eq!(model.get_vocab_size(), 719); } #[cfg(not(debug_assertions))] #[test] fn test_sample() { let mut lattice = Lattice::from("ABC", 0, 2); lattice.insert(0, 1, 1.0, 3); // A lattice.insert(1, 1, 1.2, 4); // B lattice.insert(2, 1, 1.5, 5); // C lattice.insert(0, 2, 1.6, 6); // AB lattice.insert(1, 2, 1.7, 7); // BC lattice.insert(0, 3, 1.8, 8); // ABC let thetas: Vec<f64> = vec![0.0, 0.01, 0.5, 0.7, 1.0]; for theta in thetas { let mut probs: HashMap<String, f64> = HashMap::new(); probs.insert("A B C".to_string(), (theta * (1.0 + 1.2 + 1.5)).exp()); probs.insert("AB C".to_string(), (theta * (1.6 + 1.5)).exp()); probs.insert("A BC".to_string(), (theta * (1.0 + 1.7)).exp()); probs.insert("ABC".to_string(), (theta * (1.8)).exp()); // Computes expected probabilities. let mut z = 0.0; for (_, p) in probs.iter() { z += p; } for (_, p) in probs.iter_mut() { *p /= z; } let n_trials = 10_000; let mut freq: HashMap<String, u32> = HashMap::new(); for _ in 0..n_trials { let string = lattice.sample_token(theta).join(" "); *freq.entry(string).or_insert(0) += 1; } assert_eq!(freq.len(), probs.len()); for (s, p) in probs.iter() { assert_approx_eq!(1.0 * (freq[s] as f64) / (n_trials as f64), p, 0.03) } } }
tokenizers/tokenizers/tests/unigram.rs/0
{ "file_path": "tokenizers/tokenizers/tests/unigram.rs", "repo_id": "tokenizers", "token_count": 1697 }
343
{ "source": { "excludePattern": "" } }
transformers.js/docs/jsdoc-conf.json/0
{ "file_path": "transformers.js/docs/jsdoc-conf.json", "repo_id": "transformers.js", "token_count": 30 }
344
# Running models on WebGPU WebGPU is a new web standard for accelerated graphics and compute. The [API](https://developer.mozilla.org/en-US/docs/Web/API/WebGPU_API) enables web developers to use the underlying system's GPU to carry out high-performance computations directly in the browser. WebGPU is the successor to [WebGL](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API) and provides significantly better performance, because it allows for more direct interaction with modern GPUs. Lastly, it supports general-purpose GPU computations, which makes it just perfect for machine learning! > [!WARNING] > As of October 2024, global WebGPU support is around 70% (according to [caniuse.com](https://caniuse.com/webgpu)), meaning some users may not be able to use the API. > > If the following demos do not work in your browser, you may need to enable it using a feature flag: > > - Firefox: with the `dom.webgpu.enabled` flag (see [here](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Experimental_features#:~:text=tested%20by%20Firefox.-,WebGPU%20API,-The%20WebGPU%20API)). > - Safari: with the `WebGPU` feature flag (see [here](https://webkit.org/blog/14879/webgpu-now-available-for-testing-in-safari-technology-preview/)). > - Older Chromium browsers (on Windows, macOS, Linux): with the `enable-unsafe-webgpu` flag (see [here](https://developer.chrome.com/docs/web-platform/webgpu/troubleshooting-tips)). ## Usage in Transformers.js v3 Thanks to our collaboration with [ONNX Runtime Web](https://www.npmjs.com/package/onnxruntime-web), enabling WebGPU acceleration is as simple as setting `device: 'webgpu'` when loading a model. Let's see some examples! **Example:** Compute text embeddings on WebGPU ([demo](https://v2.scrimba.com/s06a2smeej)) ```js import { pipeline } from "@huggingface/transformers"; // Create a feature-extraction pipeline const extractor = await pipeline( "feature-extraction", "mixedbread-ai/mxbai-embed-xsmall-v1", { device: "webgpu" }, ); // Compute embeddings const texts = ["Hello world!", "This is an example sentence."]; const embeddings = await extractor(texts, { pooling: "mean", normalize: true }); console.log(embeddings.tolist()); // [ // [-0.016986183822155, 0.03228696808218956, -0.0013630966423079371, ... ], // [0.09050482511520386, 0.07207386940717697, 0.05762749910354614, ... ], // ] ``` **Example:** Perform automatic speech recognition with OpenAI whisper on WebGPU ([demo](https://v2.scrimba.com/s0oi76h82g)) ```js import { pipeline } from "@huggingface/transformers"; // Create automatic speech recognition pipeline const transcriber = await pipeline( "automatic-speech-recognition", "onnx-community/whisper-tiny.en", { device: "webgpu" }, ); // Transcribe audio from a URL const url = "https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav"; const output = await transcriber(url); console.log(output); // { text: ' And so my fellow Americans ask not what your country can do for you, ask what you can do for your country.' } ``` **Example:** Perform image classification with MobileNetV4 on WebGPU ([demo](https://v2.scrimba.com/s0fv2uab1t)) ```js import { pipeline } from "@huggingface/transformers"; // Create image classification pipeline const classifier = await pipeline( "image-classification", "onnx-community/mobilenetv4_conv_small.e2400_r224_in1k", { device: "webgpu" }, ); // Classify an image from a URL const url = "https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg"; const output = await classifier(url); console.log(output); // [ // { label: 'tiger, Panthera tigris', score: 0.6149784922599792 }, // { label: 'tiger cat', score: 0.30281734466552734 }, // { label: 'tabby, tabby cat', score: 0.0019135422771796584 }, // { label: 'lynx, catamount', score: 0.0012161266058683395 }, // { label: 'Egyptian cat', score: 0.0011465961579233408 } // ] ``` ## Reporting bugs and providing feedback Due to the experimental nature of WebGPU, especially in non-Chromium browsers, you may experience issues when trying to run a model (even it it can run in WASM). If you do, please open [an issue on GitHub](https://github.com/huggingface/transformers.js/issues/new?title=[WebGPU]%20Error%20running%20MODEL_GOES_HERE&assignees=&labels=bug,webgpu&projects=&template=1_bug-report.yml) and we'll do our best to address it. Thanks!
transformers.js/docs/source/guides/webgpu.md/0
{ "file_path": "transformers.js/docs/source/guides/webgpu.md", "repo_id": "transformers.js", "token_count": 1452 }
345
function formatBytes(bytes, decimals = 0) { const sizes = ["Bytes", "KB", "MB", "GB", "TB"]; if (bytes === 0) return "0 Bytes"; const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1000)), 10); const rounded = (bytes / Math.pow(1000, i)).toFixed(decimals); return rounded + " " + sizes[i]; } export default function Progress({ data }) { const progress = data.progress ?? 0; const text = data.file; const a = formatBytes(data.loaded); const b = formatBytes(data.total); return ( <div className="progress-container"> <div className='progress-bar' style={{ 'width': `${progress}%` }}>{text} ({`${a} / ${b}`})</div> </div> ); }
transformers.js/examples/code-completion/src/components/Progress.jsx/0
{ "file_path": "transformers.js/examples/code-completion/src/components/Progress.jsx", "repo_id": "transformers.js", "token_count": 278 }
346
import { env, AutoTokenizer, AutoModelForSequenceClassification } from '@xenova/transformers'; // Skip local model check since we are downloading the model from the Hugging Face Hub. env.allowLocalModels = false; class CrossEncoderSingleton { static model_id = 'mixedbread-ai/mxbai-rerank-xsmall-v1'; static model = null; static tokenizer = null; static async getInstance(progress_callback) { if (!this.tokenizer) { this.tokenizer = AutoTokenizer.from_pretrained(this.model_id); } if (!this.model) { this.model = AutoModelForSequenceClassification.from_pretrained(this.model_id, { quantized: true, progress_callback, }); } return Promise.all([this.tokenizer, this.model]); } } // Listen for messages from the main thread self.addEventListener('message', async (event) => { // Retrieve the pipeline. When called for the first time, // this will load the pipeline and save it for future use. const [tokenizer, model] = await CrossEncoderSingleton.getInstance(x => { // We also add a progress callback to the pipeline so that we can // track model loading. self.postMessage(x); }); const { query, documents } = event.data; const docs = documents.trim().split('\n'); const inputs = tokenizer( new Array(docs.length).fill(query), { text_pair: docs, padding: true, truncation: true, } ) const { logits } = await model(inputs); const output = logits .sigmoid() .tolist() .map(([score], i) => ({ corpus_id: i, score, text: docs[i], })) .sort((a, b) => b.score - a.score); // Send the output back to the main thread self.postMessage({ status: 'complete', output }); });
transformers.js/examples/cross-encoder/src/worker.js/0
{ "file_path": "transformers.js/examples/cross-encoder/src/worker.js", "repo_id": "transformers.js", "token_count": 786 }
347
// Adapted from https://www.npmjs.com/package/audiobuffer-to-wav export function encodeWAV(samples, sampleRate = 16000) { let offset = 44; const buffer = new ArrayBuffer(offset + samples.length * 4); const view = new DataView(buffer); /* RIFF identifier */ writeString(view, 0, 'RIFF') /* RIFF chunk length */ view.setUint32(4, 36 + samples.length * 4, true) /* RIFF type */ writeString(view, 8, 'WAVE') /* format chunk identifier */ writeString(view, 12, 'fmt ') /* format chunk length */ view.setUint32(16, 16, true) /* sample format (raw) */ view.setUint16(20, 3, true) /* channel count */ view.setUint16(22, 1, true) /* sample rate */ view.setUint32(24, sampleRate, true) /* byte rate (sample rate * block align) */ view.setUint32(28, sampleRate * 4, true) /* block align (channel count * bytes per sample) */ view.setUint16(32, 4, true) /* bits per sample */ view.setUint16(34, 32, true) /* data chunk identifier */ writeString(view, 36, 'data') /* data chunk length */ view.setUint32(40, samples.length * 4, true) for (let i = 0; i < samples.length; ++i, offset += 4) { view.setFloat32(offset, samples[i], true) } return buffer } function writeString(view, offset, string) { for (let i = 0; i < string.length; ++i) { view.setUint8(offset + i, string.charCodeAt(i)) } } export async function share(body, settings) { const response = await fetch('https://huggingface.co/uploads', { method: 'POST', body }); if (!response.ok) throw new Error(`Failed to upload audio: ${response.statusText}`); const url = await response.text(); const params = new URLSearchParams({ title: `🎵 ${settings.prompt}`, description: `<audio controls src="${url}"></audio>\n${JSON.stringify(settings, null, 2)}`, }); const shareURL = `https://huggingface.co/spaces/Xenova/musicgen-web/discussions/new?${params.toString()}`; window.open(shareURL, '_blank'); }
transformers.js/examples/musicgen-web/src/utils.js/0
{ "file_path": "transformers.js/examples/musicgen-web/src/utils.js", "repo_id": "transformers.js", "token_count": 787 }
348
'use client' import { useState, useEffect, useRef, useCallback } from 'react' export default function Home() { // Keep track of the classification result and the model loading status. const [result, setResult] = useState(null); const [ready, setReady] = useState(null); // Create a reference to the worker object. const worker = useRef(null); // We use the `useEffect` hook to set up the worker as soon as the `App` component is mounted. useEffect(() => { if (!worker.current) { // Create the worker if it does not yet exist. worker.current = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' }); } // Create a callback function for messages from the worker thread. const onMessageReceived = (e) => { switch (e.data.status) { case 'initiate': setReady(false); break; case 'ready': setReady(true); break; case 'complete': setResult(e.data.output[0]) break; } }; // Attach the callback function as an event listener. worker.current.addEventListener('message', onMessageReceived); // Define a cleanup function for when the component is unmounted. return () => worker.current.removeEventListener('message', onMessageReceived); }); const classify = useCallback((text) => { if (worker.current) { worker.current.postMessage({ text }); } }, []); return ( <main className="flex min-h-screen flex-col items-center justify-center p-12"> <h1 className="text-5xl font-bold mb-2 text-center">Transformers.js</h1> <h2 className="text-2xl mb-4 text-center">Next.js template (client-side)</h2> <input type="text" className="w-full max-w-xs p-2 border border-gray-300 rounded mb-4" placeholder="Enter text here" onInput={e => { classify(e.target.value); }} /> {ready !== null && ( <pre className="bg-gray-100 p-2 rounded"> { (!ready || !result) ? 'Loading...' : JSON.stringify(result, null, 2)} </pre> )} </main> ) }
transformers.js/examples/next-client/src/app/page.js/0
{ "file_path": "transformers.js/examples/next-client/src/app/page.js", "repo_id": "transformers.js", "token_count": 858 }
349
import { useEffect, useRef, useState } from 'react' import LanguageSelector from './components/LanguageSelector'; import Progress from './components/Progress'; import './App.css' function App() { // Model loading const [ready, setReady] = useState(null); const [disabled, setDisabled] = useState(false); const [progressItems, setProgressItems] = useState([]); // Inputs and outputs const [input, setInput] = useState('I love walking my dog.'); const [sourceLanguage, setSourceLanguage] = useState('eng_Latn'); const [targetLanguage, setTargetLanguage] = useState('fra_Latn'); const [output, setOutput] = useState(''); // Create a reference to the worker object. const worker = useRef(null); // We use the `useEffect` hook to setup the worker as soon as the `App` component is mounted. useEffect(() => { if (!worker.current) { // Create the worker if it does not yet exist. worker.current = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' }); } // Create a callback function for messages from the worker thread. const onMessageReceived = (e) => { switch (e.data.status) { case 'initiate': // Model file start load: add a new progress item to the list. setReady(false); setProgressItems(prev => [...prev, e.data]); break; case 'progress': // Model file progress: update one of the progress items. setProgressItems( prev => prev.map(item => { if (item.file === e.data.file) { return { ...item, progress: e.data.progress } } return item; }) ); break; case 'done': // Model file loaded: remove the progress item from the list. setProgressItems( prev => prev.filter(item => item.file !== e.data.file) ); break; case 'ready': // Pipeline ready: the worker is ready to accept messages. setReady(true); break; case 'update': // Generation update: update the output text. setOutput(e.data.output); break; case 'complete': // Generation complete: re-enable the "Translate" button setDisabled(false); break; } }; // Attach the callback function as an event listener. worker.current.addEventListener('message', onMessageReceived); // Define a cleanup function for when the component is unmounted. return () => worker.current.removeEventListener('message', onMessageReceived); }); const translate = () => { setDisabled(true); worker.current.postMessage({ text: input, src_lang: sourceLanguage, tgt_lang: targetLanguage, }); } return ( <> <h1>Transformers.js</h1> <h2>ML-powered multilingual translation in React!</h2> <div className='container'> <div className='language-container'> <LanguageSelector type={"Source"} defaultLanguage={"eng_Latn"} onChange={x => setSourceLanguage(x.target.value)} /> <LanguageSelector type={"Target"} defaultLanguage={"fra_Latn"} onChange={x => setTargetLanguage(x.target.value)} /> </div> <div className='textbox-container'> <textarea value={input} rows={3} onChange={e => setInput(e.target.value)}></textarea> <textarea value={output} rows={3} readOnly></textarea> </div> </div> <button disabled={disabled} onClick={translate}>Translate</button> <div className='progress-bars-container'> {ready === false && ( <label>Loading models... (only run once)</label> )} {progressItems.map(data => ( <div key={data.file}> <Progress text={data.file} percentage={data.progress} /> </div> ))} </div> </> ) } export default App
transformers.js/examples/react-translator/src/App.jsx/0
{ "file_path": "transformers.js/examples/react-translator/src/App.jsx", "repo_id": "transformers.js", "token_count": 1595 }
350
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="stylesheet" href="index.css" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Transformers.js - Segment Anything WebGPU</title> </head> <body> <h1>Segment Anything WebGPU</h1> <h3>In-browser image segmentation w/ <a href="https://hf.co/docs/transformers.js" target="_blank">🤗 Transformers.js</a></h3> <div id="container"> <label id="upload-button" for="upload"> <svg width="25" height="25" viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill="#000" d="M3.5 24.3a3 3 0 0 1-1.9-.8c-.5-.5-.8-1.2-.8-1.9V2.9c0-.7.3-1.3.8-1.9.6-.5 1.2-.7 2-.7h18.6c.7 0 1.3.2 1.9.7.5.6.7 1.2.7 2v18.6c0 .7-.2 1.4-.7 1.9a3 3 0 0 1-2 .8H3.6Zm0-2.7h18.7V2.9H3.5v18.7Zm2.7-2.7h13.3c.3 0 .5 0 .6-.3v-.7l-3.7-5a.6.6 0 0 0-.6-.2c-.2 0-.4 0-.5.3l-3.5 4.6-2.4-3.3a.6.6 0 0 0-.6-.3c-.2 0-.4.1-.5.3l-2.7 3.6c-.1.2-.2.4 0 .7.1.2.3.3.6.3Z"> </path> </svg> Click to upload image <label id="example">(or try example)</label> </label> <canvas id="mask-output"></canvas> </div> <label id="status"></label> <div id="controls"> <button id="reset-image">Reset image</button> <button id="clear-points">Clear points</button> <button id="cut-mask" disabled>Cut mask</button> </div> <p id="information"> Left click = positive points, right click = negative points. </p> <input id="upload" type="file" accept="image/*" /> <script src="index.js" type="module"></script> </body> </html>
transformers.js/examples/segment-anything-client/index.html/0
{ "file_path": "transformers.js/examples/segment-anything-client/index.html", "repo_id": "transformers.js", "token_count": 893 }
351
{ "compilerOptions": { "paths": { "@/*": ["./src/*"] } } }
transformers.js/examples/semantic-image-search-client/jsconfig.json/0
{ "file_path": "transformers.js/examples/semantic-image-search-client/jsconfig.json", "repo_id": "transformers.js", "token_count": 44 }
352
/** @type {import('tailwindcss').Config} */ module.exports = { content: [ './src/pages/**/*.{js,ts,jsx,tsx,mdx}', './src/components/**/*.{js,ts,jsx,tsx,mdx}', './src/app/**/*.{js,ts,jsx,tsx,mdx}', ], theme: { extend: { boxShadow: { highlight: 'inset 0 0 0 1px rgba(255, 255, 255, 0.1)', }, }, }, plugins: [], }
transformers.js/examples/semantic-image-search-client/tailwind.config.js/0
{ "file_path": "transformers.js/examples/semantic-image-search-client/tailwind.config.js", "repo_id": "transformers.js", "token_count": 188 }
353
import { downloadImage } from '../utils.js' import Image from 'next/image' export function Modal({ currentImage, setCurrentImage }) { return ( <div className='fixed inset-0 z-30 backdrop-blur-2xl w-full h-full bg-black top-0 left-0 transition' style={{ backgroundColor: `rgba(0, 0, 0, ${currentImage ? 0.8 : 0})`, opacity: currentImage ? 1 : 0, pointerEvents: currentImage ? 'auto' : 'none', }} > {currentImage && <> <Image alt={currentImage.photo_description || currentImage.ai_description || ""} className="transform rounded-lg transition will-change-auto" style={ { transform: 'translate3d(0, 0, 0)', } } layout={'fill'} objectFit={'contain'} src={currentImage.photo_image_url} unoptimized={true} /> <div className='absolute top-0 left-0 flex items-center gap-2 p-3 text-white' > <button onClick={() => setCurrentImage(null)} className="rounded-full bg-black/50 p-2 text-white/75 backdrop-blur-lg transition hover:bg-black/75 hover:text-white"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" aria-hidden="true" className="h-5 w-5"> <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"></path> </svg> </button> </div> <div className="absolute top-0 right-0 flex items-center gap-2 p-3 text-white"> <a href={currentImage.photo_url} className="rounded-full bg-black/50 p-2 text-white/75 backdrop-blur-lg transition hover:bg-black/75 hover:text-white" target="_blank" title="View on Unsplash" rel="noreferrer"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" aria-hidden="true" className="h-5 w-5"> <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 6H5.25A2.25 2.25 0 003 8.25v10.5A2.25 2.25 0 005.25 21h10.5A2.25 2.25 0 0018 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25"></path> </svg> </a> <button onClick={() => downloadImage(currentImage.photo_image_url, `${currentImage.photo_id}.png`)} className="rounded-full bg-black/50 p-2 text-white/75 backdrop-blur-lg transition hover:bg-black/75 hover:text-white" title="Download"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" aria-hidden="true" className="h-5 w-5"> <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3"> </path> </svg> </button> </div> </> } </div>) }
transformers.js/examples/semantic-image-search/src/app/components/Modal.jsx/0
{ "file_path": "transformers.js/examples/semantic-image-search/src/app/components/Modal.jsx", "repo_id": "transformers.js", "token_count": 1950 }
354
import { useEffect, useRef } from "react"; export default function AudioPlayer({ audioUrl, mimeType }) { const audioPlayer = useRef(null); const audioSource = useRef(null); // Updates src when url changes useEffect(() => { if (audioPlayer.current && audioSource.current) { audioSource.current.src = audioUrl; audioPlayer.current.load(); } }, [audioUrl]); return ( <div className='flex relative z-10 my-4 w-full'> <audio ref={audioPlayer} controls className='w-full h-14 rounded-lg bg-white shadow-xl shadow-black/5 ring-1 ring-slate-700/10' > <source ref={audioSource} type={mimeType}></source> </audio> </div> ); }
transformers.js/examples/text-to-speech-client/src/components/AudioPlayer.jsx/0
{ "file_path": "transformers.js/examples/text-to-speech-client/src/components/AudioPlayer.jsx", "repo_id": "transformers.js", "token_count": 369 }
355
#root { max-width: 1280px; width: 100%; margin: 0 auto; padding: 2rem; text-align: center; display: flex; justify-content: center; align-items: center; flex-direction: column; }
transformers.js/examples/tokenizer-playground/src/App.css/0
{ "file_path": "transformers.js/examples/tokenizer-playground/src/App.css", "repo_id": "transformers.js", "token_count": 73 }
356
export default function UserIcon(props) { return ( <svg {...props} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" > <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" /> <circle cx="12" cy="7" r="4" /> </svg> ) }
transformers.js/examples/webgpu-vlm/src/components/icons/UserIcon.jsx/0
{ "file_path": "transformers.js/examples/webgpu-vlm/src/components/icons/UserIcon.jsx", "repo_id": "transformers.js", "token_count": 313 }
357
def generate_tokenizer_json(tokenizer): vocab = tokenizer.vocab special_tokens_vocab = vocab if "<pad>" not in tokenizer.vocab: # For MMS tokenizers, the vocab is of the form: # { # language_id: { language_vocab } # } # So, to get the list of special tokens, we just get the english vocab special_tokens_vocab = vocab['eng'] tokenizer_json = { "version": "1.0", "truncation": None, "padding": None, "added_tokens": [ { "id": v, "content": k, "single_word": False, "lstrip": True, "rstrip": True, "normalized": False, "special": True } for k, v in special_tokens_vocab.items() if k.startswith('<') and k.endswith('>') ], "normalizer": { "type": "Replace", "pattern": { "String": " " }, "content": "|" }, "pre_tokenizer": { "type": "Split", "pattern": { "Regex": "" }, "behavior": "Isolated", "invert": False }, "post_processor": None, "decoder": { "type": "CTC", "pad_token": "<pad>", "word_delimiter_token": "|", "cleanup": True }, "model": { "vocab": vocab } } return tokenizer_json
transformers.js/scripts/extra/wav2vec2.py/0
{ "file_path": "transformers.js/scripts/extra/wav2vec2.py", "repo_id": "transformers.js", "token_count": 890 }
358
/** * @module generation/stopping_criteria */ import { Callable } from "../utils/generic.js"; // NOTE: // Stopping Criteria returns a list of `batch_size` booleans, indicating whether each sequence in the batch should be stopped. /** * Abstract base class for all stopping criteria that can be applied during generation. */ export class StoppingCriteria extends Callable { /** * * @param {number[][]} input_ids (`number[][]` of shape `(batch_size, sequence_length)`): * Indices of input sequence tokens in the vocabulary. * @param {number[][]} scores scores (`number[][]` of shape `(batch_size, config.vocab_size)`): * Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax * or scores for each vocabulary token after SoftMax. * @returns {boolean[]} A list of booleans indicating whether each sequence should be stopped. */ _call(input_ids, scores) { throw Error("StoppingCriteria needs to be subclassed"); } } /** */ export class StoppingCriteriaList extends Callable { /** * Constructs a new instance of `StoppingCriteriaList`. */ constructor() { super(); this.criteria = []; } /** * Adds a new stopping criterion to the list. * * @param {StoppingCriteria} item The stopping criterion to add. */ push(item) { this.criteria.push(item); } /** * Adds multiple stopping criteria to the list. * * @param {StoppingCriteria|StoppingCriteriaList|StoppingCriteria[]} items The stopping criteria to add. */ extend(items) { if (items instanceof StoppingCriteriaList) { items = items.criteria; } else if (items instanceof StoppingCriteria) { items = [items]; } this.criteria.push(...items); } _call(input_ids, scores) { const is_done = new Array(input_ids.length).fill(false); for (const criterion of this.criteria) { const criterion_done = criterion(input_ids, scores); for (let i = 0; i < is_done.length; ++i) { is_done[i] ||= criterion_done[i]; } } return is_done; } [Symbol.iterator]() { return this.criteria.values(); } } /** * This class can be used to stop generation whenever the full generated number of tokens exceeds `max_length`. * Keep in mind for decoder-only type of transformers, this will include the initial prompted tokens. */ export class MaxLengthCriteria extends StoppingCriteria { /** * * @param {number} max_length The maximum length that the output sequence can have in number of tokens. * @param {number} [max_position_embeddings=null] The maximum model length, as defined by the model's `config.max_position_embeddings` attribute. */ constructor(max_length, max_position_embeddings = null) { super(); this.max_length = max_length; this.max_position_embeddings = max_position_embeddings; } _call(input_ids) { return input_ids.map(ids => ids.length >= this.max_length); } } // TODO: add MaxTimeCriteria /** * This class can be used to stop generation whenever the "end-of-sequence" token is generated. * By default, it uses the `model.generation_config.eos_token_id`. */ export class EosTokenCriteria extends StoppingCriteria { /** * * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. * Optionally, use a list to set multiple *end-of-sequence* tokens. */ constructor(eos_token_id) { super(); if (!Array.isArray(eos_token_id)) { eos_token_id = [eos_token_id]; } this.eos_token_id = eos_token_id; } /** * * @param {number[][]} input_ids * @param {number[][]} scores * @returns {boolean[]} */ _call(input_ids, scores) { return input_ids.map(ids => { const last = ids.at(-1); // NOTE: We use == instead of === to allow for number/bigint comparison return this.eos_token_id.some(eos_id => last == eos_id); }); } } /** * This class can be used to stop generation whenever the user interrupts the process. */ export class InterruptableStoppingCriteria extends StoppingCriteria { constructor() { super(); this.interrupted = false; } interrupt() { this.interrupted = true; } reset() { this.interrupted = false; } _call(input_ids, scores) { return new Array(input_ids.length).fill(this.interrupted); } }
transformers.js/src/generation/stopping_criteria.js/0
{ "file_path": "transformers.js/src/generation/stopping_criteria.js", "repo_id": "transformers.js", "token_count": 1803 }
359
import { ImageProcessor, } from "../../base/image_processors_utils.js"; export class DINOv3ViTImageProcessor extends ImageProcessor { }
transformers.js/src/models/dinov3_vit/image_processing_dinov3_vit.js/0
{ "file_path": "transformers.js/src/models/dinov3_vit/image_processing_dinov3_vit.js", "repo_id": "transformers.js", "token_count": 49 }
360
import { Processor } from "../../base/processing_utils.js"; import { AutoImageProcessor } from "../auto/image_processing_auto.js"; import { AutoTokenizer } from "../../tokenizers.js"; import { mergeArrays } from "../../utils/core.js"; import { Tensor } from "../../utils/tensor.js"; import { RawImage } from "../../utils/image.js"; export class VLChatProcessor extends Processor { static image_processor_class = AutoImageProcessor static tokenizer_class = AutoTokenizer static uses_processor_config = true; constructor(config, components, chat_template) { super(config, components, chat_template); this.image_tag = this.config.image_tag; this.image_start_tag = this.config.image_start_tag; this.image_end_tag = this.config.image_end_tag; this.num_image_tokens = this.config.num_image_tokens; } /** * @typedef {Object} MultimodalMessageProperties Additional properties for multimodal messages. * @property {(RawImage | string | URL)[]} [images] The images in the message. * @typedef {(import('../../tokenizers.js').Message & MultimodalMessageProperties)[]} MultimodalConversation The conversation possibly containing multimodal inputs. */ /** * @typedef {Object} VLCChatProcessorResult The processed input. * @property {Tensor} input_ids The input IDs. * @property {Tensor} attention_mask The attention mask. * @property {Tensor} images_seq_mask The image sequence mask. * @property {Tensor} images_emb_mask The image embedding mask. */ /** * @param {MultimodalConversation} conversation The chat messages to process. * @param {Object} options Additional options for processing. * @param {RawImage|RawImage[]} [options.images] The images to process, if not set in the conversation. * @param {string} [options.chat_template="default"] The chat template to use. * @returns {Promise<VLCChatProcessorResult | VLCChatProcessorResult & import('../../base/image_processors_utils.js').ImageProcessorResult>} The processed input. */ async _call(conversation, { images = null, chat_template = "default", }={}) { if (!images) { images = await Promise.all( conversation .filter((msg) => msg.images) .flatMap((msg) => msg.images) .map((img) => RawImage.read(img)) ); } else if (!Array.isArray(images)) { images = [images]; } const tokenizer = this.tokenizer; const result = tokenizer.apply_chat_template(conversation, { tokenize: false, add_generation_prompt: true, chat_template, }); const encode = (text) => tokenizer.encode(text, { add_special_tokens: false }); const parts = (/** @type {string} */(result)) .split(this.image_tag); const num_images = parts.length - 1; if (images.length !== num_images) { throw new Error(`Number of images provided (${images.length}) does not match number of "${this.image_tag}" image tags (${num_images})`); } const [ image_placeholder_tag_id, image_start_tag_id, image_end_tag_id, ] = tokenizer.model.convert_tokens_to_ids([ this.image_tag, this.image_start_tag, this.image_end_tag, ]); let input_ids = encode(parts[0]); let images_seq_mask = new Array(input_ids.length).fill(false); for (let i = 1; i < parts.length; ++i) { const placeholder_image_tokens = new Array(this.num_image_tokens).fill(image_placeholder_tag_id); const tokens = encode(parts[i]); input_ids = mergeArrays( input_ids, [image_start_tag_id], placeholder_image_tokens, [image_end_tag_id], tokens, ); const image_mask = new Array(this.num_image_tokens).fill(true); images_seq_mask = mergeArrays( images_seq_mask, [false], image_mask, [false], new Array(tokens.length).fill(false), ); } const dims = [1, input_ids.length]; const final = { input_ids: new Tensor('int64', input_ids, dims), attention_mask: new Tensor('int64', new Array(input_ids.length).fill(1), dims), images_seq_mask: new Tensor('bool', images_seq_mask, dims), images_emb_mask: new Tensor( 'bool', new Array(num_images * this.num_image_tokens).fill(true), [1, num_images, this.num_image_tokens], ), } if (images && images.length > 0) { const image_inputs = await this.image_processor(images); // Set the batch_size dimension to 1 image_inputs.pixel_values.unsqueeze_(0); return { ...final, ...image_inputs }; } return final; } }
transformers.js/src/models/janus/processing_janus.js/0
{ "file_path": "transformers.js/src/models/janus/processing_janus.js", "repo_id": "transformers.js", "token_count": 2210 }
361
import { OwlViTImageProcessor } from "../owlvit/image_processing_owlvit.js"; // NOTE: extends OwlViTImageProcessor export class Owlv2ImageProcessor extends OwlViTImageProcessor { }
transformers.js/src/models/owlv2/image_processing_owlv2.js/0
{ "file_path": "transformers.js/src/models/owlv2/image_processing_owlv2.js", "repo_id": "transformers.js", "token_count": 58 }
362
import { FeatureExtractor, validate_audio_inputs } from '../../base/feature_extraction_utils.js'; import { Tensor } from '../../utils/tensor.js'; import { mel_filter_bank, spectrogram, window_function } from '../../utils/audio.js'; export class SeamlessM4TFeatureExtractor extends FeatureExtractor { constructor(config) { super(config); const sampling_rate = this.config.sampling_rate; const mel_filters = mel_filter_bank( 257, // num_frequency_bins this.config.num_mel_bins, // num_mel_filters 20, // min_frequency Math.floor(sampling_rate / 2), // max_frequency sampling_rate, // sampling_rate null, // norm "kaldi", // mel_scale true, // triangularize_in_mel_space ); this.mel_filters = mel_filters; this.window = window_function(400, 'povey', { periodic: false, }) } /** * Computes the log-Mel spectrogram of the provided audio waveform. * @param {Float32Array|Float64Array} waveform The audio waveform to process. * @param {number} max_length The maximum number of frames to return. * @returns {Promise<Tensor>} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. */ async _extract_fbank_features(waveform, max_length) { // NOTE: We don't pad/truncate since that is passed in as `max_num_frames` // Kaldi compliance: 16-bit signed integers // 32768 == 2 ** 15 waveform = waveform.map((/** @type {number} */ x) => x * 32768) return spectrogram( waveform, this.window, // window 400, // frame_length 160, // hop_length { fft_length: 512, power: 2.0, center: false, preemphasis: 0.97, mel_filters: this.mel_filters, log_mel: 'log', mel_floor: 1.192092955078125e-07, remove_dc_offset: true, // Custom max_num_frames: max_length, transpose: true, } ) } /** * Asynchronously extracts features from a given audio using the provided configuration. * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. * @param {Object} options Optional parameters for feature extraction. * @param {boolean} [options.padding=true] Whether to pad the sequence to a multiple of `pad_to_multiple_of`. * @param {number} [options.pad_to_multiple_of=2] The number to pad the sequence to a multiple of. * @param {boolean} [options.do_normalize_per_mel_bins=true] Whether or not to zero-mean unit-variance normalize the input per mel-channel. * @param {boolean} [options.return_attention_mask=true] Whether to return the attention mask. * @returns {Promise<{ input_features: Tensor, attention_mask?: Tensor }>} A Promise resolving to an object containing the extracted input features and attention masks as Tensors. */ async _call(audio, { padding = true, pad_to_multiple_of = 2, do_normalize_per_mel_bins = true, return_attention_mask = true, } = {}) { validate_audio_inputs(audio, 'SeamlessM4TFeatureExtractor'); let features = await this._extract_fbank_features(audio, this.config.max_length); if (do_normalize_per_mel_bins) { const [num_features, feature_size] = features.dims; const data = features.data; for (let i = 0; i < feature_size; ++i) { let sum = 0; for (let j = 0; j < num_features; ++j) { sum += data[j * feature_size + i]; } const mean = sum / num_features; let variance = 0; for (let j = 0; j < num_features; ++j) { variance += (data[j * feature_size + i] - mean) ** 2; } variance /= num_features - 1; // NOTE: We use ddof=1 const std = Math.sqrt(variance + 1e-7); for (let j = 0; j < num_features; ++j) { const index = j * feature_size + i; data[index] = (data[index] - mean) / std; } } } let padded_attention_mask; if (padding) { const [num_frames, num_channels] = features.dims; const data = /** @type {Float32Array} */(features.data); const pad_size = num_frames % pad_to_multiple_of; if (pad_size > 0) { const padded_data = new Float32Array(num_channels * (num_frames + pad_size)); padded_data.set(data) padded_data.fill(this.config.padding_value, data.length) const numPaddedFrames = num_frames + pad_size; features = new Tensor( features.type, padded_data, [numPaddedFrames, num_channels], ) if (return_attention_mask) { padded_attention_mask = new Tensor( 'int64', new BigInt64Array(numPaddedFrames), [1, numPaddedFrames], ); /** @type {BigInt64Array} */ (padded_attention_mask.data).fill(1n, 0, num_frames); } } } const [num_frames, num_channels] = features.dims; const stride = this.config.stride; const remainder = num_frames % stride; if (remainder !== 0) { throw new Error(`The number of frames (${num_frames}) must be a multiple of the stride (${stride}).`) } const input_features = features.view( 1, Math.floor(num_frames / stride), num_channels * stride, ); const result = { input_features } if (return_attention_mask) { const reshapedNumFrames = input_features.dims[1]; const attention_mask_data = new BigInt64Array(reshapedNumFrames); if (padded_attention_mask) { const padded_attention_mask_data = padded_attention_mask.data; for (let i = 1, j = 0; i < num_frames; i += stride, ++j) { attention_mask_data[j] = padded_attention_mask_data[i]; } } else { attention_mask_data.fill(1n); } result.attention_mask = new Tensor( 'int64', attention_mask_data, [1, reshapedNumFrames], ); } return result; } }
transformers.js/src/models/seamless_m4t/feature_extraction_seamless_m4t.js/0
{ "file_path": "transformers.js/src/models/seamless_m4t/feature_extraction_seamless_m4t.js", "repo_id": "transformers.js", "token_count": 3292 }
363
/// <reference types="@webgpu/types" /> import { apis } from "../env.js"; import { DEVICE_TYPES } from "./devices.js"; // TODO: Use the adapter from `env.backends.onnx.webgpu.adapter` to check for `shader-f16` support, // when available in https://github.com/microsoft/onnxruntime/pull/19940. // For more information, see https://github.com/microsoft/onnxruntime/pull/19857#issuecomment-1999984753 /** * Checks if WebGPU fp16 support is available in the current environment. */ export const isWebGpuFp16Supported = (function () { /** @type {boolean} */ let cachedResult; return async function () { if (cachedResult === undefined) { if (!apis.IS_WEBGPU_AVAILABLE) { cachedResult = false; } else { try { const adapter = await navigator.gpu.requestAdapter(); cachedResult = adapter.features.has('shader-f16'); } catch (e) { cachedResult = false; } } } return cachedResult; }; })(); export const DATA_TYPES = Object.freeze({ auto: 'auto', // Auto-detect based on environment fp32: 'fp32', fp16: 'fp16', q8: 'q8', int8: 'int8', uint8: 'uint8', q4: 'q4', bnb4: 'bnb4', q4f16: 'q4f16', // fp16 model with int4 block weight quantization }); /** @typedef {keyof typeof DATA_TYPES} DataType */ export const DEFAULT_DEVICE_DTYPE_MAPPING = Object.freeze({ // NOTE: If not specified, will default to fp32 [DEVICE_TYPES.wasm]: DATA_TYPES.q8, }); /** @type {Record<Exclude<DataType, "auto">, string>} */ export const DEFAULT_DTYPE_SUFFIX_MAPPING = Object.freeze({ [DATA_TYPES.fp32]: '', [DATA_TYPES.fp16]: '_fp16', [DATA_TYPES.int8]: '_int8', [DATA_TYPES.uint8]: '_uint8', [DATA_TYPES.q8]: '_quantized', [DATA_TYPES.q4]: '_q4', [DATA_TYPES.q4f16]: '_q4f16', [DATA_TYPES.bnb4]: '_bnb4', });
transformers.js/src/utils/dtypes.js/0
{ "file_path": "transformers.js/src/utils/dtypes.js", "repo_id": "transformers.js", "token_count": 904 }
364
import { AutoFeatureExtractor, ASTFeatureExtractor } from "../../../src/transformers.js"; import { load_cached_audio } from "../../asset_cache.js"; import { MAX_FEATURE_EXTRACTOR_LOAD_TIME, MAX_TEST_EXECUTION_TIME } from "../../init.js"; export default () => { // ASTFeatureExtractor describe("ASTFeatureExtractor", () => { const model_id = "Xenova/ast-finetuned-audioset-10-10-0.4593"; /** @type {ASTFeatureExtractor} */ let feature_extractor; beforeAll(async () => { feature_extractor = await AutoFeatureExtractor.from_pretrained(model_id); }, MAX_FEATURE_EXTRACTOR_LOAD_TIME); it( "truncation", async () => { const audio = await load_cached_audio("mlk"); const { input_values } = await feature_extractor(audio); expect(input_values.dims).toEqual([1, 1024, 128]); expect(input_values.mean().item()).toBeCloseTo(-0.04054912979309085); expect(input_values.data[0]).toBeCloseTo(-0.5662586092948914); expect(input_values.data[1]).toBeCloseTo(-1.0300861597061157); expect(input_values.data[129]).toBeCloseTo(-1.084834098815918); expect(input_values.data[1025]).toBeCloseTo(-1.1204065084457397); }, MAX_TEST_EXECUTION_TIME, ); it( "padding", async () => { const audio = await load_cached_audio("mlk"); const { input_values } = await feature_extractor(audio.slice(0, 1000)); expect(input_values.dims).toEqual([1, 1024, 128]); // [1, 4, 128] -> (padded to) -> [1, 1024, 128] expect(input_values.mean().item()).toBeCloseTo(0.4647964835166931); expect(input_values.data[0]).toBeCloseTo(-0.5662586092948914); expect(input_values.data[1]).toBeCloseTo(-1.0300861597061157); expect(input_values.data[129]).toBeCloseTo(-1.084834098815918); // padded values expect(input_values.data[1025]).toBeCloseTo(0.46703237295150757); expect(input_values.data[2049]).toBeCloseTo(0.46703237295150757); expect(input_values.data[10000]).toBeCloseTo(0.46703237295150757); }, MAX_TEST_EXECUTION_TIME, ); }); };
transformers.js/tests/models/audio_spectrogram_transformer/test_feature_extraction_audio_spectrogram_transformer.js/0
{ "file_path": "transformers.js/tests/models/audio_spectrogram_transformer/test_feature_extraction_audio_spectrogram_transformer.js", "repo_id": "transformers.js", "token_count": 926 }
365
import { GPT2Tokenizer, GPT2LMHeadModel } from "../../../src/transformers.js"; import { MAX_MODEL_LOAD_TIME, MAX_TEST_EXECUTION_TIME, MAX_MODEL_DISPOSE_TIME, DEFAULT_MODEL_OPTIONS } from "../../init.js"; export default () => { describe("GPT2LMHeadModel", () => { const model_id = "hf-internal-testing/tiny-random-GPT2LMHeadModel"; /** @type {GPT2LMHeadModel} */ let model; /** @type {GPT2Tokenizer} */ let tokenizer; beforeAll(async () => { model = await GPT2LMHeadModel.from_pretrained(model_id, DEFAULT_MODEL_OPTIONS); tokenizer = await GPT2Tokenizer.from_pretrained(model_id); tokenizer.padding_side = "left"; }, MAX_MODEL_LOAD_TIME); it( "batch_size=1", async () => { const inputs = tokenizer("hello"); const outputs = await model.generate({ ...inputs, max_length: 10, }); expect(outputs.tolist()).toEqual([[258n, 863n, 79n, 79n, 79n, 79n, 79n, 79n, 79n, 243n]]); }, MAX_TEST_EXECUTION_TIME, ); it( "batch_size>1", async () => { const inputs = tokenizer(["hello", "hello world"], { padding: true }); const outputs = await model.generate({ ...inputs, max_length: 10, }); expect(outputs.tolist()).toEqual([ [0n, 0n, 258n, 863n, 79n, 79n, 79n, 79n, 79n, 79n], [258n, 863n, 79n, 269n, 813n, 813n, 813n, 813n, 813n, 813n], ]); }, MAX_TEST_EXECUTION_TIME, ); afterAll(async () => { await model?.dispose(); }, MAX_MODEL_DISPOSE_TIME); }); };
transformers.js/tests/models/gpt2/test_modeling_gpt2.js/0
{ "file_path": "transformers.js/tests/models/gpt2/test_modeling_gpt2.js", "repo_id": "transformers.js", "token_count": 769 }
366
import { PreTrainedTokenizer, Lfm2ForCausalLM } from "../../../src/transformers.js"; import { MAX_MODEL_LOAD_TIME, MAX_TEST_EXECUTION_TIME, MAX_MODEL_DISPOSE_TIME, DEFAULT_MODEL_OPTIONS } from "../../init.js"; export default () => { describe("Lfm2ForCausalLM", () => { const model_id = "onnx-internal-testing/tiny-random-Lfm2ForCausalLM"; /** @type {Lfm2ForCausalLM} */ let model; /** @type {PreTrainedTokenizer} */ let tokenizer; beforeAll(async () => { model = await Lfm2ForCausalLM.from_pretrained(model_id, DEFAULT_MODEL_OPTIONS); tokenizer = await PreTrainedTokenizer.from_pretrained(model_id); tokenizer.padding_side = "left"; }, MAX_MODEL_LOAD_TIME); it( "batch_size=1", async () => { const inputs = tokenizer("hello"); const outputs = await model.generate({ ...inputs, max_length: 10, }); expect(outputs.tolist()).toEqual([[1n, 52572n, 38892n, 6902n, 53329n, 33092n, 13656n, 49822n, 6902n, 52520n]]); }, MAX_TEST_EXECUTION_TIME, ); it( "batch_size>1", async () => { const inputs = tokenizer(["hello", "hello world"], { padding: true }); const outputs = await model.generate({ ...inputs, max_length: 10, }); expect(outputs.tolist()).toEqual([ [0n, 1n, 52572n, 60239n, 57205n, 6790n, 58292n, 30935n, 5959n, 6902n], [1n, 52572n, 2031n, 59572n, 43345n, 42427n, 31142n, 41100n, 5321n, 5816n], ]); }, MAX_TEST_EXECUTION_TIME, ); afterAll(async () => { await model?.dispose(); }, MAX_MODEL_DISPOSE_TIME); }); };
transformers.js/tests/models/lfm2/test_modeling_lfm2.js/0
{ "file_path": "transformers.js/tests/models/lfm2/test_modeling_lfm2.js", "repo_id": "transformers.js", "token_count": 794 }
367
import { NllbTokenizer } from "../../../src/tokenizers.js"; import { BASE_TEST_STRINGS } from "../test_strings.js"; export const TOKENIZER_CLASS = NllbTokenizer; export const TEST_CONFIG = { "Xenova/nllb-200-distilled-600M": { SIMPLE: { text: BASE_TEST_STRINGS.SIMPLE, tokens: ["\u2581How", "\u2581are", "\u2581you", "\u2581doing", "?"], ids: [256047, 13374, 2442, 1259, 34512, 248130, 2], decoded: "eng_Latn How are you doing?</s>", }, SIMPLE_WITH_PUNCTUATION: { text: BASE_TEST_STRINGS.SIMPLE_WITH_PUNCTUATION, tokens: ["\u2581You", "\u2581should", "'", "ve", "\u2581done", "\u2581this"], ids: [256047, 3555, 12516, 248116, 279, 27236, 3423, 2], decoded: "eng_Latn You should've done this</s>", }, NUMBERS: { text: BASE_TEST_STRINGS.NUMBERS, tokens: ["\u25810", "123", "45", "67", "89", "\u25810", "\u25811", "\u25812", "\u25813", "\u25814", "\u25815", "\u25816", "\u25817", "\u25818", "\u25819", "\u258110", "\u2581100", "\u25811000"], ids: [256047, 4097, 232903, 25497, 37462, 42763, 4097, 94, 140, 315, 436, 481, 617, 757, 799, 855, 772, 3037, 18041, 2], decoded: "eng_Latn 0123456789 0 1 2 3 4 5 6 7 8 9 10 100 1000</s>", }, TEXT_WITH_NUMBERS: { text: BASE_TEST_STRINGS.TEXT_WITH_NUMBERS, tokens: ["\u2581The", "\u2581company", "\u2581was", "\u2581found", "ed", "\u2581in", "\u25812016."], ids: [256047, 1617, 32796, 1398, 26710, 76, 108, 31889, 2], decoded: "eng_Latn The company was founded in 2016.</s>", }, PUNCTUATION: { text: BASE_TEST_STRINGS.PUNCTUATION, tokens: ["\u2581A", "\u2581'", "ll", "\u2581!!", "to", "?'", "d", "'", "'", "d", "\u2581of", ",", "\u2581can", "'", "t", "."], ids: [256047, 70, 238, 1015, 12434, 208, 7358, 248072, 248116, 248116, 248072, 452, 248079, 2125, 248116, 248065, 248075, 2], decoded: "eng_Latn A 'll!!to?'d''d of, can't.</s>", }, PYTHON_CODE: { text: BASE_TEST_STRINGS.PYTHON_CODE, tokens: ["\u2581def", "\u2581main", "(", "):", "\u2581pass"], ids: [256047, 9274, 8385, 248168, 9481, 5800, 2], decoded: "eng_Latn def main(): pass</s>", }, JAVASCRIPT_CODE: { text: BASE_TEST_STRINGS.JAVASCRIPT_CODE, tokens: ["\u2581let", "\u2581a", "\u2581=", "\u2581ob", "j", ".", "to", "Str", "ing", "(", ");", "\u2581to", "Str", "ing", "(", ");"], ids: [256047, 3190, 9, 5636, 859, 248086, 248075, 208, 134293, 87, 248168, 12387, 202, 134293, 87, 248168, 12387, 2], decoded: "eng_Latn let a = obj.toString(); toString();</s>", }, NEWLINES: { text: BASE_TEST_STRINGS.NEWLINES, tokens: ["\u2581This", "\u2581is", "\u2581a", "\u2581test", "."], ids: [256047, 9680, 248, 9, 7356, 248075, 2], decoded: "eng_Latn This is a test.</s>", }, BASIC: { text: BASE_TEST_STRINGS.BASIC, tokens: ["\u2581UN", "want", "\u00e9d", ",", "run", "ning"], ids: [256047, 16297, 41691, 11317, 248079, 8464, 888, 2], decoded: "eng_Latn UNwant\u00e9d,running</s>", }, CONTROL_TOKENS: { text: BASE_TEST_STRINGS.CONTROL_TOKENS, tokens: ["\u25811", "<unk>", "2", "\u25813"], ids: [256047, 94, 3, 248147, 315, 2], decoded: "eng_Latn 1<unk>2 3</s>", }, HELLO_WORLD_TITLECASE: { text: BASE_TEST_STRINGS.HELLO_WORLD_TITLECASE, tokens: ["\u2581Hello", "\u2581World"], ids: [256047, 94124, 13855, 2], decoded: "eng_Latn Hello World</s>", }, HELLO_WORLD_LOWERCASE: { text: BASE_TEST_STRINGS.HELLO_WORLD_LOWERCASE, tokens: ["\u2581hello", "\u2581world"], ids: [256047, 133863, 15697, 2], decoded: "eng_Latn hello world</s>", }, CHINESE_ONLY: { text: BASE_TEST_STRINGS.CHINESE_ONLY, tokens: ["\u2581\u751f\u6d3b", "\u7684", "\u771f", "<unk>", "\u662f"], ids: [256047, 182892, 248506, 249573, 3, 249221, 2], decoded: "eng_Latn \u751f\u6d3b\u7684\u771f<unk>\u662f</s>", }, LEADING_SPACE: { text: BASE_TEST_STRINGS.LEADING_SPACE, tokens: ["\u2581leading", "\u2581space"], ids: [256047, 151175, 72147, 2], decoded: "eng_Latn leading space</s>", }, TRAILING_SPACE: { text: BASE_TEST_STRINGS.TRAILING_SPACE, tokens: ["\u2581tra", "iling", "\u2581space", "\u2581"], ids: [256047, 1372, 21263, 72147, 248059, 2], decoded: "eng_Latn trailing space </s>", }, DOUBLE_SPACE: { text: BASE_TEST_STRINGS.DOUBLE_SPACE, tokens: ["\u2581Hi", "\u2581Hello"], ids: [256047, 2867, 94124, 2], decoded: "eng_Latn Hi Hello</s>", }, CURRENCY: { text: BASE_TEST_STRINGS.CURRENCY, tokens: ["\u2581test", "\u2581$1", "\u2581R", "2", "\u2581#3", "\u2581\u20ac", "4", "\u2581\u00a3", "5", "\u2581", "\u00a5", "6", "\u2581", "<unk>", "7", "\u2581", "\u20b9", "8", "\u2581", "<unk>", "9", "\u2581test"], ids: [256047, 7356, 68462, 250, 248147, 186447, 22935, 248215, 25400, 248210, 248059, 252351, 248262, 248059, 3, 248283, 248059, 254867, 248268, 248059, 3, 248212, 7356, 2], decoded: "eng_Latn test $1 R2 #3 \u20ac4 \u00a35 \u00a56 <unk>7 \u20b98 <unk>9 test</s>", }, CURRENCY_WITH_DECIMALS: { text: BASE_TEST_STRINGS.CURRENCY_WITH_DECIMALS, tokens: ["\u2581I", "\u2581bought", "\u2581an", "\u2581apple", "\u2581for", "\u2581$", "1.", "00", "\u2581at", "\u2581the", "\u2581store", "."], ids: [256047, 117, 177233, 111, 203152, 351, 4589, 3044, 460, 230, 349, 21087, 248075, 2], decoded: "eng_Latn I bought an apple for $1.00 at the store.</s>", }, ELLIPSIS: { text: BASE_TEST_STRINGS.ELLIPSIS, tokens: ["\u2581you", "...", "\u2581"], ids: [256047, 1259, 284, 248059, 2], decoded: "eng_Latn you... </s>", }, TEXT_WITH_ESCAPE_CHARACTERS: { text: BASE_TEST_STRINGS.TEXT_WITH_ESCAPE_CHARACTERS, tokens: ["\u2581you", "...", "\u2581"], ids: [256047, 1259, 284, 248059, 2], decoded: "eng_Latn you... </s>", }, TEXT_WITH_ESCAPE_CHARACTERS_2: { text: BASE_TEST_STRINGS.TEXT_WITH_ESCAPE_CHARACTERS_2, tokens: ["\u2581you", "...", "\u2581you", "...", "\u2581"], ids: [256047, 1259, 284, 1259, 284, 248059, 2], decoded: "eng_Latn you... you... </s>", }, TILDE_NORMALIZATION: { text: BASE_TEST_STRINGS.TILDE_NORMALIZATION, tokens: ["\u2581weird", "\u2581", "<unk>", "\u2581ed", "ge", "\u2581", "<unk>", "\u2581case"], ids: [256047, 197348, 248059, 3, 1074, 479, 248059, 3, 23555, 2], decoded: "eng_Latn weird <unk> edge <unk> case</s>", }, SPIECE_UNDERSCORE: { text: BASE_TEST_STRINGS.SPIECE_UNDERSCORE, tokens: ["\u2581This", "\u2581is", "\u2581a", "\u2581test", "\u2581."], ids: [256047, 9680, 248, 9, 7356, 81, 2], decoded: "eng_Latn This is a test.</s>", }, POPULAR_EMOJIS: { text: BASE_TEST_STRINGS.POPULAR_EMOJIS, tokens: ["\u2581\ud83d\ude02", "\u2581", "\ud83d\udc4d", "\u2581", "\ud83e\udd23", "\u2581\ud83d\ude0d", "\u2581", "\ud83d\ude2d", "\u2581", "<unk>", "\u2581", "\ud83d\ude4f", "\u2581", "\ud83d\ude0a", "\u2581", "\ud83d\udd25", "\u2581", "\ud83d\ude01", "\u2581", "\ud83d\ude05", "\u2581", "\ud83e\udd17", "\u2581\ud83d\ude06", "\u2581", "\ud83d\udc4f", "\u2581\u2764", "\ufe0f", "\u2581", "\ud83d\udc9c", "\u2581", "\ud83d\udc9a", "\u2581", "<unk>", "\u2581", "\ud83d\udc99", "\u2581", "<unk>", "\u2581", "\ud83d\ude0e", "\u2581", "\ud83d\udc4c", "\u2581", "<unk>", "\u2581", "\ud83d\udcaa", "\u2581", "\u2728", "\u2581", "\ud83d\udc49", "\u2581", "<unk>", "\u2581", "<unk>", "\u2581", "<unk>", "\u2581", "\ud83d\ude48", "\u2581", "<unk>", "\u2581", "<unk>", "\u2581", "\ud83d\udc47", "\u2581", "<unk>", "\u2581", "\u2705", "\u2581", "\ud83c\udf81", "\u2581", "<unk>", "\u2581", "\ud83c\udf38", "\u2581", "<unk>"], ids: [256047, 104709, 248059, 253416, 248059, 253516, 241830, 248059, 253476, 248059, 3, 248059, 253443, 248059, 253515, 248059, 254402, 248059, 253288, 248059, 253776, 248059, 255232, 147677, 248059, 255420, 82495, 251759, 248059, 255742, 248059, 255949, 248059, 3, 248059, 255649, 248059, 3, 248059, 254297, 248059, 254723, 248059, 3, 248059, 255515, 248059, 254957, 248059, 253985, 248059, 3, 248059, 3, 248059, 3, 248059, 255855, 248059, 3, 248059, 3, 248059, 255354, 248059, 3, 248059, 254268, 248059, 255879, 248059, 3, 248059, 255952, 248059, 3, 2], decoded: "eng_Latn \ud83d\ude02 \ud83d\udc4d \ud83e\udd23 \ud83d\ude0d \ud83d\ude2d <unk> \ud83d\ude4f \ud83d\ude0a \ud83d\udd25 \ud83d\ude01 \ud83d\ude05 \ud83e\udd17 \ud83d\ude06 \ud83d\udc4f \u2764\ufe0f \ud83d\udc9c \ud83d\udc9a <unk> \ud83d\udc99 <unk> \ud83d\ude0e \ud83d\udc4c <unk> \ud83d\udcaa \u2728 \ud83d\udc49 <unk> <unk> <unk> \ud83d\ude48 <unk> <unk> \ud83d\udc47 <unk> \u2705 \ud83c\udf81 <unk> \ud83c\udf38 <unk></s>", }, MULTIBYTE_EMOJIS: { text: BASE_TEST_STRINGS.MULTIBYTE_EMOJIS, tokens: ["\u2581", "\u2728", "\u2581", "\ud83e\udd17", "\u2581", "\ud83d\udc41", "\ufe0f", "\u2581", "<unk>", "\ud83c\udffb", "\u2581", "<unk>", "\u2581", "\u2642", "\ufe0f", "\u2581", "<unk>", "\ud83c\udffb", "\u2581", "\u2642", "\u2581", "<unk>", "\ud83c\udffb", "\u2581", "<unk>", "\u2581", "<unk>", "\u2581", "<unk>", "\u2581", "<unk>", "\u2581", "<unk>", "\u2581\u2764", "\u2581", "<unk>", "\u2581", "<unk>", "\u2581", "<unk>", "\u2581", "<unk>", "\u2581", "<unk>", "\u2581", "<unk>", "\u2581", "<unk>", "\ud83c\udffb", "\u2581", "<unk>", "\u2581", "<unk>", "\ud83c\udffb", "\u2581", "<unk>", "\u2581", "<unk>", "\ud83c\udffb", "\u2581\u2764", "\ufe0f", "\u2581", "<unk>", "\u2581", "<unk>", "\ud83c\udffc"], ids: [256047, 248059, 254957, 248059, 255232, 248059, 255123, 251759, 248059, 3, 254422, 248059, 3, 248059, 255331, 251759, 248059, 3, 254422, 248059, 255331, 248059, 3, 254422, 248059, 3, 248059, 3, 248059, 3, 248059, 3, 248059, 3, 82495, 248059, 3, 248059, 3, 248059, 3, 248059, 3, 248059, 3, 248059, 3, 248059, 3, 254422, 248059, 3, 248059, 3, 254422, 248059, 3, 248059, 3, 254422, 82495, 251759, 248059, 3, 248059, 3, 255832, 2], decoded: "eng_Latn \u2728 \ud83e\udd17 \ud83d\udc41\ufe0f <unk>\ud83c\udffb <unk> \u2642\ufe0f <unk>\ud83c\udffb \u2642 <unk>\ud83c\udffb <unk> <unk> <unk> <unk> <unk> \u2764 <unk> <unk> <unk> <unk> <unk> <unk> <unk>\ud83c\udffb <unk> <unk>\ud83c\udffb <unk> <unk>\ud83c\udffb \u2764\ufe0f <unk> <unk>\ud83c\udffc</s>", }, }, };
transformers.js/tests/models/nllb/test_tokenization_nllb.js/0
{ "file_path": "transformers.js/tests/models/nllb/test_tokenization_nllb.js", "repo_id": "transformers.js", "token_count": 5409 }
368
import { AutoProcessor, Qwen2VLProcessor } from "../../../src/transformers.js"; import { load_cached_image } from "../../asset_cache.js"; import { MAX_PROCESSOR_LOAD_TIME, MAX_TEST_EXECUTION_TIME } from "../../init.js"; export default () => { describe("Qwen2VLProcessor", () => { const model_id = "hf-internal-testing/tiny-random-Qwen2VLForConditionalGeneration"; /** @type {Qwen2VLProcessor} */ let processor; let images = {}; beforeAll(async () => { processor = await AutoProcessor.from_pretrained(model_id); images = { white_image: await load_cached_image("white_image"), }; }, MAX_PROCESSOR_LOAD_TIME); it( "Image and text", async () => { const conversation = [ { role: "user", content: [{ type: "image" }, { type: "text", text: "Describe this image." }], }, ]; const text = processor.apply_chat_template(conversation, { add_generation_prompt: true, }); const { input_ids, attention_mask, pixel_values, image_grid_thw } = await processor(text, images.white_image); expect(input_ids.dims).toEqual([1, 89]); expect(attention_mask.dims).toEqual([1, 89]); expect(pixel_values.dims).toEqual([256, 1176]); expect(image_grid_thw.dims).toEqual([1, 3]); }, MAX_TEST_EXECUTION_TIME, ); }); };
transformers.js/tests/models/qwen2_vl/test_processor_qwen2_vl.js/0
{ "file_path": "transformers.js/tests/models/qwen2_vl/test_processor_qwen2_vl.js", "repo_id": "transformers.js", "token_count": 612 }
369
import { AutoFeatureExtractor, WhisperFeatureExtractor } from "../../../src/transformers.js"; import { load_cached_audio } from "../../asset_cache.js"; import { MAX_FEATURE_EXTRACTOR_LOAD_TIME, MAX_TEST_EXECUTION_TIME } from "../../init.js"; export default () => { // WhisperFeatureExtractor describe("WhisperFeatureExtractor", () => { const model_id = "Xenova/whisper-tiny.en"; /** @type {WhisperFeatureExtractor} */ let feature_extractor; beforeAll(async () => { feature_extractor = await AutoFeatureExtractor.from_pretrained(model_id); }, MAX_FEATURE_EXTRACTOR_LOAD_TIME); it( "default", async () => { const audio = await load_cached_audio("mlk"); const { input_features } = await feature_extractor(audio); const { dims, data } = input_features; expect(dims).toEqual([1, 80, 3000]); expect(input_features.mean().item()).toBeCloseTo(-0.2813588131551941); expect(data[0]).toBeCloseTo(0.33168578147888184); expect(data[1]).toBeCloseTo(0.30986475944519043); expect(data[81]).toBeCloseTo(0.10727232694625854); expect(data[3001]).toBeCloseTo(0.2555035352706909); }, MAX_TEST_EXECUTION_TIME, ); it( "max_length (max_length < audio.length < max_num_samples)", async () => { const audio = await load_cached_audio("mlk"); const { input_features } = await feature_extractor(audio, { max_length: 5 * 16000 }); const { dims, data } = input_features; expect(dims).toEqual([1, 80, 500]); expect(input_features.mean().item()).toBeCloseTo(0.20474646985530853); expect(data[0]).toBeCloseTo(0.33168578147888184); expect(data[1]).toBeCloseTo(0.30986475944519043); expect(data[81]).toBeCloseTo(0.10727238655090332); expect(data[3001]).toBeCloseTo(0.4018087387084961); expect(data.at(-1)).toBeCloseTo(-0.41003990173339844); }, MAX_TEST_EXECUTION_TIME, ); it( "max_length (audio.length < max_length < max_num_samples)", async () => { const audio = await load_cached_audio("mlk"); const { input_features } = await feature_extractor(audio, { max_length: 25 * 16000 }); const { dims, data } = input_features; expect(dims).toEqual([1, 80, 2500]); expect(input_features.mean().item()).toBeCloseTo(-0.20426231622695923); expect(data[0]).toBeCloseTo(0.33168578147888184); expect(data[1]).toBeCloseTo(0.30986475944519043); expect(data[81]).toBeCloseTo(0.10727238655090332); expect(data[3001]).toBeCloseTo(0.18040966987609863); expect(data.at(-1)).toBeCloseTo(-0.6668410897254944); }, MAX_TEST_EXECUTION_TIME, ); }); };
transformers.js/tests/models/whisper/test_feature_extraction_whisper.js/0
{ "file_path": "transformers.js/tests/models/whisper/test_feature_extraction_whisper.js", "repo_id": "transformers.js", "token_count": 1219 }
370
import { pipeline, ImageToImagePipeline } from "../../src/transformers.js"; import { MAX_MODEL_LOAD_TIME, MAX_TEST_EXECUTION_TIME, MAX_MODEL_DISPOSE_TIME, DEFAULT_MODEL_OPTIONS } from "../init.js"; import { load_cached_image } from "../asset_cache.js"; const PIPELINE_ID = "image-to-image"; export default () => { describe("Image to Image", () => { const model_id = "hf-internal-testing/tiny-random-Swin2SRForImageSuperResolution"; /** @type {ImageToImagePipeline} */ let pipe; let images; beforeAll(async () => { pipe = await pipeline(PIPELINE_ID, model_id, DEFAULT_MODEL_OPTIONS); images = await Promise.all([load_cached_image("white_image"), load_cached_image("blue_image")]); }, MAX_MODEL_LOAD_TIME); it("should be an instance of ImageToImagePipeline", () => { expect(pipe).toBeInstanceOf(ImageToImagePipeline); }); describe("batch_size=1", () => { it( "default", async () => { const output = await pipe(images[0]); expect(output.size).toEqual([64, 64]); expect(output.channels).toEqual(3); expect(output.data.reduce((a, b) => a + b, 0) / output.data.length).toBeCloseTo(110.107421875, 3); }, MAX_TEST_EXECUTION_TIME, ); }); describe("batch_size>1", () => { it( "default", async () => { const output = await pipe(images); expect(output[0].size).toEqual([64, 64]); expect(output[0].channels).toEqual(3); expect(output[0].data.reduce((a, b) => a + b, 0) / output[0].data.length).toBeCloseTo(110.107421875, 3); expect(output[1].size).toEqual([64, 64]); expect(output[1].channels).toEqual(3); expect(output[1].data.reduce((a, b) => a + b, 0) / output[1].data.length).toBeCloseTo(110.60196940104167, 3); }, MAX_TEST_EXECUTION_TIME, ); }); afterAll(async () => { await pipe.dispose(); }, MAX_MODEL_DISPOSE_TIME); }); };
transformers.js/tests/pipelines/test_pipelines_image_to_image.js/0
{ "file_path": "transformers.js/tests/pipelines/test_pipelines_image_to_image.js", "repo_id": "transformers.js", "token_count": 898 }
371
import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; export async function loadAudio(url) { // NOTE: Since the Web Audio API is not available in Node.js, we will need to use the `wavefile` library to obtain the raw audio data. // For more information, see: https://huggingface.co/docs/transformers.js/guides/node-audio-processing let wavefile = (await import("wavefile")).default; // Load audio data let buffer = Buffer.from(await fetch(url).then((x) => x.arrayBuffer())); // Read .wav file and convert it to required format let wav = new wavefile.WaveFile(buffer); wav.toBitDepth("32f"); // Pipeline expects input as a Float32Array wav.toSampleRate(16000); // Whisper expects audio with a sampling rate of 16000 let audioData = wav.getSamples(); if (Array.isArray(audioData)) { if (audioData.length > 1) { const SCALING_FACTOR = Math.sqrt(2); // Merge channels (into first channel to save memory) for (let i = 0; i < audioData[0].length; ++i) { audioData[0][i] = (SCALING_FACTOR * (audioData[0][i] + audioData[1][i])) / 2; } } // Select first channel audioData = audioData[0]; } return audioData; } /** * Deep equality test (for arrays and objects) with tolerance for floating point numbers * @param {any} val1 The first item * @param {any} val2 The second item * @param {number} tol Tolerance for floating point numbers */ export function compare(val1, val2, tol = 0.1) { if (val1 !== null && val2 !== null && typeof val1 === "object" && typeof val2 === "object") { // Both are non-null objects if (Array.isArray(val1) && Array.isArray(val2)) { expect(val1).toHaveLength(val2.length); for (let i = 0; i < val1.length; ++i) { compare(val1[i], val2[i], tol); } } else { expect(Object.keys(val1)).toHaveLength(Object.keys(val2).length); for (let key in val1) { compare(val1[key], val2[key], tol); } } } else { // At least one of them is not an object // First check that both have the same type expect(typeof val1).toEqual(typeof val2); if (typeof val1 === "number" && (!Number.isInteger(val1) || !Number.isInteger(val2))) { // If both are numbers and at least one of them is not an integer expect(val1).toBeCloseTo(val2, -Math.log10(tol)); } else { // Perform equality test expect(val1).toEqual(val2); } } } const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const models_dir = path.join(__dirname, "models"); const pipelines_dir = path.join(__dirname, "pipelines"); /** * Helper function to collect all unit tests, which can be found in files * of the form: `tests/models/<model_type>/test_<filename>_<model_type>.js`. * @param {string} filename * @returns {Promise<[string, Function][]>} */ export async function collect_tests(filename) { const model_types = fs.readdirSync(models_dir); const all_tests = []; for (const model_type of model_types) { const dir = path.join(models_dir, model_type); if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) { continue; } const file = path.join(dir, `test_${filename}_${model_type}.js`); if (!fs.existsSync(file)) { continue; } const items = await import(file); all_tests.push([model_type, items]); } return all_tests; } /** * Helper function to collect and execute all unit tests, which can be found in files * of the form: `tests/models/<model_type>/test_<filename>_<model_type>.js`. * @param {string} title The title of the test * @param {string} filename The name of the test */ export async function collect_and_execute_tests(title, filename) { // 1. Collect all tests const all_tests = await collect_tests(filename); // 2. Execute tests describe(title, () => all_tests.forEach(([name, test]) => describe(name, test.default))); } /** * Helper function to collect all pipeline tests, which can be found in files * of the form: `tests/pipelines/test_pipeline_<pipeline_id>.js`. */ export async function collect_and_execute_pipeline_tests(title) { // 1. Collect all tests const all_tests = []; const pipeline_types = fs.readdirSync(pipelines_dir); for (const filename of pipeline_types) { const file = path.join(pipelines_dir, filename); const items = await import(file); all_tests.push(items); } // 2. Execute tests describe(title, () => all_tests.forEach((test) => test.default())); }
transformers.js/tests/test_utils.js/0
{ "file_path": "transformers.js/tests/test_utils.js", "repo_id": "transformers.js", "token_count": 1618 }
372
import re import argparse def parse_pytest_output(file_path): skipped_tests = {} skipped_count = 0 with open(file_path, 'r') as file: for line in file: match = re.match(r'^SKIPPED \[(\d+)\] (tests/.*): (.*)$', line) if match: skipped_count += 1 test_file, test_line, reason = match.groups() skipped_tests[reason] = skipped_tests.get(reason, []) + [(test_file, test_line)] for k,v in sorted(skipped_tests.items(), key=lambda x:len(x[1])): print(f"{len(v):4} skipped because: {k}") print("Number of skipped tests:", skipped_count) def parse_pytest_failure_output(file_path): failed_tests = {} failed_count = 0 with open(file_path, 'r') as file: for line in file: match = re.match(r'^FAILED (tests/.*) - (.*): (.*)$', line) if match: failed_count += 1 _, error, reason = match.groups() failed_tests[reason] = failed_tests.get(reason, []) + [error] for k,v in sorted(failed_tests.items(), key=lambda x:len(x[1])): print(f"{len(v):4} failed because `{v[0]}` -> {k}") print("Number of failed tests:", failed_count) if failed_count>0: exit(1) def parse_pytest_errors_output(file_path): print(file_path) error_tests = {} error_count = 0 with open(file_path, 'r') as file: for line in file: match = re.match(r'^ERROR (tests/.*) - (.*): (.*)$', line) if match: error_count += 1 _, test_error, reason = match.groups() error_tests[reason] = error_tests.get(reason, []) + [test_error] for k,v in sorted(error_tests.items(), key=lambda x:len(x[1])): print(f"{len(v):4} errored out because of `{v[0]}` -> {k}") print("Number of errors:", error_count) if error_count>0: exit(1) def main(): parser = argparse.ArgumentParser() parser.add_argument("--file", help="file to parse") parser.add_argument("--skip", action="store_true", help="show skipped reasons") parser.add_argument("--fail", action="store_true", help="show failed tests") parser.add_argument("--errors", action="store_true", help="show failed tests") args = parser.parse_args() if args.skip: parse_pytest_output(args.file) if args.fail: parse_pytest_failure_output(args.file) if args.errors: parse_pytest_errors_output(args.file) if __name__ == "__main__": main()
transformers/.circleci/parse_test_outputs.py/0
{ "file_path": "transformers/.circleci/parse_test_outputs.py", "repo_id": "transformers", "token_count": 1145 }
373
.PHONY: deps_table_update modified_only_fixup extra_style_checks quality style fixup fix-copies test test-examples benchmark # make sure to test the local checkout in scripts and not the pre-installed one (don't use quotes!) export PYTHONPATH = src check_dirs := examples tests src utils exclude_folders := "" modified_only_fixup: @current_branch=$$(git branch --show-current); \ if [ "$$current_branch" = "main" ]; then \ echo "On main branch, running 'style' target instead..."; \ $(MAKE) style; \ else \ modified_py_files=$$(python utils/get_modified_files.py $(check_dirs)); \ if [ -n "$$modified_py_files" ]; then \ echo "Checking/fixing files: $${modified_py_files}"; \ ruff check $${modified_py_files} --fix --exclude $(exclude_folders); \ ruff format $${modified_py_files} --exclude $(exclude_folders); \ else \ echo "No library .py files were modified"; \ fi; \ fi # Update src/transformers/dependency_versions_table.py deps_table_update: @python setup.py deps_table_update deps_table_check_updated: @md5sum src/transformers/dependency_versions_table.py > md5sum.saved @python setup.py deps_table_update @md5sum -c --quiet md5sum.saved || (printf "\nError: the version dependency table is outdated.\nPlease run 'make fixup' or 'make style' and commit the changes.\n\n" && exit 1) @rm md5sum.saved # autogenerating code autogenerate_code: deps_table_update # Check that the repo is in a good state repo-consistency: python utils/check_copies.py python utils/check_modular_conversion.py python utils/check_dummies.py python utils/check_repo.py python utils/check_inits.py python utils/check_pipeline_typing.py python utils/check_config_docstrings.py python utils/check_config_attributes.py python utils/check_doctest_list.py python utils/update_metadata.py --check-only python utils/check_docstrings.py python utils/add_dates.py # this target runs checks on all files quality: @python -c "from transformers import *" || (echo '🚨 import failed, this means you introduced unprotected imports! 🚨'; exit 1) ruff check $(check_dirs) setup.py conftest.py ruff format --check $(check_dirs) setup.py conftest.py python utils/sort_auto_mappings.py --check_only python utils/check_doc_toc.py python utils/check_docstrings.py --check_all # Format source code automatically and check is there are any problems left that need manual fixing extra_style_checks: python utils/sort_auto_mappings.py python utils/check_doc_toc.py --fix_and_overwrite # this target runs checks on all files and potentially modifies some of them style: ruff check $(check_dirs) setup.py conftest.py --fix --exclude $(exclude_folders) ruff format $(check_dirs) setup.py conftest.py --exclude $(exclude_folders) ${MAKE} autogenerate_code ${MAKE} extra_style_checks # Super fast fix and check target that only works on relevant modified files since the branch was made fixup: modified_only_fixup extra_style_checks autogenerate_code repo-consistency # Make marked copies of snippets of codes conform to the original fix-copies: python utils/check_copies.py --fix_and_overwrite python utils/check_modular_conversion.py --fix_and_overwrite python utils/check_dummies.py --fix_and_overwrite python utils/check_pipeline_typing.py --fix_and_overwrite python utils/check_doctest_list.py --fix_and_overwrite python utils/check_docstrings.py --fix_and_overwrite # Run tests for the library test: python -m pytest -n auto --dist=loadfile -s -v ./tests/ # Run tests for examples test-examples: python -m pytest -n auto --dist=loadfile -s -v ./examples/pytorch/ # Run benchmark benchmark: python3 benchmark/benchmark.py --config-dir benchmark/config --config-name generation --commit=diff backend.model=google/gemma-2b backend.cache_implementation=null,static backend.torch_compile=false,true --multirun # Run tests for SageMaker DLC release test-sagemaker: # install sagemaker dependencies in advance with pip install .[sagemaker] TEST_SAGEMAKER=True python -m pytest -n auto -s -v ./tests/sagemaker # Release stuff pre-release: python utils/release.py pre-patch: python utils/release.py --patch post-release: python utils/release.py --post_release post-patch: python utils/release.py --post_release --patch build-release: rm -rf dist rm -rf build python setup.py bdist_wheel python setup.py sdist python utils/check_build.py
transformers/Makefile/0
{ "file_path": "transformers/Makefile", "repo_id": "transformers", "token_count": 1510 }
374
FROM nvidia/cuda:12.6.0-cudnn-devel-ubuntu22.04 LABEL maintainer="Hugging Face" ARG DEBIAN_FRONTEND=noninteractive # Use login shell to read variables from `~/.profile` (to pass dynamic created variables between RUN commands) SHELL ["sh", "-lc"] # The following `ARG` are mainly used to specify the versions explicitly & directly in this docker file, and not meant # to be used as arguments for docker build (so far). ARG PYTORCH='2.8.0' # Example: `cu102`, `cu113`, etc. ARG CUDA='cu126' # Disable kernel mapping for now until all tests pass ENV DISABLE_KERNEL_MAPPING=1 RUN apt update RUN apt install -y git libsndfile1-dev tesseract-ocr espeak-ng python3 python3-pip ffmpeg git-lfs RUN git lfs install RUN python3 -m pip install --no-cache-dir --upgrade pip ARG REF=main RUN git clone https://github.com/huggingface/transformers && cd transformers && git checkout $REF # 1. Put several commands in a single `RUN` to avoid image/layer exporting issue. Could be revised in the future. # 2. Regarding `torch` part, We might need to specify proper versions for `torchvision` and `torchaudio`. # Currently, let's not bother to specify their versions explicitly (so installed with their latest release versions). RUN python3 -m pip install --no-cache-dir -e ./transformers[dev,onnxruntime] && [ ${#PYTORCH} -gt 0 -a "$PYTORCH" != "pre" ] && VERSION='torch=='$PYTORCH'.*' || VERSION='torch'; echo "export VERSION='$VERSION'" >> ~/.profile && echo torch=$VERSION && [ "$PYTORCH" != "pre" ] && python3 -m pip install --no-cache-dir -U $VERSION torchvision torchaudio torchcodec --extra-index-url https://download.pytorch.org/whl/$CUDA || python3 -m pip install --no-cache-dir -U --pre torch torchvision torchaudio torchcodec --extra-index-url https://download.pytorch.org/whl/nightly/$CUDA && python3 -m pip uninstall -y tensorflow tensorflow_text tensorflow_probability RUN python3 -m pip uninstall -y flax jax RUN python3 -m pip install --no-cache-dir -U timm RUN python3 -m pip install --no-cache-dir git+https://github.com/facebookresearch/detectron2.git pytesseract RUN python3 -m pip install -U "itsdangerous<2.1.0" RUN python3 -m pip install --no-cache-dir git+https://github.com/huggingface/accelerate@main#egg=accelerate RUN python3 -m pip install --no-cache-dir git+https://github.com/huggingface/peft@main#egg=peft # For bettertransformer RUN python3 -m pip install --no-cache-dir git+https://github.com/huggingface/optimum@main#egg=optimum # For video model testing RUN python3 -m pip install --no-cache-dir av # Some slow tests require bnb RUN python3 -m pip install --no-cache-dir bitsandbytes # Some tests require quanto RUN python3 -m pip install --no-cache-dir quanto # `quanto` will install `ninja` which leads to many `CUDA error: an illegal memory access ...` in some model tests # (`deformable_detr`, `rwkv`, `mra`) RUN python3 -m pip uninstall -y ninja # For `nougat` tokenizer RUN python3 -m pip install --no-cache-dir python-Levenshtein # For `FastSpeech2ConformerTokenizer` tokenizer RUN python3 -m pip install --no-cache-dir g2p-en # For Some bitsandbytes tests RUN python3 -m pip install --no-cache-dir einops # For Some tests with `@require_liger_kernel` RUN python3 -m pip install --no-cache-dir liger-kernel # `kernels` may give different outputs (within 1e-5 range) even with the same model (weights) and the same inputs RUN python3 -m pip uninstall -y kernels # When installing in editable mode, `transformers` is not recognized as a package. # this line must be added in order for python to be aware of transformers. RUN cd transformers && python3 setup.py develop
transformers/docker/transformers-all-latest-gpu/Dockerfile/0
{ "file_path": "transformers/docker/transformers-all-latest-gpu/Dockerfile", "repo_id": "transformers", "token_count": 1188 }
375
<!--- Copyright 2020 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. --> # Generating the documentation To generate the documentation, you first have to build it. Several packages are necessary to build the doc, you can install them with the following command, at the root of the code repository: ```bash pip install -e ".[dev]" ``` > [!NOTE] > This command might fail for some OS that are missing dependencies. Check step 4 in [Create a Pull Request](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#create-a-pull-request) to workaround it. Then you need to install our special tool that builds the documentation: ```bash pip install git+https://github.com/huggingface/doc-builder ``` > [!NOTE] > You only need to generate the documentation to inspect it locally (if you're planning changes and want to > check how they look before committing for instance). You don't have to commit the built documentation. ## Building the documentation Once you have setup the `doc-builder` and additional packages, you can generate the documentation by typing the following command: ```bash doc-builder build transformers docs/source/en/ --build_dir ~/tmp/test-build ``` You can adapt the `--build_dir` to set any temporary folder that you prefer. This command will create it and generate the MDX files that will be rendered as the documentation on the main website. You can inspect them in your favorite Markdown editor. ## Previewing the documentation To preview the docs, first install the `watchdog` module with: ```bash pip install watchdog ``` Then run the following command: ```bash doc-builder preview {package_name} {path_to_docs} ``` For example: ```bash doc-builder preview transformers docs/source/en/ ``` The docs will be viewable at [http://localhost:3000](http://localhost:3000). You can also preview the docs once you have opened a PR. You will see a bot add a comment to a link where the documentation with your changes lives. > [!NOTE] > The `preview` command only works with existing doc files. When you add a completely new file, you need to update `_toctree.yml` & restart `preview` command (`ctrl-c` to stop it & call `doc-builder preview ...` again). ## Adding a new element to the navigation bar Accepted files are Markdown (.md). Create a file with its extension and put it in the source directory. You can then link it to the toc-tree by putting the filename without the extension in the [`_toctree.yml`](https://github.com/huggingface/transformers/blob/main/docs/source/en/_toctree.yml) file. ## Renaming section headers and moving sections It helps to keep the old links working when renaming the section header and/or moving sections from one document to another. This is because the old links are likely to be used in Issues, Forums, and Social media and it'd make for a much more superior user experience if users reading those months later could still easily navigate to the originally intended information. Therefore, we simply keep a little map of moved sections at the end of the document where the original section was. The key is to preserve the original anchor. So if you renamed a section from: "Section A" to "Section B", then you can add at the end of the file: ``` Sections that were moved: [ <a href="#section-b">Section A</a><a id="section-a"></a> ] ``` and of course, if you moved it to another file, then: ``` Sections that were moved: [ <a href="../new-file#section-b">Section A</a><a id="section-a"></a> ] ``` Use the relative style to link to the new file so that the versioned docs continue to work. For an example of a rich moved section set please see the very end of [the Trainer doc](https://github.com/huggingface/transformers/blob/main/docs/source/en/main_classes/trainer.md). ## Writing Documentation - Specification The `huggingface/transformers` documentation follows the [Google documentation](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html) style for docstrings, although we can write them directly in Markdown. ### Adding a new tutorial Adding a new tutorial or section is done in two steps: - Add a new file under `./source`. This file can either be ReStructuredText (.rst) or Markdown (.md). - Link that file in `./source/_toctree.yml` on the correct toc-tree. Make sure to put your new file under the proper section. It's unlikely to go in the first section (*Get Started*), so depending on the intended targets (beginners, more advanced users, or researchers) it should go in sections two, three, or four. ### Translating When translating, refer to the guide at [./TRANSLATING.md](https://github.com/huggingface/transformers/blob/main/docs/TRANSLATING.md). ### Adding a new model When adding a new model: - Create a file `xxx.md` or under `./source/model_doc` (don't hesitate to copy an existing file as template). - Link that file in `./source/_toctree.yml`. - Write a short overview of the model: - Overview with paper & authors - Paper abstract - Tips and tricks and how to use it best - Add the classes that should be linked in the model. This generally includes the configuration, the tokenizer, and every model of that class (the base model, alongside models with additional heads), both in PyTorch and TensorFlow. The order is generally: - Configuration - Tokenizer - PyTorch base model - PyTorch head models - TensorFlow base model - TensorFlow head models - Flax base model - Flax head models These classes should be added using our Markdown syntax. Usually as follows: ``` ## XXXConfig [[autodoc]] XXXConfig ``` > [!IMPORTANT] > Always add a blank line after `[[autodoc]]` to ensure it passes the CI/CD checks. This will include every public method of the configuration that is documented. If for some reason you wish for a method not to be displayed in the documentation, you can do so by specifying which methods should be in the docs: ``` ## XXXTokenizer [[autodoc]] XXXTokenizer - build_inputs_with_special_tokens - get_special_tokens_mask - create_token_type_ids_from_sequences - save_vocabulary ``` If you just want to add a method that is not documented (for instance magic methods like `__call__` are not documented by default) you can put the list of methods to add in a list that contains `all`: ``` ## XXXTokenizer [[autodoc]] XXXTokenizer - all - __call__ ``` ### Writing source documentation Values that should be put in `code` should either be surrounded by backticks: \`like so\`. Note that argument names and objects like True, None, or any strings should usually be put in `code`. When mentioning a class, function, or method, it is recommended to use our syntax for internal links so that our tool adds a link to its documentation with this syntax: \[\`XXXClass\`\] or \[\`function\`\]. This requires the class or function to be in the main package. If you want to create a link to some internal class or function, you need to provide its path. For instance: \[\`utils.ModelOutput\`\]. This will be converted into a link with `utils.ModelOutput` in the description. To get rid of the path and only keep the name of the object you are linking to in the description, add a ~: \[\`~utils.ModelOutput\`\] will generate a link with `ModelOutput` in the description. The same works for methods so you can either use \[\`XXXClass.method\`\] or \[\`~XXXClass.method\`\]. #### Defining arguments in a method Arguments should be defined with the `Args:` (or `Arguments:` or `Parameters:`) prefix, followed by a line return and an indentation. The argument should be followed by its type, with its shape if it is a tensor, a colon, and its description: ``` Args: n_layers (`int`): The number of layers of the model. ``` If the description is too long to fit in one line, another indentation is necessary before writing the description after the argument. Here's an example showcasing everything so far: ``` Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AlbertTokenizer`]. See [`~PreTrainedTokenizer.encode`] and [`~PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) ``` For optional arguments or arguments with defaults we follow the following syntax: imagine we have a function with the following signature: ``` def my_function(x: str = None, a: float = 1): ``` then its documentation should look like this: ``` Args: x (`str`, *optional*): This argument controls ... a (`float`, *optional*, defaults to 1): This argument is used to ... ``` Note that we always omit the "defaults to \`None\`" when None is the default for any argument. Also note that even if the first line describing your argument type and its default gets long, you can't break it on several lines. You can however, write as many lines as you want in the indented description (see the example above with `input_ids`). #### Writing a multi-line code block Multi-line code blocks can be useful for displaying examples. They are done between two lines of three backticks as usual in Markdown: ```` ``` # first line of code # second line # etc ``` ```` We follow the [doctest](https://docs.python.org/3/library/doctest.html) syntax for the examples to automatically test the results to stay consistent with the library. #### Writing a return block The return block should be introduced with the `Returns:` prefix, followed by a line return and an indentation. The first line should be the type of the return, followed by a line return. No need to indent further for the elements building the return. Here's an example of a single value return: ```python Returns: `list[int]`: A list of integers in the range [0, 1] --- 1 for a special token, 0 for a sequence token. ``` Here's an example of a tuple return, comprising several objects: ```python Returns: `tuple(torch.FloatTensor)` comprising various elements depending on the configuration ([`BertConfig`]) and inputs: - ** loss** (*optional*, returned when `masked_lm_labels` is provided) `torch.FloatTensor` of shape `(1,)` -- Total loss is the sum of the masked language modeling loss and the next sequence prediction (classification) loss. - **prediction_scores** (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`) -- Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). ``` #### Adding an image Due to the rapidly growing repository, it is important to make sure that no files that would significantly weigh down the repository are added. This includes images, videos, and other non-text files. We prefer to leverage a hf.co hosted `dataset` like the ones hosted on [`hf-internal-testing`](https://huggingface.co/hf-internal-testing) in which to place these files and reference them by URL. We recommend putting them in the following dataset: [huggingface/documentation-images](https://huggingface.co/datasets/huggingface/documentation-images). If an external contribution, feel free to add the images to your PR and ask a Hugging Face member to migrate your images to this dataset. ## Styling the docstring We have an automatic script running with the `make style` comment that will make sure that: - the docstrings fully take advantage of the line width - all code examples are formatted using black, like the code of the Transformers library This script may have some weird failures if you made a syntax mistake or if you uncover a bug. Therefore, it's recommended to commit your changes before running `make style`, so you can revert the changes done by that script easily. # Testing documentation examples Good documentation often comes with an example of how a specific function or class should be used. Each model class should contain at least one example showcasing how to use this model class in inference. *E.g.* the class [Wav2Vec2ForCTC](https://huggingface.co/docs/transformers/model_doc/wav2vec2#transformers.Wav2Vec2ForCTC) includes an example of how to transcribe speech to text in the [docstring of its forward function](https://huggingface.co/docs/transformers/model_doc/wav2vec2#transformers.Wav2Vec2ForCTC.forward). ## Writing documentation examples The syntax for Example docstrings can look as follows: ```python Example: >>> from transformers import Wav2Vec2Processor, Wav2Vec2ForCTC >>> from datasets import load_dataset >>> import torch >>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation") >>> dataset = dataset.sort("id") >>> sampling_rate = dataset.features["audio"].sampling_rate >>> processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base-960h") >>> model = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-base-960h") >>> # audio file is decoded on the fly >>> inputs = processor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt") >>> with torch.no_grad(): ... logits = model(**inputs).logits >>> predicted_ids = torch.argmax(logits, dim=-1) >>> # transcribe speech >>> transcription = processor.batch_decode(predicted_ids) >>> transcription[0] 'MISTER QUILTER IS THE APOSTLE OF THE MIDDLE CLASSES AND WE ARE GLAD TO WELCOME HIS GOSPEL' ``` The docstring should give a minimal, clear example of how the respective model is to be used in inference and also include the expected (ideally sensible) output. Often, readers will try out the example before even going through the function or class definitions. Therefore, it is of utmost importance that the example works as expected. ## Docstring testing To do so each example should be included in the doctests. We use pytests' [doctest integration](https://docs.pytest.org/doctest.html) to verify that all of our examples run correctly. For Transformers, the doctests are run on a daily basis via GitHub Actions as can be seen [here](https://github.com/huggingface/transformers/actions/workflows/doctests.yml). ### For Python files Run all the tests in the docstrings of a given file with the following command, here is how we test the modeling file of Wav2Vec2 for instance: ```bash pytest --doctest-modules src/transformers/models/wav2vec2/modeling_wav2vec2.py -sv --doctest-continue-on-failure ``` If you want to isolate a specific docstring, just add `::` after the file name then type the whole path of the function/class/method whose docstring you want to test. For instance, here is how to just test the forward method of `Wav2Vec2ForCTC`: ```bash pytest --doctest-modules src/transformers/models/wav2vec2/modeling_wav2vec2.py::transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForCTC.forward -sv --doctest-continue-on-failure ``` ### For Markdown files You can test locally a given file with this command (here testing the quicktour): ```bash pytest --doctest-modules docs/source/quicktour.md -sv --doctest-continue-on-failure --doctest-glob="*.md" ``` ### Writing doctests Here are a few tips to help you debug the doctests and make them pass: - The outputs of the code need to match the expected output **exactly**, so make sure you have the same outputs. In particular doctest will see a difference between single quotes and double quotes, or a missing parenthesis. The only exceptions to that rule are: * whitespace: one give whitespace (space, tabulation, new line) is equivalent to any number of whitespace, so you can add new lines where there are spaces to make your output more readable. * numerical values: you should never put more than 4 or 5 digits to expected results as different setups or library versions might get you slightly different results. `doctest` is configured to ignore any difference lower than the precision to which you wrote (so 1e-4 if you write 4 digits). - Don't leave a block of code that is very long to execute. If you can't make it fast, you can either not use the doctest syntax on it (so that it's ignored), or if you want to use the doctest syntax to show the results, you can add a comment `# doctest: +SKIP` at the end of the lines of code too long to execute - Each line of code that produces a result needs to have that result written below. You can ignore an output if you don't want to show it in your code example by adding a comment ` # doctest: +IGNORE_RESULT` at the end of the line of code producing it.
transformers/docs/README.md/0
{ "file_path": "transformers/docs/README.md", "repo_id": "transformers", "token_count": 4924 }
376
# قاموس المصطلحات يحدد هذا المسرد مصطلحات التعلم الآلي العامة و 🤗 Transformers لمساعدتك على فهم الوثائق بشكل أفضل. ## A ### قناع الانتباه (Attention Mask) قناع الانتباه هو مُدخل اختياري يستخدم عند تجميع التسلسلات معًا <Youtube id="M6adb1j2jPI"/> يشير هذا المُدخل إلى النموذج أى الرموز المميزة (tokens) التي يجب الانتباه إليها، وأيها لا ينبغي ذلك. على سبيل المثال، تأمّل هذين التسلسُلين : ```python >>> from transformers import BertTokenizer >>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased") >>> sequence_a = "This is a short sequence." >>> sequence_b = "This is a rather long sequence. It is at least longer than sequence A." >>> encoded_sequence_a = tokenizer(sequence_a)["input_ids"] >>> encoded_sequence_b = tokenizer(sequence_b)["input_ids"] ``` لدى الإصدارات المشفرة أطوال مختلفة: ```python >>> len(encoded_sequence_a), len(encoded_sequence_b) (8, 19) ``` لذلك، لا يمكننا وضعها معًا في نفس المصفوفة كما هي. يجب إضافة حشو إلى التسلسل الأول حتى يصل إلى طول التسلسل الثاني، أو يجب تقليص الثاني إلى طول الأول. في الحالة الأولى، يتم تمديد قائمة المعرفات بواسطة مؤشرات الحشو. يمكننا تمرير قائمة إلى المحلل اللغوي وطلب منه إضافة الحشو بهذه الطريقة: ```python >>> padded_sequences = tokenizer([sequence_a, sequence_b], padding=True) ``` يمكننا أن نرى أنه تمت إضافة اصفار على يمين الجملة الأولى لجعلها بنفس طول الجملة الثانية: ```python >>> padded_sequences["input_ids"] [[101, 1188, 1110, 170, 1603, 4954, 119, 102, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [101, 1188, 1110, 170, 1897, 1263, 4954, 119, 1135, 1110, 1120, 1655, 2039, 1190, 1103, 4954, 138, 119, 102]] ``` يمكن بعد ذلك تحويل هذا إلى مصفوفة في PyTorch أو TensorFlow. قناع الانتباه هو مصفوفة ثنائية تشير إلى موضع المؤشرات المحشوه بحيث لا ينتبه إليها النموذج. بالنسبة إلى [`BertTokenizer`]`1` يشير إلى قيمة يجب الانتباه إليها، في حين يشير `0` إلى قيمة مبطنة. يُمكن إيجاد قناع الانتباه في القاموس الذي يُعيده مُجزِّئ النصوص (tokenizer) تحت المفتاح "attention_mask". ```python >>> padded_sequences["attention_mask"] [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ``` ### نماذج الترميز التلقائي (autoencoding models) راجع [نماذج الترميز](#encoder-models) و [نمذجة اللغة المقنعة](#masked-language-modeling-mlm) ### النماذج ذاتية الانحدار (Autoregressive Models) راجع [نمذجة اللغة السببية](#causal-language-modeling) و [نماذج فك التشفير](#decoder-models) ## B ### العمود الفقري (backbone) يُمثل العمود الفقري الشبكة العصبونية (الترميزات والطبقات) المسؤولة عن إخراج الحالات الخفية أو المُميزات الأولية. عادة ما يكون متصلاً بـ [رأس](#head) يستقبل المُميزات كمدخلات لإجراء تنبؤ. على سبيل المثال، يُعد النموذج [`ViTModel`] عمودًا فقريًا دون رأس مُحدد مُرفق به. يمكن أيضًا استخدام `ViTModel` كعمود فقري في نماذج أخرى, مثل [DPT](model_doc/dpt). ## C ### نمذجة اللغة السببية (أو التنبؤية) causal language modeling مهمة ما قبل التدريب يقوم فيها النموذج بقراءة النصوص بالترتيب ويتنبأ بالكلمة التالية. يتم ذلك عادةً من خلال قراءة الجملة كاملةً، ولكن مع استخدام قناع داخل النموذج لإخفاء الرموز المميزة اللاحقة في خطوة زمنية معينة. ### قناة(channel) تتكون الصور الملونة من مزيج من القيم في ثلاث قنوات لونية: الأحمر والأخضر والأزرق (RGB) بينما تحتوي صور ذات التدرج رمادي على قناة واحدة فقط. في مكتبة 🤗 Transformers، يمكن أن تكون القناة اللونية البُعد الأول أو الأخير في مُصفوفة الصورة: [`n_channels`، `height`، `width`] أو [`height`، `width`، `n_channels`]. ### التصنيف الزمني التوصيلي connectionist temporal classification (CTC) خوارزمية تسمح للنموذج بالتعلم دون معرفة كيفية محاذاة المدخلات مع المخرجات بدقة؛ يحسب CTC توزيع جميع المخرجات المحتملة لمدخلات مُحددة ويختار المخرج الأكثر احتمالًا. تُستخدم CTC بشكل شائع في مهام التعرف على الكلام نظرًا لأن الكلام المنطوق لا يتوافق دائمًا بشكل مُباشر مع النص المكتوب، لأسباب مختلفة مثل معدلات الكلام المختلفة للمتكلم. ### الالتفاف (Convolution) نوع من الطبقات في شبكة عصبية، حيث تُضرب مصفوفة الإدخال عُنصرًا بُعنصر بمصفوفة أصغر تُسمى (النواة أو المرشح) ويتم جمع القيم في مصفوفة جديدة. يُعرف هذا باسم عملية الالتفاف التي يتم تكرارها عبر مصفوفة الإدخال بأكملها. تُطبق كل عملية التفاف على جزء مُختلف من مصفوفة الإدخال. تُستخدم الشبكات العصبية الالتفافية (CNNs) بشكل شائع في رؤية الحاسوب. ## D ### التوازي على مستوى البيانات (DataParallel - DP) هي تقنية تُستخدم لتدريب النماذج على عدة وحدات معالجة رسومات (GPUs)، حيث يتم نسخ نفس إعداد التدريب عدة مرات، بحيث تتلقى كل نسخة شريحة مختلفة من البيانات يتم تنفيذ المعالجة بالتوازي ويتم مزامنة جميع الإعدادات في نهاية كل خطوة تدريب. تعرف على المزيد حول كيفية عمل DataParallel [هنا](perf_train_gpu_many#dataparallel-vs-distributeddataparallel). ### معرفات مدخلات وحدة فك التشفير (decoder input IDs) هذا المدخل خاص بنماذج الترميز وفك التشفير، ويحتوي على معرفات الإدخال التي سيتم تغذيتها إلى وحدة فك التشفير. يجب استخدام هذه المدخلات لمهام التسلسل إلى التسلسل، مثل الترجمة أو التلخيص، وعادة ما يتم بناؤها بطريقة محددة لكل نموذج. تقوم معظم نماذج الترميز وفك التشفير (BART، T5) بإنشاء معرفات `decoder_input_ids` الخاصة بها من `labels`. في مثل هذه النماذج، يعد تمرير `labels` هو الطريقة المفضلة للتعامل مع التدريب. يرجى التحقق من وثائق كل نموذج لمعرفة كيفية تعاملها مع معرفات الإدخال هذه للتدريب على التسلسل إلى التسلسل. ### نماذج فك التشفير (decoder models) يُشار إليها أيضًا باسم نماذج التنبؤية الذاتية، وتنطوي نماذج فك التشفير على مهمة ما قبل التدريب (تسمى نمذجة اللغة السببية) حيث يقرأ النموذج النصوص بالترتيب ويتعين عليه التنبؤ بالكلمة التالية. يتم ذلك عادةً عن طريق قراءة الجملة بأكملها مع قناع لإخفاء الرموز المميزة المستقبلية في خطوة زمنية معينة. <Youtube id="d_ixlCubqQw"/> ### التعلم العميق deep learning (DL) خوارزميات التعلم الآلي التي تستخدم الشبكات العصبية متعددة الطبقات. ## E ### نماذج الترميز (encoder models) تُعرف أيضًا باسم نماذج الترميز التلقائي، وتأخذ نماذج الترميز إدخالًا (مثل النص أو الصور) وتحويلها إلى تمثيل رقمي مكثف يُطلق عليه الترميز. غالبًا ما يتم تدريب نماذج الترميز مسبقًا باستخدام تقنيات مثل [نمذجة اللغة المقنعة](#masked-language-modeling-mlm)، والتي تقوم بإخفاء أجزاء من تسلسل الإدخال وإجبار النموذج على إنشاء تمثيلات أكثر دلالة (فائدة ووضوحاً). <Youtube id="H39Z_720T5s"/> ## F ### استخراج الميزات (feature extraction) عملية اختيار وتحويل البيانات الأولية إلى مجموعة من الميزات الأكثر إفادة وفائدة لخوارزميات التعلم الآلي. بعض الأمثلة على استخراج الميزات تشمل تحويل النص الأولي/الخام إلى ترميزات الكلمات واستخراج ميزات مهمة مثل الحواف أو الأشكال من بيانات الصور/الفيديو. ### تجزئة التغذية الأمامية (feed forward chunking) في كل وحدة الانتباه الباقية في المحولات، تلي طبقة الاهتمام الانتباه عادة طبقتان للتغذية الأمامية. حجم تضمين الطبقة الأمامية الوسيطة أكبر عادة من حجم المخفي للنموذج (على سبيل المثال، لـ `google-bert/bert-base-uncased`). بالنسبة لإدخال بحجم `[batch_size, sequence_length]`، يمكن أن تمثل الذاكرة المطلوبة لتخزين التضمينات الأمامية الوسيطة `[batch_size، sequence_length, config.intermediate_size]` جزءًا كبيرًا من استخدام الذاكرة. لاحظ مؤلفو (https://huggingface.co/papers/2001.04451)[Reformer: The Efficient Transformer] أنه نظرًا لأن الحساب مستقل عن بعد `sequence_length`، فإنه من المكافئ رياضيًا حساب تضمينات الإخراج الأمامية `[batch_size، config.hidden_size]_0, ..., [batch_size، `config_size]_n فردياً والتوصيل بها لاحقًا إلى `[batch_size, sequence_length, config.hidden_size]` مع `n = sequence_length`، والذي يتداول زيادة وقت الحساب مقابل تقليل استخدام الذاكرة، ولكنه ينتج عنه نتيجة مكافئة رياضيا. بالنسبة للنماذج التي تستخدم الدالة `[apply_chunking_to_forward]`، يحدد `chunk_size` عدد التضمينات يتم حساب الإخراج بالتوازي وبالتالي يحدد المقايضة بين حجم الذاكرة والتعقيد الوقت. إذا تم تعيين `chunk_size` إلى `0`، فلن يتم إجراء تجزئة التغذية الأمامية. ### النماذج المضبوطة (finetuned models) الضبط الدقيق هو شكل من أشكال نقل التعلم، يتضمن أخذ نموذج مُدرّب مسبقًا، وتجميد أوزانه، واستبدال طبقة الإخراج برأس نموذج مُضاف حديثًا. يتم تدريب رأس النموذج على مجموعة البيانات المستهدفة. راجع البرنامج التعليمي [Fine-tune a pretrained model](https://huggingface.co/docs/transformers/training) لمزيد من التفاصيل، وتعرف على كيفية ضبط النماذج باستخدام 🤗 Transformers. ## H ### رأس النموذج (head) يشير رأس النموذج إلى الطبقة الأخيرة من الشبكة العصبية التي تقبل الحالات المخفية الخام/الأولية وتُسقطها على بُعد مختلف. يوجد رأس نموذج مختلف لكل مهمة. * [`GPT2ForSequenceClassification`] هو رأس تصنيف تسلسل - طبقة خطية - أعلى نموذج [`GPT2Model`] الأساسي. * [`ViTForImageClassification`] هو رأس تصنيف صورة - طبقة خطية أعلى حالة مخفية نهائية للرمز `CLS` - أعلى نموذج [`ViTModel`] الأساسي. * [`Wav2Vec2ForCTC`] هو رأس نمذجة اللغة مع [CTC](#connectionist-temporal-classification-ctc) أعلى نموذج [`Wav2Vec2Model`] الأساسي. ## I ### رقعة الصور (image patch) "رقعة الصورة" في نماذج المحولات البصرية، تُقسم الصورة إلى أجزاء أصغر تسمى "رقعات". يتم تمثيل كل رقعة بشكل رقمي (تحويلها إلى مجموعة من الأرقام) ثم تُعالج كسلسلة من البيانات. يمكنك العثور على حجم الرُقعة patch_size - أو دقتها - في إعدادات النموذج. ### الاستدلال (Inference) الاستدلال هو عملية تقييم نموذج على بيانات جديدة بعد اكتمال التدريب. راجع البرنامج التعليمي [Pipeline for inference](https://huggingface.co/docs/transformers/pipeline_tutorial) لمعرفة كيفية إجراء الاستدلال باستخدام 🤗 Transformers. ### معرفات الإدخال (input IDs) معرفات الإدخال هي غالبًا المعلمات المطلوبة الوحيدة التي يجب تمريرها إلى النموذج كإدخال. هذه المعرفات عبارة عن أرقام تمثل كل كلمة أو رمز في الجملة التي نريد أن يفهمها النموذج. بمعنى آخر، هي طريقة لترجمة الكلمات إلى أرقام يتم استخدامها كإدخال بواسطة النموذج. <Youtube id="VFp38yj8h3A"/> يعمل كل محلل لغوي بشكل مختلف ولكن الآلية الأساسية تبقى كما هي. إليك مثال باستخدام محلل BERT اللغوي، والذي يعد محلل لغوي [WordPiece](https://huggingface.co/papers/1609.08144): ```python >>> from transformers import BertTokenizer >>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased") >>> sequence = "A Titan RTX has 24GB of VRAM" ``` يتولى المحلل اللغوي مهمة تقسيم التسلسل إلى رموز مميزة متوفرة في قاموس المحلل اللغوي. ```python >>> tokenized_sequence = tokenizer.tokenize(sequence) ``` االرموز إما كلمات أو أجزاء كلمات. هنا على سبيل المثال، لم تكن كلمة "VRAM" موجودة في مفردات النموذج، لذلك تم تقسيمها إلى "V" و "RA" و "M". للإشارة إلى أن هذه الرموز ليست كلمات منفصلة ولكنها أجزاء من نفس الكلمة، تمت إضافة بادئة مزدوجة (#) إلى "RA" و "M": ```python >>> print(tokenized_sequence) ['A', 'Titan', 'R', '##T', '##X', 'has', '24', '##GB', 'of', 'V', '##RA', '##M'] ``` ```python >>> print(tokenized_sequence) ['A'، 'Titan'، 'R'، '##T'، '##X'، 'has'، '24'، '##GB'، 'of'، 'V'، '##RA'، '##M'] ``` يمكن بعد ذلك تحويل هذه الرموز إلى مُعرفات يفهمها النموذج. يمكن القيام بذلك عن طريق تغذية الجملة مباشرةً إلى مُجزّئ الرموز، والذي يستفيد من تنفيذ 🤗 Tokenizers بلغة Rust للحصول على أعلى أداء. ```python >>> inputs = tokenizer(sequence) ``` يقوم المحلل اللغوي بإرجاع قاموس يحتوي على جميع المعلومات التي يحتاجها النموذج للعمل بشكل صحيح. وتوجد مؤشرات الرموز المميزة تحت مفتاح `input_ids`: ```python >>> encoded_sequence = inputs["input_ids"] >>> print(encoded_sequence) [101، 138، 18696، 155، 1942، 3190، 1144، 1572، 13745، 1104، 159، 9664، 2107، 102] ``` لاحظ أن المحلل اللغوي يضيف تلقائيًا "رموزًا خاصة" (إذا كان النموذج المرتبط يعتمد عليها) وهي معرفات خاصة يستخدمها النموذج في بعض الأحيان. إذا قمنا بفك تشفير التسلسل السابق، ```python >>> decoded_sequence = tokenizer.decode(encoded_sequence) ``` سنرى ```python >>> print(decoded_sequence) [CLS] A Titan RTX has 24GB of VRAM [SEP] ``` لأن هذه هي الطريقة التي يتوقع بها نموذج [`BertModel`] إدخالاته. ## L ### االملصقات (Labels) هي معامل اختياري يمكن إدخاله في النموذج لحساب الخسارة بنفسه. نماذج تصنيف التسلسل: ([BertForSequenceClassification]) يتوقع النموذج مصفوفة ذات بعد (batch_size) حيث تتوافق كل قيمة من المجموعة مع الملصق المتوقع للتسلسل بأكمله. نماذج تصنيف الرمز: ([BertForTokenClassification]) يتوقع النموذج مصفوفة ذات بعد (batch_size, seq_length) حيث تتوافق كل قيمة مع الملصق المتوقع لكل رمز فردي. نماذج النمذجة اللغوية المقنعة:([BertForMaskedLM]) يتوقع النموذج مصفوفة ذات بعد (batch_size, seq_length) حيث تتوافق كل قيمة مع الملصق المتوقع لكل رمز فردي: تكون الملصقات هي معرف رمز الكلمة المقنعة، والقيم الأخرى يتم تجاهلها (عادةً -100). مهام التسلسل إلى التسلسل: ([BartForConditionalGeneration], [MBartForConditionalGeneration]) يتوقع النموذج مصفوفة ذات بعد (batch_size, tgt_seq_length) حيث تتوافق كل قيمة مع التسلسل الهدف المرتبط بكل تسلسل مدخل. أثناء التدريب، سيقوم كل من BART و T5 بإنشاء decoder_input_ids و decoder attention masks داخليًا. عادةً لا يلزم توفيرها. هذا لا ينطبق على النماذج التي تستخدم إطار العمل Encoder-Decoder. نماذج تصنيف الصور: ([ViTForImageClassification]) يتوقع النموذج مصفوفة ذات بعد (batch_size) حيث تتوافق كل قيمة من المجموعة مع الملصق المتوقع لكل صورة فردية. نماذج التقسيم الدلالي: ([SegformerForSemanticSegmentation]) يتوقع النموذج مصفوفة ذات بعد (batch_size, height, width) حيث تتوافق كل قيمة من المجموعة مع الملصق المتوقع لكل بكسل فردي. نماذج اكتشاف الأجسام: ([DetrForObjectDetection]) يتوقع النموذج قائمة من القواميس تحتوي على مفتاح class_labels و boxes حيث تتوافق كل قيمة من المجموعة مع الملصق المتوقع وعدد المربعات المحيطة بكل صورة فردية. نماذج التعرف التلقائي على الكلام: ([Wav2Vec2ForCTC]) يتوقع النموذج مصفوفة ذات بعد (batch_size, target_length) حيث تتوافق كل قيمة مع الملصق المتوقع لكل رمز فردي. <Tip> قد تختلف تسميات كل نموذج، لذا تأكد دائمًا من مراجعة وثائق كل نموذج للحصول على معلومات حول التسميات الخاصة به. </Tip> لا تقبل النماذج الأساسية ([`BertModel`]) الملصقات ، لأنها نماذج المحول الأساسية، والتي تقوم ببساطة بإخراج الميزات. ### نماذج اللغة الكبيرة large language models (LLM) مصطلح عام يشير إلى نماذج اللغة المحولة (GPT-3 و BLOOM و OPT) التي تم تدريبها على كمية كبيرة من البيانات. تميل هذه النماذج أيضًا إلى وجود عدد كبير من المعلمات القابلة للتعلم (على سبيل المثال، 175 مليار لمعلمة GPT-3). ## M ### نمذجة اللغة المقنعة masked language modeling (MLM) مهمة تدريب مسبق حيث يرى النموذج نسخة تالفة من النصوص، وعادة ما يتم ذلك عن طريق حجب بعض الرموز بشكل عشوائي، ويتعين على النموذج التنبؤ بالنص الأصلي. ### متعدد الوسائط (multimodal) مهمة تجمع بين النصوص مع نوع آخر من المدخلات (على سبيل المثال، الصور). ## N ### توليد اللغة الطبيعية Natural language generation (NLG) جميع المهام المتعلقة بتوليد النص (على سبيل المثال، [اكتب باستخدام المحولات](https://transformer.huggingface.co/)، والترجمة). ### معالجة اللغة الطبيعية Natural language processing (NLP) طريقة عامة للقول "التعامل مع النصوص". ### فهم اللغة الطبيعية Natural language understanding (NLU) جميع المهام المتعلقة بفهم ما هو موجود في نص (على سبيل المثال تصنيف النص بأكمله، أو الكلمات الفردية). ## P ### خط الأنابيب (pipeline) في مكتبة Transformers، يُشير مصطلح "خط الأنابيب" إلى سلسلة من الخطوات التي يتم تنفيذها بترتيب محدد لمعالجة البيانات وتحويلها وإرجاع تنبؤ من نموذج. بعض المراحل الشائعة في خط الأنابيب قد تشمل معالجة البيانات الأولية، واستخراج الميزات، والتوحيد. للحصول على مزيد من التفاصيل، راجع [خطوط الأنابيب للاستدلال](https://huggingface.co/docs/transformers/pipeline_tutorial). ### التوازي على مستوى خط الأنابيب (PipelineParallel) تقنية توازي يتم فيها تقسيم النموذج رأسياً (على مستوى الطبقة) عبر وحدات معالجة الرسومات (GPU) متعددة، بحيث توجد طبقة واحدة أو عدة طبقات من النموذج على وحدة معالجة الرسومات (GPU) واحدة فقط. تقوم كل وحدة معالجة رسومات (GPU) بمعالجة مراحل مختلفة من خط الأنابيب بالتوازي والعمل على جزء صغير من الدفعة. تعرف على المزيد حول كيفية عمل PipelineParallel [هنا](perf_train_gpu_many#from-naive-model-parallelism-to-pipeline-parallelism). ### قيم البكسل (pixel values) مصفوفة من التمثيلات الرقمية لصورة يتم تمريرها إلى نموذج. تأخذ قيم البكسل شكل [`batch_size`، `num_channels`، `height`، `width`]، ويتم إنشاؤها من معالج الصور. ### التجميع (Pooling) هي عملية تقوم بتقليص مصفوفة إلى مصفوفة أصغر، إما عن طريق أخذ القيمة القصوى أو المتوسط الحسابي للأبعاد التي يتم تجميعها. توجد طبقات التجميع بشكل شائع بين الطبقات التلافيفية convolutional layers لتقليل حجم تمثيل الميزات. ### معرفات الموضع (position IDs) على عكس الشبكات العصبية المتكررة (RNNs) التي تتضمن موضع كل رمز (token) ضمن بنيتها، لا تدرك المحولات موضع كل رمز. لذلك، تستخدم معرفات الموضع (`position_ids`) من قبل النموذج لتحديد موضع كل رمز في قائمة الرموز. إنها معلمة اختيارية. إذا لم يتم تمرير أي `position_ids` إلى النموذج، يتم إنشاء المعرفات تلقائيًا كترميزات موضعية مطلقة. يتم اختيار الترميزات الموضعية المطلقة في النطاق `[0، config.max_position_embeddings - 1]`. تستخدم بعض النماذج أنواعًا أخرى من الترميزات الموضعية، مثل الترميزات الموضعية الجيبية أو الترميزات الموضعية النسبية. ### ما قبل المعالجة (preprocessing) مهمة إعداد البيانات الخام بتنسيق يمكن أن تستهلكه نماذج التعلم الآلي بسهولة. على سبيل المثال، عادةً ما تتم معالجة النص مسبقًا عن طريق التمييز. للحصول على فكرة أفضل عن كيفية ظهور المعالجة المسبقة لأنواع الإدخال الأخرى، راجع البرنامج التعليمي [Preprocess](https://huggingface.co/docs/transformers/preprocessing). ### النموذج المسبق التدريب (pretrained model) نموذج تم تدريبه مسبقًا على بعض البيانات (على سبيل المثال، كل Wikipedia). تنطوي طرق التدريب المسبق على هدف ذاتي الإشراف، والذي يمكن أن يكون قراءة النص ومحاولة التنبؤ بالكلمة التالية ( راجع (causal-language-modeling#)[نمذجة اللغة السببية] ) أو قناع بعض الكلمات ومحاولة التنبؤ بها ( راجع (masked-language#)[نمذجة اللغة المقنعة]- عرض MLM). لدى نماذج الكلام والرؤية أهدافها التدريبية المسبقة الخاصة. على سبيل المثال، Wav2Vec2 هو نموذج كلام تم تدريبه مسبقًا على مهمة تباينية تتطلب من النموذج تحديد تمثيل الكلام "الحقيقي" من مجموعة من تمثيلات الكلام "الخاطئة". من ناحية أخرى، BEiT هو نموذج رؤية تم تدريبه مسبقًا على مهمة نمذجة صورة مقنعة تقوم بقناع بعض رقع الصورة وتتطلب من النموذج التنبؤ بالرقع المقنعة (مشابهة لهدف نمذجة اللغة المقيدة). ## R ### شبكة عصبية متكررة (RNN) هي نوع من النماذج التي تستخدم حلقة متكررة فوق طبقة معينة لمعالجة النصوص. ### التعلم التمثيلي (representation learning) هو فرع من فروع تعلم الآلة يركز على تعلم تمثيلات ذات معنى للبيانات الخام. بعض الأمثلة على تقنيات التعلم التمثيلي تشمل تضمين الكلمات، والمشفرات ذاتية، وشبكات التنافس التوليدية(GANs). ## S ### معدل العينات (sampling rate) قياس، بالهرتز، لعدد العينات (إشارة الصوت) المأخوذة في الثانية. ينتج معدل العينات عن تمييز إشارة مستمرة مثل الكلام. ### الانتباه الذاتي (Self-Attention) هو آلية تتيح لكل عنصر في المدخل أن يحدد أي العناصر الأخرى في نفس المدخل يجب أن ينتبه إليها. ### التعلم الذاتي الخاضع للإشراف (supervised learning) فئة من تقنيات التعلم الآلي التي يقوم فيها النموذج بإنشاء هدفه التعليمي الخاص من البيانات غير الموسومة. يختلف عن [التعلم غير الخاضع للإشراف](#unsupervised-learning) و [التعلم الخاضع للإشراف](#supervised-learning) في أن عملية التعلم خاضعة للإشراف، ولكن ليس صراحة من المستخدم. مثال واحد على التعلم الذاتي الخاضع للإشراف هو [نمذجة اللغة المقيدة](#masked-language- عرض MLM)، حيث يتم تمرير جمل للنموذج مع إزالة نسبة من رموزه ويتعلم التنبؤ بالرموز المفقودة. ### التعلم شبه الخاضع للإشراف (semi-supervised learning) فئة واسعة من تقنيات تدريب التعلم الآلي التي تستفيد من كمية صغيرة من البيانات الموسومة مع كمية أكبر من البيانات غير الموسومة لتحسين دقة النموذج، على عكس [التعلم الخاضع للإشراف](#supervised-learning) و [التعلم غير الخاضع للإشراف](#unsupervised-learning). مثال على نهج التعلم شبه الخاضع للإشراف هو "التدريب الذاتي"، حيث يتم تدريب نموذج على بيانات موسومة، ثم يستخدم لتقديم تنبؤات حول البيانات غير الموسومة. يتم إضافة الجزء من البيانات غير الموسومة التي يتنبأ بها النموذج بأكبر قدر من الثقة إلى مجموعة البيانات الموسومة ويتم استخدامها لإعادة تدريب النموذج. ### تسلسل إلى تسلسل (seq2seq) نماذج تولد تسلسلًا جديدًا من إدخال، مثل نماذج الترجمة، أو نماذج التلخيص (مثل [Bart](model_doc/bart) أو [T5](model_doc/t5)). ### Sharded DDP اسم آخر لمفهوم [Zero Redundancy Optimizer](#zero-redundancy-optimizer-zero) الأساسي كما هو مستخدم من قبل العديد من التطبيقات الأخرى لـ Zero. ### الخطوة (Stride) في العمليات التلافيفية أو التجميعية، تشير الخطوة إلى المسافة التي يتحرك بها النواة (kernel) فوق المصفوفة. خطوة تساوي 1 تعني أن النواة تتحرك بكسل واحد في كل مرة. ### التعلم الخاضع للإشراف (supervised learning) هو نوع من تدريب النماذج التي تستخدم بيانات مُعلَّمة بشكل مباشر لتصحيح أداء النموذج وتوجيهه. يتم تغذية البيانات إلى النموذج قيد التدريب، ويتم مقارنة تنبؤاته بالنتائج الصحيحة المعروفة. يقوم النموذج بتعديل أوزانه بناءً على مدى خطأ تنبؤاته، وتتكرر هذه العملية لتحسين أداء النموذج. ## T ### توازي Tensor (TP) تقنية توازي لتدريب وحدات معالجة الرسومات (GPU) متعددة يتم فيها تقسيم المصفوفة إلى عدة أجزاء، لذا بدلاً من وجود المصفوفة بأكملها على وحدة معالجة الرسومات (GPU) واحدة، توجد كل شظية من المصفوفة على وحدة معالجة الرسومات (GPU) المخصصة لها. تتم معالجة الشظايا بشكل منفصل وبالتوازي على وحدات معالجة الرسومات (GPU) المختلفة ويتم مزامنة النتائج في نهاية خطوة المعالجة. هذا ما يُطلق عليه أحيانًا التوازي الأفقي، حيث يحدث الانقسام على المستوى الأفقي. تعرف على المزيد حول توازي Tensor [هنا](perf_train_gpu_many#tensor-parallelism). ### الرمز اللغوي (Token) جزء من جملة، عادة ما يكون كلمة، ولكن يمكن أن يكون أيضًا كلمة فرعية (غالبًا ما يتم تقسيم الكلمات غير الشائعة إلى كلمات فرعية) أو علامة ترقيم. ### معرفات نوع الرمز (token type ids) الغرض من بعض النماذج هو إجراء التصنيف على أزواج من الجمل أو الإجابة على الأسئلة. <Youtube id="0u3ioSwev3s"/> يتطلب ذلك تسلسلين مختلفين يتم دمجهما في إدخال "input_ids" واحد، والذي يتم عادةً باستخدام رموز خاصة، مثل رموز التصنيف (`[CLS]`) والفاصل (`[SEP]`). على سبيل المثال، يقوم نموذج BERT ببناء إدخال تسلسلين على النحو التالي: ```python >>> # [CLS] SEQUENCE_A [SEP] SEQUENCE_B [SEP] ``` يمكننا استخدام برنامجنا للتمييز لإنشاء مثل هذه الجملة تلقائيًا عن طريق تمرير التسلسلين إلى `tokenizer` كمعامليين (وليس قائمة، كما كان من قبل) مثل هذا: ```python >>> from transformers import BertTokenizer >>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased") >>> sequence_a = "HuggingFace is based in NYC" >>> sequence_b = "Where is HuggingFace based?" >>> encoded_dict = tokenizer(sequence_a، sequence_b) >>> decoded = tokenizer.decode(encoded_dict["input_ids"]) ``` والذي سيعيد: ```python >>> print(decoded) [CLS] HuggingFace is based in NYC [SEP] Where is HuggingFace based؟ [SEP] ``` هذا يكفي لبعض النماذج لفهم أين ينتهي تسلسل واحد وأين يبدأ الآخر. ومع ذلك، تستخدم نماذج أخرى، مثل BERT، أيضًا معرفات نوع الرمز (يُطلق عليها أيضًا معرفات الجزء). يتم تمثيلها كماسك ثنائي لتحديد نوعي التسلسل في النموذج. يعيد برنامج الترميز هذا القناع كإدخال "token_type_ids": ```python >>> encoded_dict["token_type_ids"] [0، 0، 0، 0، 0، 0، 0، 0، 0، 0، 1، 1، 1، 1، 1، 1، 1، 1، 1] ``` يتم تمثيل التسلسل الأول، "السياق" المستخدم للسؤال، بجميع رموزه بواسطة `0`، في حين يتم تمثيل التسلسل الثاني، المقابل إلى "السؤال"، بجميع رموزه بواسطة `1`. تستخدم بعض النماذج، مثل [`XLNetModel`] رمزًا إضافيًا يمثله `2`. ### التعلم الانتقالي (Transfer Learning) تقنية تنطوي على أخذ نموذج تم تدريبه مسبقًا وتكييفه مع مجموعة بيانات خاصة بمهمتك. بدلاً من تدريب نموذج من الصفر، يمكنك الاستفادة من المعرفة المكتسبة من نموذج موجود كنقطة بداية. يسرع هذا عملية التعلم ويقلل من كمية بيانات التدريب المطلوبة. ### المحول (Transformer) هو بنية لنموذج تعلم عميق يعتمد على الانتباه الذاتي. ## U ### التعلم غير الخاضع للإشراف (unsupervised learning) شكل من أشكال تدريب النماذج حيث لا يتم وضع علامات على البيانات المقدمة إلى النموذج. تستفيد تقنيات التعلم غير الخاضعة للإشراف من المعلومات الإحصائية لتوزيع البيانات للعثور على الأنماط المفيدة للمهمة المعنية. ## Z ### محسن التكرار الصفري (ZeRO) تقنية توازي تقوم بتشظية المصفوفات بطريقة مشابهة لـ [TensorParallel](#tensor-parallelism-tp)، باستثناء إعادة بناء المصفوفة بالكامل في الوقت المناسب لحساب التقدير أو الحساب الخلفي، وبالتالي لا يلزم تعديل النموذج. تدعم هذه الطريقة أيضًا تقنيات الإخلاء المختلفة للتعويض عن ذاكرة GPU المحدودة. تعرف على المزيد حول Zero [هنا](perf_train_gpu_many#zero-data-parallelism).
transformers/docs/source/ar/glossary.md/0
{ "file_path": "transformers/docs/source/ar/glossary.md", "repo_id": "transformers", "token_count": 19554 }
377
# خطوط الأنابيب الاستدلال يجعل [`pipeline`] من السهل استخدام أي نموذج من [Hub](https://huggingface.co/models) للاستدلال لأي مهام خاصة باللغة أو الرؤية الحاسوبية أو الكلام أو المهام متعددة الوسائط. حتى إذا لم يكن لديك خبرة في طريقة معينة أو لم تكن على دراية بالرمز الأساسي وراء النماذج، يمكنك مع ذلك استخدامها للاستدلال باستخدام [`pipeline`]! سوف يُعلمك هذا البرنامج التعليمي ما يلي: * استخدام [`pipeline`] للاستدلال. * استخدم مُجزّئ أو نموذجًا محددًا. * استخدم [`pipeline`] للمهام الصوتية والبصرية والمتعددة الوسائط. <Tip> اطلع على وثائق [`pipeline`] للحصول على القائمة كاملة بالمهام المدعومة والمعلمات المتاحة. </Tip> ## استخدام الأنابيب على الرغم من أن لكل مهمة أنبوب [`pipeline`] خاص بها، إلا أنه من الأبسط استخدام تجريد خط الأنابيب العام [`pipeline`] الذي يحتوي على جميع خطوط الأنابيب الخاصة بالمهمة. يقوم [`pipeline`] تلقائيًا بتحميل نموذج افتراضي وفئة معالجة مسبقة قادرة على الاستدلال لمهمتك. دعنا نأخذ مثال استخدام [`pipeline`] للتعرف التلقائي على الكلام (ASR)، أو تحويل الكلام إلى نص. 1. ابدأ بإنشاء [`pipeline`] وحدد مهمة الاستدلال: ```py >>> from transformers import pipeline >>> transcriber = pipeline(task="automatic-speech-recognition") ``` 2. مرر إدخالك إلى [`pipeline`]. في حالة التعرف على الكلام، يكون هذا ملف إدخال صوتي: ```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'} ``` لم تحصل على النتيجة التي تريدها؟ تحقق من بعض [نماذج التعرف على الكلام الأكثر تنزيلًا](https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&sort=trending) على Hub لمعرفة ما إذا كان بإمكانك الحصول على نسخة منقحة أفضل. لنَجرب نموذج [Whisper large-v2](https://huggingface.co/openai/whisper-large) من OpenAI. تم إصدار Whisper بعد عامين من إصدار Wav2Vec2، وتم تدريبه على ما يقرب من 10 أضعاف كمية البيانات. وبهذه الصفة، فإنه يتفوق على Wav2Vec2 في معظم معظم المقاييس. كما أنه يمتلك ميزة إضافية وهي في التنبؤ بعلامات الترقيم وحالة الأحرف، والتي لا يمكن تحقيقها مع Wav2Vec2. دعونا نجربها هنا لنرى كيف تؤدي: ```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.'} ``` الآن تبدو هذه النتيجة أكثر دقة! لمقارنة عميقة حول Wav2Vec2 مقابل Whisper، راجع [دورة Audio Transformers](https://huggingface.co/learn/audio-course/chapter5/asr_models). نشجعك بشدة على التحقق من Hub للحصول على نماذج بلغات مختلفة، ونماذج متخصصة في مجالك، وأكثر من ذلك. يمكنك التحقق من نتائج النموذج ومقارنتها مباشرة من متصفحك على Hub لمعرفة ما إذا كان يناسبها أو التعامل مع الحالات الخاصة بشكل أفضل من غيرها. وإذا لم تجد نموذجًا لحالتك الاستخدام، فيمكنك دائمًا البدء في [التدريب](training) الخاص بك! إذا كان لديك عدة مدخلات، فيمكنك تمرير إدخالك كقائمة: ```py transcriber( [ "https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac", "https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac", ] ) ``` تعد خطوط الأنابيب مثالية للتجريب نظرًا لأن التبديل من نموذج إلى آخر أمر بسيط للغاية؛ ومع ذلك، هناك بعض الطرق لتحسينها لأحمال عمل أكبر من التجريب. راجع الأدلة التالية التي تتعمق فى التكرار عبر مجموعات البيانات الكاملة أو استخدام خطوط الأنابيب في خادم ويب: من الوثائق: * [استخدام خطوط الأنابيب على مجموعة بيانات](#using-pipelines-on-a-dataset) * [استخدام خطوط الأنابيب لخادم ويب](./pipeline_webserver) ## المعلمات يدعم [`pipeline`] العديد من المعلمات؛ بعضها خاص بالمهمة، والبعض الآخر عام لجميع خطوط الأنابيب. بشكل عام، يمكنك تحديد المعلمات في أي مكان تريده: ```py transcriber = pipeline(model="openai/whisper-large-v2", my_parameter=1) out = transcriber(...) # سيتم استخدام هذا `my_parameter=1`. out = transcriber(..., my_parameter=2) # سيتم تجاوز هذا واستخدام `my_parameter=2`. out = transcriber(...) # سيتم الرجوع إلى استخدام `my_parameter=1`. ``` دعونا نلقي نظرة على 3 مهمة: ### الجهاز إذا كنت تستخدم `device=n`، فإن خط الأنابيب يضع النموذج تلقائيًا على الجهاز المحدد. سيعمل هذا بغض النظر عما إذا كنت تستخدم PyTorch أو Tensorflow. ```py transcriber = pipeline(model="openai/whisper-large-v2", device=0) ``` إذا كان النموذج كبيرًا جدًا بالنسبة لوحدة معالجة الرسومات (GPU) واحدة، وأنت تستخدم PyTorch، فيمكنك تعيين `dtype='float16'` لتمكين الاستدلال بدقة FP16. عادةً ما لا يتسبب ذلك في حدوث انخفاضات كبيرة في الأداء، ولكن تأكد من تقييمه على نماذجك! بدلاً من ذلك، يمكنك تعيين `device_map="auto"` لتحديد كيفية تحميل مخزنات النموذج وتخزينها تلقائيًا. يتطلب استخدام معامل `device_map` مكتبه 🤗 [Accelerate](https://huggingface.co/docs/accelerate): ```bash pip install --upgrade accelerate ``` تقوم الشفرة التالية بتحميل مخزنات النموذج وتخزينها تلقائيًا عبر الأجهزة: ```py transcriber = pipeline(model="openai/whisper-large-v2", device_map="auto") ``` لاحظ أنه إذا تم تمرير `device_map="auto"`، فلا توجد حاجة لإضافة حجة `device=device` عند إنشاء خط الأنابيب الخاص بك، فقد تواجه بعض السلوكيات غير المتوقعة! ### حجم الدفعة بشكل افتراضي، لن تقوم خطوط الأنابيب بتجميع الاستدلال لأسباب مفصلة [هنا](https://huggingface.co/docs/transformers/main_classes/pipelines#pipeline-batching). والسبب هو أن التجميع ليست أسرع بالضرورة، ويمكن أن تكون أبطأ في الواقع في بعض الحالات. ولكن إذا نجحت في حالتك الاستخدام، فيمكنك استخدام ما يلي: ```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) ``` هذا يشغل خط الأنابيب على ملفات الصوت الأربعة المتاحة، ولكنه سيمررها على دفعتين إلى النموذج (الذي يوجد على وحدة معالجة الرسومات (GPU)، حيث من المرجح أن تساعد التجميع) دون الحاجة إلى أي رمز إضافي منك. يجب أن تتطابق الإخراج دائمًا مع ما كنت ستحصل عليه دون التجميع. المقصود منه فقط كطريقة لمساعدتك في الحصول على سرعة أكبر من خط الأنابيب. يمكن لخطوط الأنابيب أيضًا تخفيف بعض تعقيدات التجميع لأنه، بالنسبة لبعض خطوط الأنابيب، يجب تقسيم عنصر واحد (مثل ملف صوتي طويل) إلى أجزاء متعددة لمعالجته بواسطة نموذج. يقوم خط الأنابيب بأداء هذه العملية التي تسمى تجميع الأجزاء [*batch batching*](./main_classes/pipelines#pipeline-chunk-batching) نيابة عنك. ### معلمات خاصة بالمهمة توفر جميع المهام معلمات خاصة بالمهمة تتيح المرونة والخيارات الإضافية لمساعدتك في أداء عملك. على سبيل المثال، تحتوي طريقة [`transformers.AutomaticSpeechRecognitionPipeline.__call__`] على معلمة `return_timestamps` التي تبدو واعدة لترجمة مقاطع الفيديو: ```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.'}]} ``` كما ترون، استنتج النموذج النص.وكذلك حدد **وقت** نطق الجمل المختلفة. تتوفر العديد من المعلمات لكل مهمة، لذا تحقق من مرجع API لكل مهمة لمعرفة ما يمكنك تعديله! على سبيل المثال، تحتوي [`~transformers.AutomaticSpeechRecognitionPipeline`] على معلمة `chunk_length_s` مفيدة للعمل على ملفات الصوت الطويلة جدًا (على سبيل المثال، ترجمة الأفلام أو مقاطع الفيديو التي تستغرق ساعة) والتي لا يمكن للنموذج التعامل معها بمفرده: ```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"} ``` إذا لم تتمكن من العثور على معلمة قد تساعدك حقًا، فلا تتردد في [طلبها](https://github.com/huggingface/transformers/issues/new?assignees=&labels=feature&template=feature-request.yml)! ## استخدام خطوط الأنابيب على مجموعة بيانات يمكن أيضًا تشغيل خط الأنابيب للاستدلال على مجموعة بيانات كبيرة. أسهل طريقة نوصي بها للقيام بذلك هي باستخدام المتكرر (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"]) ``` يقوم المؤشر `data()` بإرجاع كل نتيجة، ويتعرف خط الأنابيب تلقائيًا المدخل قابل للتحديد ويبدأ في جلب البيانات أثناء يستمر في معالجتها على وحدة معالجة الرسومات (GPU) (يستخدم هذا [DataLoader](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader) تحت الغطاء). هذا أمر مهم لأنك لا تحتاج إلى تخصيص ذاكرة لمجموعة البيانات بأكملها ويمكنك تغذية وحدة معالجة الرسومات (GPU) بأسرع ما يمكن. نظرًا لأن التجميع قد تسرع الأمور، فقد يكون من المفيد ضبط معلمة `batch_size` هنا. أبسط طريقة للتنقل خلال مجموعة بيانات هي فقط تحميل واحدة من 🤗 [Datasets](https://github.com/huggingface/datasets/): ```py # KeyDataset هي أداة مساعدة ستقوم فقط بإخراج العنصر الذي نهتم به. 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) ``` ## استخدام خطوط الأنابيب لخادم ويب <Tip> إن إنشاء محرك استدلال هو موضوع معقد يستحق صفحته الخاصة. </Tip> [Link](./pipeline_webserver) ## خط أنابيب الرؤية إن استخدام [`pipeline`] لمهام الرؤية مماثل تمامًا. حدد مهمتك ومرر صورتك إلى المصنف. يمكن أن تكون الصورة رابطًا أو مسارًا محليًا أو صورة مشفرة بتنسيق base64. على سبيل المثال، ما نوع القطط الموضح أدناه؟ ![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'}] ``` ## خط أنابيب النص إن استخدام [`pipeline`] لمهام NLP مماثل تمامًا. ```py >>> from transformers import pipeline >>> # هذا النموذج هو نموذج "zero-shot-classification". >>> # سيصنف النص، ولكن يمكنك اختيار أي تسمية قد تتخيلها >>> 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]} ``` ## خط أنابيب متعدد الوسائط تدعم [`pipeline`] أكثر من طريقة واحدة. على سبيل المثال، تجمع مهمة الإجابة على الأسئلة المرئية (VQA) بين النص والصورة. لا تتردد في استخدام أي رابط صورة تريده وسؤال تريد طرحه حول الصورة. يمكن أن تكون الصورة عنوان URL أو مسارًا محليًا للصورة. على سبيل المثال، إذا كنت تستخدم هذه [صورة الفاتورة](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> لتشغيل المثال أعلاه، تحتاج إلى تثبيت [`pytesseract`](https://pypi.org/project/pytesseract/) بالإضافة إلى 🤗 Transformers: ```bash sudo apt install -y tesseract-ocr pip install pytesseract ``` </Tip> ## استخدام `pipeline` على نماذج كبيرة مع 🤗 `accelerate`: يمكنك بسهولة تشغيل `pipeline` على نماذج كبيرة باستخدام 🤗 `accelerate`! أولاً، تأكد من تثبيت `accelerate` باستخدام `pip install accelerate`. قم أولاً بتحميل نموذجك باستخدام `device_map="auto"`! سنستخدم `facebook/opt-1.3b` كمثال لنا. ```py # pip install accelerate import torch from transformers import pipeline pipe = pipeline(model="facebook/opt-1.3b", dtype=torch.bfloat16, device_map="auto") output = pipe("This is a cool example!", do_sample=True, top_p=0.95) ``` يمكنك أيضًا تمرير نماذج محملة بـ 8 بت إذا قمت بتثبيت `bitsandbytes` وإضافة الحجة `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) ``` لاحظ أنه يمكنك استبدال نقطة التفتيش بأي نموذج من Hugging Face يدعم تحميل النماذج الكبيرة، مثل BLOOM. ## إنشاء عروض توضيحية ويب من خطوط الأنابيب باستخدام `gradio` يتم دعم خطوط الأنابيب تلقائيًا في [Gradio](https://github.com/gradio-app/gradio/)، وهي مكتبة تجعل إنشاء تطبيقات تعليم الآلة الجميلة والسهلة الاستخدام على الويب أمرًا سهلاً. أولاً، تأكد من تثبيت Gradio: ``` pip install gradio ``` بعد ذلك، يمكنك إنشاء عرض توضيحي ويب حول خط أنابيب تصنيف الصور (أو أي خط أنابيب آخر) في سطر واحد من التعليمات البرمجية عن طريق استدعاء وظيفة [`Interface.from_pipeline`](https://www.gradio.app/docs/interface#interface-from-pipeline) في Gradio لإطلاق خط الأنابيب. يقوم هذا بإنشاء واجهة بديهية للسحب والإفلات في مستعرضك: ```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) بشكل افتراضي، يعمل العرض التوضيحي على خادم محلي. إذا كنت تريد مشاركتها مع الآخرين، فيمكنك إنشاء رابط عام مؤقت عن طريق تعيين `share=True` في `launch()`. يمكنك أيضًا استضافة عرضك التوضيحي على [Hugging Face Spaces](https://huggingface.co/spaces) للحصول على رابط دائم.
transformers/docs/source/ar/pipeline_tutorial.md/0
{ "file_path": "transformers/docs/source/ar/pipeline_tutorial.md", "repo_id": "transformers", "token_count": 10223 }
378
# كيف تُنجز نماذج 🤗 Transformers المهام؟ في [ما الذي يمكن أن تفعله نماذج 🤗 Transformers](task_summary)، تعلمت عن معالجة اللغات الطبيعية (NLP)، والخطاب والصوت، ورؤية الحاسب، وبعض تطبيقاتها المهمة. ستلقي هذه الصفحة نظرة فاحصة على كيفية حل النماذج لهذه المهام وتوضيح ما يحدث ما يحدث وراء الكواليس. هناك العديد من الطرق لحل مهمة معينة، وقد تنفذ بعض النماذج تقنيات معينة أو حتى تتناول المهمة من زاوية جديدة، ولكن بالنسبة لنماذج Transformer، فإن الفكرة العامة هي نفسها. وبفضل تصميمها المرن، فنظراً لهيكلها المرن، تُعدّ معظم النماذج عبارة عن متغير من بنية المُشفّر (Encoder) أو المُفكّك (Decoder) أو المُشفّر - المُفكّك (Encoder-Decoder). بالإضافة إلى نماذج Transformer، تحتوي مكتبتنا أيضًا على العديد من الشبكات العصبية التلافيفية (CNNs)، والتي لا تزال تستخدم حتى اليوم لمهام رؤية الحاسب. سنشرح أيضًا كيف تعمل شبكة عصبية تلافيفية CNN الحديثة. لشرح كيفية حل المهام، سنشرح ما يحدث داخل النموذج لإخراج تنبؤات مفيدة. - [Wav2Vec2](model_doc/wav2vec2) لتصنيف الصوت والتعرف التلقائي على الكلام (ASR) - [Vision Transformer (ViT)](model_doc/vit) و [ConvNeXT](model_doc/convnext) لتصنيف الصور - [DETR](model_doc/detr) للكشف عن الأجسام - [Mask2Former](model_doc/mask2former) لتجزئة الصورة - [GLPN](model_doc/glpn) لتقدير العمق - [BERT](model_doc/bert) لمهام NLP مثل تصنيف النصوص، وتصنيف الرموز، والإجابة على الأسئلة التي تستخدم مشفرًا - [GPT2](model_doc/gpt2) لمهام NLP مثل توليد النصوص التي تستخدم فك تشفير - [BART](model_doc/bart) لمهام NLP مثل الملخص والترجمة التي تستخدم ترميز-فك تشفير <Tip> قبل المتابعة، من الجيد أن يكون لديك بعض المعرفة الأساسية بهيكلية المحولات (Transformer Architecture) الأصلية. إن معرفة كيفية عمل المُشفّرات (Encoders) والمُفكّكات (Decoders) وآلية الانتباه (Attention Mechanism) سوف تساعدك في فهم كيفية عمل نماذج Transformer المختلفة. إذا كنت مبتدئًا أو بحاجة إلى مراجعة، فراجع [دورتنا](https://huggingface.co/course/chapter1/4؟fw=pt) لمزيد من المعلومات! </Tip> ## الكلام والصوت (Speech and audio) يُعدّ [Wav2Vec2](model_doc/wav2vec2) نموذجًا مُدرَّبًا ذاتيًا (Self-Supervised) على بيانات الكلام غير المُصنّفة، ويُمكن ضبطه بدقة (Fine-tuning) على بيانات موسومة لأداء مهام تصنيف الصوت والتعرف التلقائي على الكلام. <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/wav2vec2_architecture.png"/> </div> يتكون هذا النموذج على أربعة مكونات رئيسية: 1. *مشفّر الميزات (Feature Encoder)* يأخذ الموجة الصوتية الخام، ويقوم بتطبيعها (Normalization) إلى متوسط صفري وانحراف معياري وحدوي، وتحويلها إلى تسلسل من متجهات الميزات التي يبلغ طول كل منها 20 مللي ثانية. 2. *وحدة التكميم (Quantization Module):** تتميز أشكال الموجات الصوتية بطبيعتها المُستمرة،، لذلك لا يمكن تقسيمها إلى وحدات منفصلة كما يمكن تقسيم التسلسل النصّي إلى كلمات ولهذا السبب يتم تمرير متجهات الميزات إلى *وحدة التكميم*، والتي تهدف إلى تعلم وحدات الكلام المنفصلة. يتم اختيار وحدة الكلام من مجموعة من الرموز، والمعروفة باسم *كتاب الرموز* (يمكنك اعتبار هذا بمثابة المفردات). ومن كتاب الرموز،يتم اختيار المتجه أو وحدة الكلام التي تُمثّل مدخل الصوت المُستمر على أفضل وجه، ويتم تمريرها عبر النموذج. 3. **شبكة السياق (Context Network):** يتم إخفاء حوالي نصف متجهات الميزات بشكل عشوائي، ويتم تغذية متجه الميزة المُقنّع إلى *شبكة السياق*، والتي تعد مُشفّر محوّلات (Transformer Encoder) الذي يضيف أيضًا تضمينات موضعية نسبية (Relative Positional Embeddings).. 4. **مهمة التناقضية:** يتمثل الهدف من التدريب المسبق لشبكة السياق هو *مهمة تناقضية*. يجب على النموذج التنبؤ بالتمثيل الصحيح للكلام المُكمّم للتنبؤ المقنع من مجموعة من التمثيلات الخاطئة، مما يشجع النموذج على ا إيجاد متجه السياق ووحدة الكلام المُكمّمة الأكثر تشابهًا (التصنيف المستهدف). بمجرد تدريب Wav2Vec2 مسبقًا، يمكنك ضبط دقته على بياناتك لتصنيف الصوت أو التعرف التلقائي على الكلام! ### تصنيف الصوت (Audio classification) لاستخدام النموذج الذي تم تدريبه مسبقًا لتصنيف الصوت، أضف رأس تصنيف تسلسلي أعلى نموذج Wav2Vec2 الأساسي. رأس التصنيف هو طبقة خطية تستقبل الحالات المخفية للمشفر. تمثل الحالات المخفية الميزات التي تم تعلمها من كل إطار صوتي والذي يمكن أن يكون له أطوال مختلفة. لتحويلها إلى متجه واحد ثابت الطول، يتم تجميع الحالات المخفية أولاً ثم تحويلها إلى احتمالات عبر تصنيفات الفئات. يتم حساب التكلفة (الخسارة المتقاطعة) بين الاحتمالات والتصنيف المستهدف للعثور على الفئة الأكثر احتمالًا. هل أنت مستعد لتجربة تصنيف الصوت؟ تحقق من دليلنا الشامل [تصنيف الصوت](tasks/audio_classification) لمعرفة كيفية ضبط دقة نموذج Wav2Vec2 واستخدامه للاستدلال! ### التعرف التلقائي على الكلام (Automatic speech recognition - ASR) لاستخدام النموذج الذي تم تدريبه مسبقًا للتعرف التلقائي على الكلام، أضف رأس نمذجة لغوية أعلى نموذج Wav2Vec2 الأساسي لـ [[التصنيف الزمني الترابطي (CTC)](glossary#connectionist-temporal-classification-ctc). رأس النمذجة اللغوية عبارة عن طبقة خطية تقبل الحالات المخفية للمُشفّر وتحويلها إلى احتمالات. يمثل كل احتمال فئة رمزية (يأتي عدد الرموز من مفردات المهمة). يتم حساب تكلفة CTC بين الاحتمالات والأهداف للعثور على تسلسل الرموز الأكثر احتمالًا، والتي يتم فك تشفيرها بعد ذلك إلى نص مكتوب. هل أنت مستعد لتجربة التعرف التلقائي على الكلام؟ تحقق من دليلنا الشامل [التعرف التلقائي على الكلام](tasks/asr) لمعرفة كيفية ضبط دقة نموذج Wav2Vec2 واستخدامه للاستدلال! ## رؤية الحاسب (Computer vision) هناك طريقتان لتناول مهام رؤية الحاسب: 1. قم بتقسيم الصورة إلى تسلسل من الرقع ومعالجتها بالتوازي باستخدام مُحوّل Transformer. 2. استخدم شبكة عصبية تلافيفية CNN) حديثة، مثل [ConvNeXT](model_doc/convnext)، والتي تعتمد على الطبقات التلافيفية ولكنها تعتمد تصميمات حديثة للشبكات. <Tip> يقوم النهج الثالث بمزج المحولات مع التلافيف (على سبيل المثال، [Convolutional Vision Transformer](model_doc/cvt) أو [LeViT](model_doc/levit)). لن نناقشها لأنها تجمع ببساطة بين النهجين اللذين نستعرضهما هنا. </Tip> يتم استخدام ViT و ConvNeXT بشكل شائع لتصنيف الصور، ولكن بالنسبة لمهام الرؤية الأخرى مثل اكتشاف الكائنات والتجزئة وتقدير العمق، سنلقي نظرة على DETR و Mask2Former و GLPN، على التوالي؛ فهذه النماذج هي الأنسب لتلك المهام. ### تصنيف الصور (Image classification) يمكن استخدام كل من ViT و ConvNeXT لتصنيف الصور؛ الاختلاف الرئيسي هو أن ViT يستخدم آلية انتباه بينما يستخدم ConvNeXT الالتفافات. #### المحول Transformer [ViT](model_doc/vit) يستبدل التلافيف تمامًا بهندسة Transformer نقية. إذا كنت على دراية بـ Transformer الأصلي، فأنت بالفعل في طريقك إلى فهم ViT. <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/vit_architecture.jpg"/> </div> كان التغيير الرئيسي الذي قدمه ViT هو كيفية تغذية الصور إلى Transformer: 1. يتم تقسيم الصورة إلى رقع مربعة غير متداخلة، يتم تحويل كل منها إلى متجه أو يُسمى *تمثيل الرقعة*. يتم إنشاء تضمينات الرقع من طبقة تلافيفية ثنائية الأبعاد 2D والتي تقوم بإنشاء أبعاد الإدخال الصحيحة (والتي بالنسبة إلى Transformer الأساسي هي 768 قيمة لكل تضمين رقعة). إذا كان لديك صورة 224x224 بكسل، فيمكنك تقسيمها إلى 196 رقعة صورة 16x16. تمامًا مثل كيفية تجزئة النص إلى كلمات، يتم "تجزئة" الصورة إلى سلسلة من الرقع. 2. يتم إضافة *رمز قابل للتعلم* - تتم إضافة رمز خاص `[CLS]` - إلى بداية تمثيلات الرقع تمامًا مثل BERT. يتم استخدام الحالة المخفية النهائية للرمز `[CLS]` كمدخل لرأس التصنيف المُرفق؛ يتم تجاهل المخرجات الأخرى. تساعد هذه الرموز النموذج على تعلم كيفية ترميز تمثيل الصورة. 3. الشيء الأخير تتم إضافة "تمثيلات تموضع" إلى تمثيلات الرقع والرمز القابل للتعلم لأن النموذج لا يعرف كيفية ترتيب رقع الصورة. تكون تمثيلات التموضع قابلة للتعلم أيضًا ولها نفس حجم تمثيلات الرقع. وأخيرًا، يتم تمرير جميع التمثيلات إلى مُشفّر Transformer. 4. يتم تمرير الإخراج، وتحديدًا مخرج الرمز `[CLS]`، إلى رأس الإدراك المتعدد الطبقات (MLP). الهدف من التدريب المسبق لـ ViT هو التصنيف فقط. يقوم رأس MLP، مثل رؤوس التصنيف الأخرى، يحول رأس MLP المخرجات إلى احتمالات عبر تصنيفات الفئات ويحسب دالة التكلفة (الخسارة المتقاطعة) للعثور على الفئة الأكثر احتمالًا. هل أنت مستعد لتجربة تصنيف الصور؟ تحقق من دليلنا الشامل [تصنيف الصور](tasks/image_classification) لمعرفة كيفية ضبط دقة نموذج ViT واستخدامه للاستدلال! #### الشبكات العصبية التلافيفية (CNN) <Tip> يشرح هذا القسم بإيجاز الالتفافات، ولكن سيكون من المفيد أن يكون لديك فهم مسبق لكيفية تغيير شكل الصورة وحجمها. إذا كنت غير معتاد على الالتفافات، تحقق من [فصل الشبكات العصبية التلافيفية](https://github.com/fastai/fastbook/blob/master/13_convolutions.ipynb) من كتاب fastai! </Tip> [ConvNeXT](model_doc/convnext) هو بنية CNN تعتمد تصاميم الشبكات الجديدة والحديثة لتحسين الأداء. ومع ذلك، لا تزال الالتفافات هي جوهر النموذج. من منظور عام، [الالتفاف](glossary#convolution) هو عملية حيث يتم ضرب مصفوفة أصغر (*نواة*) بمقطع صغير من وحدات بكسل الصورة. يحسب بعض الميزات منه، مثل نسيج معين أو انحناء خط. ثم ينزلق إلى النافذة التالية من البكسلات؛ المسافة التي تقطعها الالتفاف تسمى *الخطوة*. <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/convolution.gif"/> </div> <small>عملية التفاف أساسية بدون حشو أو خطو خطوة واسعة، مأخوذة من <a href="https://huggingface.co/papers/1603.07285">دليل لحساب الالتفاف للتعلم العميق.</a></small> يمكنك تغذية هذا الناتج إلى طبقة التفاف أخرى، ومع كل طبقة متتالية، تتعلم الشبكة أشياء أكثر تعقيدًا وتجريدية مثل النقانق أو الصواريخ. بين طبقات الالتفاف، من الشائع إضافة طبقة تجميع لتقليل الأبعاد وجعل النموذج أكثر قوة للتغيرات في موضع الميزة. <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/convnext_architecture.png"/> </div> يقوم ConvNeXT بتحديث شبكة CNN بطرق خمس: 1. تغيير عدد الكتل في كل مرحلة و"ترقيع" الصورة باستخدام خطوة أكبر وحجم نواة المقابل. تجعل استراتيجية التجزئة غير المتداخلة استراتيجية الترقيع مشابهة للطريقة التي يقسم بها ViT للصورة إلى رقع. 2. تقلص طبقة *العنق الزجاجي* عدد القنوات ثم تعيدها لأنها أسرع في إجراء التفاف 1x1، ويمكنك زيادة العمق. يقوم عنق الزجاجة المقلوب بالعكس عن طريق توسيع عدد القنوات وتقلصها، وهو أكثر كفاءة من حيث الذاكرة. 3. استبدل طبقة الالتفاف النموذجية 3x3 في طبقة عنق الزجاجة بـ *الالتفاف بالعمق*، والذي يطبق الالتفاف على كل قناة إدخال بشكل منفصل ثم يقوم بتكديسها معًا مرة أخرى في النهاية. هذا يوسع عرض الشبكة لتحسين الأداء. 4. لدى ViT مجال استقبال عالمي مما يعني أنه يمكنه رؤية المزيد من الصورة في وقت واحد بفضل آلية الانتباه الخاصة به. تحاول ConvNeXT محاكاة هذا التأثير عن طريق زيادة حجم النواة إلى 7x7. 5. يقوم ConvNeXT أيضًا بإجراء العديد من تغييرات تصميم الطبقة التي تُحاكي نماذج المحولات. هناك عدد أقل من طبقات التنشيط والطبقات التطبيع، يتم تبديل دالة التنشيط إلى GELU بدلاً من ReLU، ويستخدم LayerNorm بدلاً من BatchNorm. يتم تمرير الإخراج من كتل الالتفاف إلى رأس تصنيف يحول المخرجات إلى احتمالات ويحسب دالة التكلفة (الخسارة المتقاطعة) للعثور على التصنيف الأكثر احتمالاً. ### اكتشاف الكائنات (Object detection) [DETR](model_doc/detr)، *DEtection TRansformer*، هو نموذج اكتشاف كائنات من البداية إلى النهاية يجمع بين CNN مع محول المشفر-فك التشفير. <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/detr_architecture.png"/> </div> 1. يأخذ العمود الفقري CNN *المدرب مسبقًا* صورة، ممثلة بقيم بكسلاتها، وينشئ خريطة ميزات منخفضة الدقة لها. يتم تطبيق التفاف 1x1 على خريطة الميزات لتقليل الأبعاد، و إنشاء خريطة ميزات جديدة بتمثيل صورة عالي المستوى. نظرًا لأن المحول (Transformer) هو نموذج تسلسلي، يتم تسوية خريطة الميزات إلى تسلسل من متجهات الميزات التي يتم دمجها مع تمثيلات التموضع. 2. يتم تمرير متجهات الميزات إلى المشفر، والذي يتعلم تمثيلات الصورة باستخدام طبقات الانتباه الخاصة به. بعد ذلك، يتم دمج الحالات المخفية للمُشفّر مع *استعلامات الكائنات* في فك التشفير. استعلامات الكائنات هي تمثيلات مكتسبة تركز على مناطق مختلفة من الصورة، ويتم تحديثها أثناء مرورها عبر كل طبقة انتباه. يتم تمرير الحالات المخفية لفك التشفير إلى شبكة تغذية أمامية التي تتنبأ بإحداثيات مربعات الإحاطة وتصنيف العلامة لكل استعلام كائن، أو `بدون كائن` إذا لم يكن هناك أي كائن. يقوم DETR بفك تشفير كل استعلام كائن بالتوازي لإخراج *N* من التنبؤات النهائية، حيث *N* هو عدد الاستعلامات. على عكس النموذج التلقائي الذي يتنبأ بعنصر واحد في كل مرة، فإن "اكتشاف الكائنات" هو مهمة تنبؤ بمجموعة من التنبؤات (مثل `مربع إحاطة`، `تصنيف`) تقوم بإجراء *N* من التنبؤات في مرور واحدة. 3. يستخدم DETR دالة *خسارة المطابقة ثنائية الفئات* أثناء التدريب لمقارنة عدد ثابت من التنبؤات بمجموعة ثابتة من تصنيفات البيانات الحقيقية. إذا كان هناك عدد أقل من تصنيفات البيانات الحقيقية في مجموعة *N* من التصنيفات، فيتم حشوها بفئة "بدون كائن". تشجع دالة الخسارة هذه DETR على العثور على تعيين واحد لواحد بين التنبؤات وتصنيفات البيانات الحقيقية. إذا لم تكن مربعات الإحاطة أو تصنيفات الفئات صحيحة، يتم تكبد خسارة. وبالمثل، إذا تنبأ DETR بكائن غير موجود، فإنه يتم معاقبته. وهذا يشجع DETR على العثور على كائنات أخرى في الصورة بدلاً من التركيز على كائن بارز حقًا. يتم إضافة رأس اكتشاف كائن أعلى DETR للعثور على تصنيف الكائن وإحداثيات مربع الإحاطة. هناك مكونان لرأس اكتشاف الكائنات: طبقة خطية لتحويل حالات فك التشفير المخفية إلى احتمالات عبر تصنيفات الفئات، وشبكةMLP للتنبؤ بمربع الإحاطة. هل أنت مستعد لتجربة اكتشاف الكائنات؟ تحقق من دليلنا الشامل [دليل اكتشاف الكائنات](tasks/object_detection) لمعرفة كيفية ضبط نموذج DETR واستخدامه للاستدلال! ### تجزئة الصورة (Image segmentation) يُعد [Mask2Former](model_doc/mask2former) بنيةً شاملةً لحل جميع أنواع مهام تجزئة الصور. عادةً ما تُصمم نماذج التجزئة التقليدية لمهمة فرعية محددة من مهام تجزئة الصور، مثل تجزئة المثيل أو التجزئة الدلالية أو التجزئة الشاملة. يصوغ Mask2Former كل مهمة من تلك المهام على أنها مشكلة *تصنيف الأقنعة*. يقوم تصنيف القناع بتجميع وحدات البكسل في *N* قطعة، ويتنبأ بـ *N* أقنعة وتصنيف الفئة المقابل لها لصورة معينة. سنشرح في هذا القسم كيفية عمل Mask2Former، ويمكنك بعد ذلك تجربة ضبط SegFormer في النهاية. <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/mask2former_architecture.png"/> </div> هناك ثلاثة مكونات رئيسية لـ Mask2Former: 1. العمود الفقري [Swin](model_doc/swin) يقبل صورة وينشئ خريطة ميزات منخفضة الدقة من 3 عمليات التفافات متتالية 3x3. 2. يتم تمرير خريطة الميزات إلى *فك تشفير البكسل* الذي يقوم تدريجياً بزيادة الميزات منخفضة الدقة إلى تمثيلات عالية الدقة لكل بكسل. في الواقع، يقوم فك تشفير البكسل بإنشاء ميزات متعددة المقاييس (تحتوي على كل من الميزات منخفضة وعالية الدقة) بدقة 1/32 و1/16 و1/8 من الصورة الأصلية. 3. يتم تغذية كل من خرائط الميزات ذات المقاييس المختلفة على التوالي إلى طبقة واحدة من طبقات فك التشفير في كل مرة لالتقاط الأجسام الصغيرة من ميزات الدقة العالية. يتمثل مفتاح Mask2Former آلية *الاهتمام المقنع* في فك التشفير. على عكس الانتباه المتقاطع الذي يمكن أن يركز على الصورة بأكملها، يركز الانتباه المقنع فقط على منطقة معينة من الصورة. هذا أسرع ويؤدي إلى أداء أفضل لأن الميزات المحلية لصورة كافية للنموذج للتعلم منها. 4. مثل [DETR](tasks_explained#object-detection)، يستخدم Mask2Former أيضًا استعلامات كائن مكتسبة ويجمعها مع ميزات الصورة من فك تشفير البكسل لإجراء تنبؤ مجموعة (`تصنيف الفئة`، `التنبؤ بالقناع`). يتم تمرير حالات فك التشفير المخفية إلى طبقة خطية وتحويلها إلى احتمالات عبر علامات التصنيف. يتم حساب دالة التكلفة (الخسارة المتقاطعة) بين الاحتمالات وتصنيف الفئة لتحديد الأكثر احتمالاً. يتم إنشاء تنبؤات الأقنعة عن طريق الجمع بين تمثيلات البكسل وحالات فك التشفير المخفية النهائية. يتم حساب دالة الخسارة المتقاطعة سيجمويد وخسارة النرد بين الاحتمالات والقناع البيانات الحقيقية للعثور على القناع الأكثر احتمالاً. هل أنت مستعد لتجربة يدك في اكتشاف الكائنات؟ تحقق من دليلنا الشامل [دليل تجزئة الصورة](tasks/semantic_segmentation) لمعرفة كيفية ضبط SegFormer واستخدامه للاستدلال! ### تقدير العمق (Depth estimation) [GLPN](model_doc/glpn)، شبكة المسار العالمية المحلية، هي محول ل تقدير العمق الذي يجمع بين مشفر [SegFormer](model_doc/segformer) مع فك تشفير خفيف الوزن. <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/glpn_architecture.jpg"/> </div> 1. مثل ViT، يتم تقسيم الصورة إلى تسلسل من الرقع، باستثناء أن هذه رقع الصورة أصغر. هذا أفضل لمهام التنبؤ الكثيفة مثل التجزئة أو تقدير العمق. يتم تحويل رقع الصورة إلى تمثيلات للرقع (راجع قسم [تصنيف الصور](#image-classification) لمزيد من التفاصيل حول كيفية إنشاء تمثيلات الرقع)، والتي يتم تغذيتها إلى المشفر. 2. يقبل المشفر تمثيلات الرقع، ويمررها عبر عدة كتل مشفرة. يتكون كل كتلة من طبقات انتباه وMix-FFN. الغرض من هذا الأخير هو توفير معلومات موضعية. في نهاية كل كتلة مشفرة توجد طبقة *دمج الرقع* لإنشاء تمثيلات هرمية. يتم دمج ميزات كل مجموعة من الرقع المجاورة، ويتم تطبيق طبقة خطية على الميزات المدمجة لتقليل عدد الرقع إلى دقة 1/4. يصبح هذا المُدخل للكتلة المشفرة التالية، حيث تتكرر هذه العملية بأكملها حتى تحصل على ميزات الصورة بدقة 1/8 و1/16 و1/32. 3. يقوم فك تشفير خفيف الوزن بأخذ خريطة الميزات الأخيرة (مقياس 1/32) من المشفر وزيادة حجمها إلى مقياس 1/16. من هنا، يتم تمرير الميزة إلى وحدة *دمج الميزات الانتقائية (SFF)*، والتي تقوم باختيار ودمج الميزات المحلية والعالمية من خريطة انتباه لكل ميزة ثم زيادة حجمها إلى 1/8. تتم إعادة هذه العملية حتى تصبح الميزات فك التشفير بنفس حجم الصورة الأصلية. يتم تمرير الإخراج عبر طبقتين تلافيفتين ثم يتم تطبيق تنشيط سيجمويد للتنبؤ بعمق كل بكسل. ## معالجة اللغات الطبيعية (Natural language processing -NLP) تم تصميم نموذج المحول Transformer في الأصل للترجمة الآلية، ومنذ ذلك الحين أصبح في الواقع البنية الافتراضية لحل جميع مهام NLP. تناسب بعض المهام بنية المشفر في نموذج المحول، في حين أن البعض الآخر أكثر ملاءمة لفك التشفير. لا تزال مهام أخرى تستخدم بنية المشفر-فك التشفير في نموذج المحول. ### تصنيف النصوص (Text classification) يعد [BERT](model_doc/bert) نموذج يعتمد على المُشفّر فقط، وهو أول نموذج يُطبق بشكل فعال ثنائية الاتجاه العميقة لتعلم تمثيلات أكثر ثراءً للنص من خلال الانتباه إلى الكلمات على كلا الجانبين. 1. يستخدم BERT تجزئة [WordPiece](tokenizer_summary#wordpiece) لإنشاء تمثيل رمزي للنص. للتمييز بين جملة واحدة وزوج من الجمل، تتم إضافة رمز خاص `[SEP]` للتفريق بينهما. تتم إضافة رمز خاص `[CLS]` إلى بداية كل تسلسل نصي. ويتم استخدام الإخراج النهائي مع الرمز `[CLS]` كمدخل لرأس التصنيف لمهام التصنيف. كما يضيف BERT تضمينًا للمقطع للإشارة إلى ما إذا كان الرمز ينتمي إلى الجملة الأولى أو الثانية في زوج من الجمل. 2. يتم تدريب BERT المسبق باستخدام هدفين: نمذجة اللغة المقنعة وتنبؤ الجملة التالية. في نمذجة اللغة المقنعة، يتم إخفاء نسبة مئوية مُعيّنة من رموز الإدخال بشكل عشوائي، ويجب على النموذج التنبؤ بها. يحل هذا مشكلة ثنائية الاتجاه، حيث يمكن للنموذج أن يغش ويرى جميع الكلمات و"يتنبأ" بالكلمة التالية. تتم تمرير الحالات المخفية النهائية للرموز المقنعة المتوقعة إلى شبكة تغذية أمامية مع دالة Softmax عبر مفردات اللغة للتنبؤ بالكلمة المقنعة. الهدف الثاني من التدريب المسبق هو توقع الجملة التالية. يجب على النموذج التنبؤ بما إذا كانت الجملة "ب" تتبع الجملة"أ". نصف الوقت تكون الجملة "ب" هي الجملة التالية، والنصف الآخر من الوقت، تكون الجملة "ب" عبارة عشوائية. يتم تمرير التنبؤ، سواء كانت الجملة التالية أم لا، إلى شبكة تغذية أمامية مع دالة Softmax عبر الفئتين (`IsNext` و`NotNext`). 3. يتم تمرير تمثيلات الإدخال عبر عدة طبقات مشفرة لإخراج بعض الحالات المخفية النهائية. لاستخدام النموذج المسبق التدريب لتصنيف النصوص، أضف رأس تصنيف تسلسلي أعلى نموذج BERT الأساسي. رأس تصنيف التسلسلي هو طبقة خطية تقبل الحالات المخفية النهائية وتجري تحويلًا خطيًا لتحويلها إلى احتمالات logits. يتم حساب دالة التكلفة (الخسارة المتقاطعة) بين logits والهدف للعثور على التصنيف الأكثر احتمالًا. هل أنت مستعد لتجربة تصنيف النصوص؟ تحقق من [دليل تصنيف النصوص](tasks/sequence_classification) الشامل الخاص بنا لمعرفة كيفية ضبط نموذج DistilBERT واستخدامه للاستنتاج! ### تصنيف الرموز (Token classification) لاستخدام BERT لمهام تصنيف الرموز مثل التعرف على الكيانات المسماة (NER)، أضف رأس تصنيف الرموز أعلى نموذج BERT الأساسي. رأس تصنيف الرموز هو طبقة خطية تقبل الحالات المخفية النهائية وتجري تحويلًا خطيًا لتحويلها إلى logits. يتم حساب دالة التكلفة (الخسارة المتقاطعة) بين logits وكل رمز للعثور على التصنيف الأكثر احتمالًا. هل أنت مستعد لتجربة تصنيف الرموز؟ تحقق من [دليل تصنيف الرموز](tasks/token_classification) الشامل الخاص بنا لمعرفة كيفية ضبط نموذج DistilBERT واستخدامه للاستنتاج! ### الإجابة على الأسئلة (Question answering) لاستخدام BERT للإجابة على الأسئلة، أضف رأس تصنيف المدى أعلى نموذج BERT الأساسي. تقبل هذه الطبقة الخطية الحالات المخفية النهائية وتُجري تحويلًا خطيًا لحساب داية ونهاية `الامتداد` logits `span` البداية والنهاية المقابلة للإجابة. يتم حسابدالة التكلفة (الخسارة المتقاطعة) بين logits وموقع التصنيف للعثور على الامتداد الأكثر احتمالًا من النص المقابل للإجابة. هل أنت مستعد لتجربة الإجابة على الأسئلة؟ راجع [دليل الإجابة على الأسئلة](tasks/question_answering) الشامل الخاص بنا لمعرفة كيفية ضبط نموذج DistilBERT واستخدامه في الاستدلال! <Tip> 💡 لاحظ مدى سهولة استخدام BERT لمهام مختلفة بمجرد تدريبه مسبقًا. كل ما تحتاج إليه هو إضافة رأس محدد إلى النموذج المسبق التدريب للتلاعب بالحالات المخفية إلى الإخراج المطلوب! </Tip> ### توليد النصوص (Text generation) يُعد [GPT-2](model_doc/gpt2) نموذجًا قائم على فك التشفير فقط تم تدريبه المسبق على كمية كبيرة من النصوص. يمكنه توليد نص مقنع (على الرغم من أنه ليس دائمًا صحيحًا!) بناءً على مُحفّز معين واستكمال مهام NLP الأخرى مثل الإجابة على الأسئلة على الرغم من أنه لم يتم تدريبه بشكل صريح على ذلك. <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gpt2_architecture.png"/> </div> 1. يستخدم GPT-2 [ترميز الأزواج البايتية (BPE)](tokenizer_summary#byte-pair-encoding-bpe) لتجزئة الكلمات وإنشاء تمثيل رمزى. يتم إضافة تمثيلات موضعية إلى تمثيلات الرموز للإشارة إلى موضع كل رمز في التسلسل. يتم تمرير تمثيلات الإدخال عبر عدة كتل فك تشفير لإخراج بعض الحالات المخفية النهائية. داخل كل كتلة فك تشفير، يستخدم GPT-2 طبقة *انتباه ذاتي مقنع* مما يعني أن GPT-2 لا يمكنه الانتباه بالرموز المستقبلية. يُسمح له فقط بالاهتمام بالرموز الموجودة على اليسار. يختلف هذا عن رمز [`mask`] الخاص بـ BERT لأنه، في الانتباه الذاتي المقنع، يتم استخدام قناع انتباه لتعيين النتيجة إلى `0` للرموز المستقبلية. 2. يتم تمرير الإخراج من فك التشفير إلى رأس نمذجة اللغة، والتي تُجري تحويلًا خطيًا لتحويل الحالات المخفية إلى احتمالات logits. التصنيف هو الرمز التالي في التسلسل، والذي يتم إنشاؤه عن طريق تغيير موضع logits إلى اليمين بمقدار واحد. يتم حساب دالة التكلفة (الخسارة المتقاطعة) بين logits التي تم تغيير موضعها والتصنيفات لإخراج الرمز التالي الأكثر احتمالًا. يستند هدف التدريب المسبق لـ GPT-2 بالكامل إلى [نمذجة اللغة السببية](glossary#causal-language-modeling)، والتنبؤ بالكلمة التالية في تسلسل. يجعل هذا GPT-2 جيدًا بشكل خاص في المهام التي تتضمن توليد النص. هل أنت مستعد لتجربة توليد النصوص؟ تحقق من دليل [دليل نمذجة اللغة السببية](tasks/language_modeling#causal- الشامل الخاص بنا لمعرفة كيفية ضبط نموذج DistilGPT-2 واستخدامه للاستنتاج! <Tip> للحصول على مزيد من المعلومات حول توليد النص، راجع دليل [استراتيجيات توليد النصوص](generation_strategies)! </Tip> ### التلخيص (Summarization) تم تصميم نماذج المشفر-فك التشفير مثل [BART](model_doc/bart) و [T5](model_doc/t5) لنمط تسلسل إلى تسلسل لمهمة التلخيص. سنشرح كيف يعمل BART في هذا القسم، ثم يمكنك تجربة ضبط T5 في النهاية. <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bart_architecture.png"/> </div> 1. تتشابه بنية المشفر BART كثيرًا مع BERT وتقبل رمزًا وتمثيلًا موضعيًا للنص. يتم تدريب BART مسبقًا عن طريق إتلاف المُدخلات ثم إعادة بنائه باستخدام فك التشفير. على عكس المشفرات الأخرى ذات استراتيجيات الإتلاف المحددة، يمكن لـ BART تطبيق أي نوع من الإتلاف. ومع ذلك، فإن استراتيجية إتلاف "ملء النص" تعمل بشكل أفضل. في ملء النص، يتم استبدال عدد من امتدادات النص برمز **واحد** [`mask`]. هذا أمر مهم لأن النموذج يجب أن يتنبأ بالرموز المقنعة، ويعلّم النموذج التنبؤ بعدد الرموز المفقودة. يتم تمرير تمثيلات الإدخال والامتدادات المقنعة عبر المشفر لإخراج بعض الحالات المخفية النهائية، ولكن على عكس BERT، لا يضيف BART شبكة تغذية أمامية نهائية في النهاية للتنبؤ بكلمة. 2. يتم تمرير إخراج المشفر إلى فك التشفير، والذي يجب أن يتنبأ بالرموز المقنعة وأي رموز غير تالفة من ناتج المشفر. يمنح هذا فك التشفير سياقًا إضافيًا للمساعدة في استعادة النص الأصلي. يتم تمرير ناتج فك التشفير إلى رأس نمذجة اللغوية، والذي يجري تحويلًا خطيًا لتحويل الحالات المخفية إلى احتمالات(logits). يتم حساب دالة التكلفة (الخسارة المتقاطعة) بين الاحتمالات logits والتصنيف، وهو مجرد الرمز الذي تم تغيير موضعه إلى اليمين. هل أنت مستعد لتجربة التلخيص؟ تحقق من دليل التلخيص الشامل الخاص بنا لمعرفة كيفية ضبط نموذج T5 واستخدامه للاستنتاج! <Tip> للحصول على مزيد من المعلومات حول توليد النص، راجع دليل استراتيجيات توليد النص! </Tip> ### الترجمة (Translation) تُعد الترجمة مثالًا آخر على مهام التسلسل إلى التسلسل، مما يعني أنه يمكنك استخدام نموذج المشفر-فك التشفير مثل [BART](model_doc/bart) أو [T5](model_doc/t5) للقيام بذلك. سنشرح كيف يعمل BART في هذا القسم، ثم يمكنك تجربة ضبط T5 في النهاية. يتكيف BART مع الترجمة عن طريق إضافة مشفر منفصل يتم تهيئته بشكل عشوائي لتعيين لغة المصدر بمدخلات يمكن فك تشفيرها إلى لغة الهدف. يتم تمرير تمثيلات هذا المشفر الجديد إلى المشفر المسبق التدريب بدلاً من تمثيلات الكلمات الأصلية. يتم تدريب مشفر المصدر عن طريق تحديث مشفر المصدر وتمثيلات التموضع وتمثيلات الإدخال باستخدام دالة التكلفة (الخسارة المتقاطعة) من ناتج النموذج. يتم تجميد معلمات النموذج في هذه الخطوة الأولى، ويتم تدريب جميع معلمات النموذج معًا في الخطوة الثانية. تم إصدار نسخة متعددة اللغات من BART، تسمى mBART، مُخصصة للترجمة ومُدرّبة مسبقًا على العديد من اللغات المختلفة. هل أنت مستعد لتجربة الترجمة؟ تحقق من دليل الترجمة الشامل الخاص بنا لمعرفة كيفية ضبط نموذج T5 واستخدامه للاستنتاج! <Tip> **للحصول على مزيد من المعلومات حول توليد النصوص، راجع دليل [استراتيجيات توليد النصوص](generation_strategies)!** </Tip>
transformers/docs/source/ar/tasks_explained.md/0
{ "file_path": "transformers/docs/source/ar/tasks_explained.md", "repo_id": "transformers", "token_count": 22792 }
379
<!--- 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. --> # Installation Installieren Sie 🤗 Transformers für die Deep-Learning-Bibliothek, mit der Sie arbeiten, richten Sie Ihren Cache ein und konfigurieren Sie 🤗 Transformers optional für den Offline-Betrieb. 🤗 Transformers wurde unter Python 3.6+, PyTorch 1.1.0+, TensorFlow 2.0+, und Flax getestet. Folgen Sie den Installationsanweisungen unten für die von Ihnen verwendete Deep-Learning-Bibliothek: * [PyTorch](https://pytorch.org/get-started/locally/) installation instructions. * [TensorFlow 2.0](https://www.tensorflow.org/install/pip) installation instructions. * [Flax](https://flax.readthedocs.io/en/latest/) installation instructions. ## Installation mit pip Sie sollten 🤗 Transformers in einer [virtuellen Umgebung](https://docs.python.org/3/library/venv.html) installieren. Wenn Sie mit virtuellen Python-Umgebungen nicht vertraut sind, werfen Sie einen Blick auf diese [Anleitung](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/). Eine virtuelle Umgebung macht es einfacher, verschiedene Projekte zu verwalten und Kompatibilitätsprobleme zwischen Abhängigkeiten zu vermeiden. Beginnen wir mit der Erstellung einer virtuellen Umgebung in Ihrem Projektverzeichnis: ```bash python -m venv .env ``` Aktivieren wir die virtuelle Umgebung. Unter Linux und MacOs: ```bash source .env/bin/activate ``` Aktivieren wir die virtuelle Umgebung unter Windows ```bash .env/Scripts/activate ``` Jetzt können wir die 🤗 Transformers mit dem folgenden Befehl installieren: ```bash pip install transformers ``` Bei reiner CPU-Unterstützung können wir 🤗 Transformers und eine Deep-Learning-Bibliothek bequem in einer Zeile installieren. Installieren wir zum Beispiel 🤗 Transformers und PyTorch mit: ```bash pip install transformers[torch] ``` 🤗 Transformers und TensorFlow 2.0: ```bash pip install transformers[tf-cpu] ``` 🤗 Transformers und Flax: ```bash pip install transformers[flax] ``` Überprüfen wir abschließend, ob 🤗 Transformers ordnungsgemäß installiert wurde, indem wir den folgenden Befehl ausführen. Es wird ein vortrainiertes Modell heruntergeladen: ```bash python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('we love you'))" ``` Dann wird die Kategorie und die Wahrscheinlichkeit ausgegeben: ```bash [{'label': 'POSITIVE', 'score': 0.9998704791069031}] ``` ## Installation aus dem Code Installieren wir 🤗 Transformers aus dem Quellcode mit dem folgenden Befehl: ```bash pip install git+https://github.com/huggingface/transformers ``` Dieser Befehl installiert die aktuelle `main` Version und nicht die neueste `stable` Version. Die `main`-Version ist nützlich, um mit den neuesten Entwicklungen Schritt zu halten. Zum Beispiel, wenn ein Fehler seit der letzten offiziellen Version behoben wurde, aber eine neue Version noch nicht veröffentlicht wurde. Das bedeutet jedoch, dass die "Hauptversion" nicht immer stabil ist. Wir bemühen uns, die Hauptversion einsatzbereit zu halten, und die meisten Probleme werden normalerweise innerhalb weniger Stunden oder eines Tages behoben. Wenn Sie auf ein Problem stoßen, öffnen Sie bitte ein [Issue](https://github.com/huggingface/transformers/issues), damit wir es noch schneller beheben können! Überprüfen wir, ob 🤗 Transformers richtig installiert wurde, indem Sie den folgenden Befehl ausführen: ```bash python -c "from transformers import pipeline; print(pipeline('sentiment-analysis')('I love you'))" ``` ## Editierbare Installation Sie benötigen eine bearbeitbare Installation, wenn Sie: * die "Haupt"-Version des Quellcodes verwenden möchten. * Zu 🤗 Transformers beitragen und Änderungen am Code testen wollen. Klonen Sie das Repository und installieren 🤗 Transformers mit den folgenden Befehlen: ```bash git clone https://github.com/huggingface/transformers.git cd transformers pip install -e . ``` Diese Befehle verknüpfen den Ordner, in den Sie das Repository geklont haben, mit den Pfaden Ihrer Python-Bibliotheken. Python wird nun in dem Ordner suchen, in den Sie geklont haben, zusätzlich zu den normalen Bibliothekspfaden. Wenn zum Beispiel Ihre Python-Pakete normalerweise in `~/anaconda3/envs/main/lib/python3.7/site-packages/` installiert sind, wird Python auch den Ordner durchsuchen, in den Sie geklont haben: `~/transformers/`. <Tip warning={true}> Sie müssen den Ordner `transformers` behalten, wenn Sie die Bibliothek weiter verwenden wollen. </Tip> Jetzt können Sie Ihren Klon mit dem folgenden Befehl ganz einfach auf die neueste Version von 🤗 Transformers aktualisieren: ```bash cd ~/transformers/ git pull ``` Ihre Python-Umgebung wird beim nächsten Ausführen die `main`-Version von 🤗 Transformers finden. ## Installation mit conda Installation von dem conda Kanal `conda-forge`: ```bash conda install conda-forge::transformers ``` ## Cache Einrichtung Vorgefertigte Modelle werden heruntergeladen und lokal zwischengespeichert unter: `~/.cache/huggingface/hub`. Dies ist das Standardverzeichnis, das durch die Shell-Umgebungsvariable "TRANSFORMERS_CACHE" vorgegeben ist. Unter Windows wird das Standardverzeichnis durch `C:\Benutzer\Benutzername\.cache\huggingface\hub` angegeben. Sie können die unten aufgeführten Shell-Umgebungsvariablen - in der Reihenfolge ihrer Priorität - ändern, um ein anderes Cache-Verzeichnis anzugeben: 1. Shell-Umgebungsvariable (Standard): `HF_HUB_CACHE` oder `TRANSFORMERS_CACHE`. 2. Shell-Umgebungsvariable: `HF_HOME`. 3. Shell-Umgebungsvariable: `XDG_CACHE_HOME` + `/huggingface`. <Tip> Transformers verwendet die Shell-Umgebungsvariablen `PYTORCH_TRANSFORMERS_CACHE` oder `PYTORCH_PRETRAINED_BERT_CACHE`, wenn Sie von einer früheren Iteration dieser Bibliothek kommen und diese Umgebungsvariablen gesetzt haben, sofern Sie nicht die Shell-Umgebungsvariable `TRANSFORMERS_CACHE` angeben. </Tip> ## Offline Modus Transformers ist in der Lage, in einer Firewall- oder Offline-Umgebung zu laufen, indem es nur lokale Dateien verwendet. Setzen Sie die Umgebungsvariable `HF_HUB_OFFLINE=1`, um dieses Verhalten zu aktivieren. <Tip> Fügen sie [🤗 Datasets](https://huggingface.co/docs/datasets/) zu Ihrem Offline-Trainingsworkflow hinzufügen, indem Sie die Umgebungsvariable `HF_DATASETS_OFFLINE=1` setzen. </Tip> So würden Sie beispielsweise ein Programm in einem normalen Netzwerk mit einer Firewall für externe Instanzen mit dem folgenden Befehl ausführen: ```bash python examples/pytorch/translation/run_translation.py --model_name_or_path google-t5/t5-small --dataset_name wmt16 --dataset_config ro-en ... ``` Führen Sie das gleiche Programm in einer Offline-Instanz mit aus: ```bash HF_DATASETS_OFFLINE=1 HF_HUB_OFFLINE=1 \ python examples/pytorch/translation/run_translation.py --model_name_or_path google-t5/t5-small --dataset_name wmt16 --dataset_config ro-en ... ``` Das Skript sollte nun laufen, ohne sich aufzuhängen oder eine Zeitüberschreitung abzuwarten, da es weiß, dass es nur nach lokalen Dateien suchen soll. ### Abrufen von Modellen und Tokenizern zur Offline-Verwendung Eine andere Möglichkeit, 🤗 Transformers offline zu verwenden, besteht darin, die Dateien im Voraus herunterzuladen und dann auf ihren lokalen Pfad zu verweisen, wenn Sie sie offline verwenden müssen. Es gibt drei Möglichkeiten, dies zu tun: * Laden Sie eine Datei über die Benutzeroberfläche des [Model Hub](https://huggingface.co/models) herunter, indem Sie auf das ↓-Symbol klicken. ![download-icon](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/download-icon.png) * Verwenden Sie den [PreTrainedModel.from_pretrained] und [PreTrainedModel.save_pretrained] Workflow: 1. Laden Sie Ihre Dateien im Voraus mit [`PreTrainedModel.from_pretrained`] herunter: ```py >>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM >>> tokenizer = AutoTokenizer.from_pretrained("bigscience/T0_3B") >>> model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0_3B") ``` 2. Speichern Sie Ihre Dateien in einem bestimmten Verzeichnis mit [`PreTrainedModel.save_pretrained`]: ```py >>> tokenizer.save_pretrained("./your/path/bigscience_t0") >>> model.save_pretrained("./your/path/bigscience_t0") ``` 3. Wenn Sie nun offline sind, laden Sie Ihre Dateien mit [`PreTrainedModel.from_pretrained`] aus dem bestimmten Verzeichnis: ```py >>> tokenizer = AutoTokenizer.from_pretrained("./your/path/bigscience_t0") >>> model = AutoModel.from_pretrained("./your/path/bigscience_t0") ``` * Programmatisches Herunterladen von Dateien mit der [huggingface_hub](https://github.com/huggingface/huggingface_hub/tree/main/src/huggingface_hub) Bibliothek: 1. Installieren Sie die "huggingface_hub"-Bibliothek in Ihrer virtuellen Umgebung: ```bash python -m pip install huggingface_hub ``` 2. Verwenden Sie die Funktion [`hf_hub_download`](https://huggingface.co/docs/hub/adding-a-library#download-files-from-the-hub), um eine Datei in einen bestimmten Pfad herunterzuladen. Der folgende Befehl lädt zum Beispiel die Datei "config.json" aus dem Modell [T0](https://huggingface.co/bigscience/T0_3B) in den gewünschten Pfad herunter: ```py >>> from huggingface_hub import hf_hub_download >>> hf_hub_download(repo_id="bigscience/T0_3B", filename="config.json", cache_dir="./your/path/bigscience_t0") ``` Sobald Ihre Datei heruntergeladen und lokal zwischengespeichert ist, geben Sie den lokalen Pfad an, um sie zu laden und zu verwenden: ```py >>> from transformers import AutoConfig >>> config = AutoConfig.from_pretrained("./your/path/bigscience_t0/config.json") ``` <Tip> Weitere Informationen zum Herunterladen von Dateien, die auf dem Hub gespeichert sind, finden Sie im Abschnitt [Wie man Dateien vom Hub herunterlädt](https://huggingface.co/docs/hub/how-to-downstream). </Tip>
transformers/docs/source/de/installation.md/0
{ "file_path": "transformers/docs/source/de/installation.md", "repo_id": "transformers", "token_count": 3996 }
380
<!--Copyright 2024 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 ⚠️ 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. --> # Legacy model contribution > [!TIP] > Try adding new models with a more [modular](./modular_transformers) approach first. This makes it significantly easier to contribute a model to Transformers! Many of the models in Transformers are contributed by developers and researchers. As an open-source first project, we're invested in empowering the community to actively and independently add more models. When you add a model to Transformers, you'll learn: - more about open-source best practices - about a models architecture - about Transformers' design principles - how to efficiently test large models - how to use Python utilities like [Black](https://black.readthedocs.io/en/stable/) and [Ruff](https://docs.astral.sh/ruff/) to create clean and readable code It is a challenging but rewarding process. This guide will walk you through adding an example BrandNewLlama PyTorch model to Transformers. Before you begin, it is a good idea to familiarize yourself with the library. ## Transformers overview Transformers is an opinionated library with its own unique philosophy and design choices. These choices help us sustainably scale and maintain Transformers. > [!TIP] > Learn more about our design principles on the [Philosophy](./philosophy) doc. Some of these design choices are: - composition > over-abstraction - duplicate code isn't always bad if it greatly improves readability and accessibility - model files are self-contained and all the necessary model code is found in the `modeling_mymodel.py` file These design choices are important *for everyone* interacting with the model. It is easier to read, understand, and modify. This section describes how the model and configuration classes interact and the Transformers code style. ### Model and configuration All Transformers' models inherit from a base [`PreTrainedModel`] and [`PretrainedConfig`] class. The configuration is the models blueprint. There is never more than two levels of abstraction for any model to keep the code readable. The example model here, BrandNewLlama, inherits from `BrandNewLlamaPreTrainedModel` and [`PreTrainedModel`]. It is important that a new model only depends on [`PreTrainedModel`] so that it can use the [`~PreTrainedModel.from_pretrained`] and [`~PreTrainedModel.save_pretrained`] methods. Other important functions like the forward method are defined in the `modeling.py` file. Specific model heads (for example, sequence classification or language modeling) should call the base model in the forward pass rather than inheriting from it to keep abstraction low. New models require a configuration, for example `BrandNewLlamaConfig`, that is stored as an attribute of [`PreTrainedModel`]. ```py model = BrandNewLlamaModel.from_pretrained("username/brand_new_llama") model.config ``` [`PretrainedConfig`] provides the [`~PretrainedConfig.from_pretrained`] and [`~PretrainedConfig.save_pretrained`] methods. When you use [`PreTrainedModel.save_pretrained`], it automatically calls [`PretrainedConfig.save_pretrained`] so that both the model and configuration are saved together. A model is saved to a `model.safetensors` file and a configuration is saved to a `config.json` file. ### Code style Transformers prefers a clean and readable code over a more abstracted code style. Some of the code style choices include: - The code should be accessible to non-English users. Pick descriptive variable names and avoid abbreviations. For example, "activation" is preferred over "act". One letter variables names are highly discouraged unless it's an index in a for loop. - Explicit code is preferred - even if it's longer - over shorter code. - Avoid subclassing [nn.Sequential](https://pytorch.org/docs/stable/generated/torch.nn.Sequential.html). Subclass [nn.Module](https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module) instead so the code can be quickly debugged with print statements or breakpoints. - Function signatures should be type-annotated. Otherwise, use good variable names so they're more understandable. ## New model addition issue Open a [New model addition](https://github.com/huggingface/transformers/issues/new?assignees=&labels=New+model&template=new-model-addition.yml) issue to add a specific model. > [!TIP] > Filter by the [New model](https://github.com/huggingface/transformers/labels/New%20model) label on GitHub to view and add any existing model requests. Now is a good time to get familiar with BrandNewLlama. It is helpful to read a models research paper to understand its technical design and implementation. You don't necessarily have to worry too much about the theoretical details. Instead, focus on the practical ones. Use the questions below to guide your reading. - What type of model is BrandNewLlama? Is it a encoder, decoder, or encoder-decoder model? - What tasks can BrandNewLlama be used for? - What makes BrandNewLlama different from other models? - What models in Transformers are most similar to BrandNewLlama? - What tokenizer does BrandNewLlama use? In addition to learning more about your model, use the tips below to help you add a model faster. > [!TIP] > Each contributor has a unique style and workflow for adding models to Transformers. For an example, take a look at how [Gemma](https://github.com/huggingface/transformers/pull/29167) was added. - Don't reinvent the wheel! Take your time to explore existing models and tokenizers to see what you can copy and reuse. [Grep](https://www.gnu.org/software/grep/) and [ripgrep](https://github.com/BurntSushi/ripgrep) are great tools for this. - This is more of an engineering than a science challenge. Focus on the more practical (setting up an efficient debugging environment for example) instead of the theorertical aspects of the model. - Don't be shy to ask for help! We are here to support you. 🤗 ## Dev environment Click on the **Fork** button on the [Transformers](https://github.com/huggingface/transformers) repository to create your own copy to work on. Clone the repository to your local disk and add the base repository as the remote. ```bash git clone https://github.com/[your Github handle]/transformers.git cd transformers git remote add upstream https://github.com/huggingface/transformers.git ``` Create a virtual environment and perform an [editable install](./installation#editable-install) of the library with the "dev" or development dependencies. ```bash python -m venv .env source .env/bin/activate pip install -e ".[dev]" ``` Due to the number of optional dependencies as Transformers grows, this command may fail. In this case, install the "quality" dependencies. Also make sure you have a deep learning framework installed. ```bash pip install -e ".[quality]" ``` Return to the parent directory and clone and install the original BrandNewLlama repository. ```bash git clone https://github.com/org_that_created_brand_new_llama_org/brand_new_llama.git cd brand_new_bert pip install -e . ``` Return to your clone of Transformers to begin porting BrandNewLlama. ```bash cd transformers ``` There are two possible debugging environments for running the original model, a notebook ([Google Colab](https://colab.research.google.com/notebooks/intro.ipynb) or [Jupyter](https://jupyter.org/)) or a local Python script. > [!WARNING] > We don't recommend setting up a GPU environment to run the original model because it can be expensive. Instead, work in a CPU environment first to verify the model works in Transformers. Once it does, then you can verify it on a GPU. Notebooks are great for executing code cell-by-cell which can help split logical components from one another. It can also accelerate debugging cycles because intermediate results can be stored. You can also share notebooks when working with other contributors. The downside is that if you aren't used to them, it may take some time to get used to. > [!TIP] > If the model architecture is identical to an existing model, skip ahead to add a [conversion script](#conversion-script), because you can reuse the architecture of the existing model. Run the command below to start and complete the questionnaire with some basic information about the new model. This command jumpstarts the process by automatically generating some model code that you'll need to adapt. ```bash transformers add-new-model-like ``` ## Create a pull request Before you start adapting the code, create a pull request to track your progress and get feedback from the Transformers team. Title your pull request **[WIP] Add BrandNewLlama** so it's clear that this is a work in progress. Create a branch with a descriptive name from your main branch. ```bash git checkout -b add_brand_new_bert ``` Commit the code, and then fetch and rebase on the main branch. ```bash git add . git commit git fetch upstream git rebase upstream/main ``` Push any changes to your branch and click on **Compare & pull request** to open a pull request on GitHub. Open the pull request as a *draft* to indicate it's a work in progress. ```bash git push -u origin a-descriptive-name-for-my-changes ``` Include relevant Hugging Face team members by adding their GitHub handles in the pull request for questions, feedback, comments, and reviews. Direct team members to specific parts of the code you want by clicking on the **Files changed** tab, and then clicking on **+** to the left of the line number to add a comment. When a question or problem is solved, click on **Resolve** to indicate the issue is resolved. This keeps the conversation organized and clean. Remember to periodically commit and push your work, and update your work with the current main branch. ```bash git fetch upstream git merge upstream/main ``` ## Original checkpoint Take some time to work on the original model implementation first to understand how it works. This can be difficult if the original model repository is lacking documentation or if the codebase is complex. But you should use this as your motivation to implement the model in Transformers. Your contribution makes it more accessible and user-friendly to everyone! Orient yourself with the original repository by doing the following. - Locate the pretrained weights. - Figure out how to the load pretrained weights into the model. - Figure out how to run the tokenizer independently of the model. - Trace one forward pass to understand which classes and functions are required. These are probably the only classes and functions you'll have to implement. - Locate all the important components (model class, model subclasses, self-attention layer, etc.) of the model. - Figure out how to debug the model in the original repository. Add print statements, use interactive debuggers like [ipdb](https://github.com/gotcha/ipdb), or a efficient integrated development environment (IDE) like [PyCharm](https://www.jetbrains.com/pycharm/). The last point is especially important because you'll need a thorough understanding of what's happening inside the original model before you can reimplement it in Transformers. Feel free to open issues and pull requests in the original repository if you encounter any issues. A good first step is to load a *small* pretrained checkpoint and try to reproduce a single forward pass with an example integer vector of inputs. For example, in pseudocode, this could look like the following. ```py model = BrandNewLlamaModel.load_pretrained_checkpoint("/path/to/checkpoint/") input_ids = [0, 4, 5, 2, 3, 7, 9] # vector of input ids original_output = model.generate(input_ids) ``` ### Debugging If you run into issues, you'll need to choose one of the following debugging strategies depending on the original models codebase. <hfoptions id="debug-strategy"> <hfoption id="sub-components"> This strategy relies on breaking the original model into smaller sub-components, such as when the code can be easily run in eager mode. While more difficult, there are some advantages to this approach. 1. It is easier later to compare the original model to your implementation. You can automatically verify that each individual component matches its corresponding component in the Transformers' implementation. This is better than relying on a visual comparison based on print statements. 2. It is easier to port individual components instead of the entire model. 3. It is easier for understanding how a model works by breaking it up into smaller parts. 4. It is easier to prevent regressions at a later stage when you change your code thanks to component-by-component tests. > [!TIP] > Refer to the ELECTRA [integration checks](https://gist.github.com/LysandreJik/db4c948f6b4483960de5cbac598ad4ed) for a good example of how to decompose a model into smaller components. </hfoption> <hfoption id="model and tokenizer"> This strategy is viable when the original codebase is too complex, only allows intermediate components to be run in compiled mode, or if it's too time-consuming (maybe even impossible) to separate the model into smaller sub-components. For example, the MeshTensorFlow implementation of [T5](https://github.com/tensorflow/mesh/tree/master/mesh_tensorflow) is too complex and doesn't offer a simple way to decompose the model into its sub-components. In this situation, you'll have to rely on verifying print statements. </hfoption> </hfoptions> Whichever strategy you choose, it is recommended to debug the initial layers first and the final layers last. Retrieve the output, either with print statements or sub-component functions, of the following layers in this order. 1. input ids passed to the model 2. word embeddings 3. input of the first Transformer layer 4. output of the first Transformer layer 5. output of the following n-1 Transformer layers 6. output of the whole model The input ids should just be an array of integers like `input_ids = [0, 4, 4, 3, 2, 4, 1, 7, 19]`. Layer outputs often consist of multi-dimensional float arrays. ```py [[ [-0.1465, -0.6501, 0.1993, ..., 0.1451, 0.3430, 0.6024], [-0.4417, -0.5920, 0.3450, ..., -0.3062, 0.6182, 0.7132], [-0.5009, -0.7122, 0.4548, ..., -0.3662, 0.6091, 0.7648], ..., [-0.5613, -0.6332, 0.4324, ..., -0.3792, 0.7372, 0.9288], [-0.5416, -0.6345, 0.4180, ..., -0.3564, 0.6992, 0.9191], [-0.5334, -0.6403, 0.4271, ..., -0.3339, 0.6533, 0.8694]]], ``` Every Transformers model output should have a precision or error tolerance of *1e-3*. This accounts for any output differences that arise from using a different library framework. Compare the intermediate outputs of the original model with the Transformers implementation to ensure they're nearly identical. Having an *efficient* debugging environment is crucial for this step. Here are some tips for an efficient debugging environment. - To debug intermediate results, it depends on the machine learning framework the original model repository is using. For PyTorch, you should write a script to decompose the original model into smaller sub-components to retrieve the intermediate values. For TensorFlow, you may need to use [tf.print](https://www.tensorflow.org/api_docs/python/tf/print). For Flax, make sure the model is *not jitted* during the forward pass (refer to this GitHub [Issue](https://github.com/google/jax/issues/196) for more details). - It is faster to debug with a smaller pretrained checkpoint versus a larger checkpoint where the forward pass takes more than 10 seconds. If only large checkpoints are available, create a dummy model with randomly initialized weights and save those weights to compare against the Transformers implementation. - Find the easiest way to call the model's forward pass. Ideally, this function (may be called `predict`, `evaluate`, `forward`, or `__call__`) should only call the forward pass *once*. It is more difficult to debug a function that calls the forward pass multiple times. - Separate tokenization from the forward pass. Locate where a string input is changed to input ids in the forward pass and start here. You may need to create a small script or modify the original code to directly input the input ids instead of an input string. - Ensure the model is *not* in training mode. This can produce random outputs due to multiple dropout layers in a model. The forward pass in your debugging environment should be *deterministic* so that the dropout layers aren't used. Once you're able to run the original checkpoint, you're ready to start adapting the model code for Transformers. ## Adapt the model code The `transformers add-new-model-like` command should have generated a model and configuration file. - `src/transformers/models/brand_new_llama/modeling_brand_new_llama.py` - `src/transformers/models/brand_new_llama/configuration_brand_new_llama.py` The automatically generated code in the `modeling.py` file has the same architecture as Llama if you answered it's a decoder-only model or it will have the same architecture as BART if you answered it's an encoder-decoder model. The generated code is just a starting point. Based on your research on the new model, you'll need to implement those specific changes by adapting the generated code. This may involve changes to the self-attention layer, the order of the normalization layer, and so on. ### Model initialization At this point, your code doesn't have to be clean or even fully correct, It is more efficient to quickly create a first draft and then iteratively improve on it. The most important thing is that your model can be instantiated from Transformers. The command below creates a model from the configuration with random weights, verifying that the `__init__` method works. ```py from transformers import BrandNewLlama, BrandNewLlamaConfig model = BrandNewLlama(BrandNewLlamaConfig()) ``` Random initialization occurs in the `_init_weights` method of `BrandNewLlamaPreTrainedModel`. All leaf modules are initialized depending on the configuration's variables. ```py def _init_weights(self, module): """Initialize the weights""" if isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() elif isinstance(module, nn.LayerNorm): module.bias.data.zero_() module.weight.data.fill_(1.0) ``` The initialization scheme can look different if you need to adapt it to your model. For example, [`Wav2Vec2ForPreTraining`] initializes [nn.Linear](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html) in its last two linear layers. The `_is_hf_initialized` flag makes sure the submodule is only initialized once. Setting `module.project_q` and `module.project_hid` to `True` ensures the custom initialization is not overridden later. The `_init_weights` function won't be applied to these modules. ```py def _init_weights(self, module): """Initialize the weights""" if isinstance(module, Wav2Vec2ForPreTraining): module.project_hid.reset_parameters() module.project_q.reset_parameters() module.project_hid._is_hf_initialized = True module.project_q._is_hf_initialized = True elif isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() ``` ### Convert checkpoints to Transformers The original checkpoint must be converted to a Transformers compatible checkpoint. > [!TIP] > Try looking for an existing conversion script to copy, adapt, and reuse for your model! > > - If you're porting a model from TensorFlow to PyTorch, a good starting point may be the BERT [conversion script](https://github.com/huggingface/transformers/blob/7acfa95afb8194f8f9c1f4d2c6028224dbed35a2/src/transformers/models/bert/modeling_bert.py#L91). > - If you're porting a model from PyTorch to PyTorch, a good starting point may be the BART [conversion script](https://github.com/huggingface/transformers/blob/main/src/transformers/models/bart/convert_bart_original_pytorch_checkpoint_to_pytorch.py). Make sure **all** required weights are initialized and print out all the checkpoint weights that weren't used for initialization to make sure the model has been converted correctly. You may encounter wrong shape statements or name assignments during the conversion. This is most likely because of incorrect parameters in `BrandNewLlamaConfig`, the wrong architecture, a bug in the `init` method of your implementation, or you need to transpose one of the checkpoint weights. Keep iterating on the [Adapt the model code](#adapt-the-model-code) section until all the checkpoint weights are correctly loaded. Once you can load a checkpoint in your model, save it to a folder. This should contain a `model.safetensors` file and a `config.json` file. ```py model.save_pretrained("/path/to/converted/checkpoint/folder") ``` To help with conversion, the next section briefly describes how PyTorch models stores and defines layer weights and names. #### PyTorch layer weights and names It is helpful to create a basic PyTorch model to understand how layer names are defined and weights are initialized. ```py from torch import nn class SimpleModel(nn.Module): def __init__(self): super().__init__() self.dense = nn.Linear(10, 10) self.intermediate = nn.Linear(10, 10) self.layer_norm = nn.LayerNorm(10) ``` PyTorch layer names are defined by the class attribute name of the layer (`dense`, `intermediate`, `layer_norm`). Create a instance of `SimpleModel` to fill all the layers with random weights. ```py model = SimpleModel() print(model) SimpleModel( (dense): Linear(in_features=10, out_features=10, bias=True) (intermediate): Linear(in_features=10, out_features=10, bias=True) (layer_norm): LayerNorm((10,), eps=1e-05, elementwise_affine=True) ) ``` The weight values of a specific layer are randomly initialized. ```py print(model.dense.weight.data) tensor([[-0.0818, 0.2207, -0.0749, -0.0030, 0.0045, -0.1569, -0.1598, 0.0212, -0.2077, 0.2157], [ 0.1044, 0.0201, 0.0990, 0.2482, 0.3116, 0.2509, 0.2866, -0.2190, 0.2166, -0.0212], [-0.2000, 0.1107, -0.1999, -0.3119, 0.1559, 0.0993, 0.1776, -0.1950, -0.1023, -0.0447], [-0.0888, -0.1092, 0.2281, 0.0336, 0.1817, -0.0115, 0.2096, 0.1415, -0.1876, -0.2467], [ 0.2208, -0.2352, -0.1426, -0.2636, -0.2889, -0.2061, -0.2849, -0.0465, 0.2577, 0.0402], [ 0.1502, 0.2465, 0.2566, 0.0693, 0.2352, -0.0530, 0.1859, -0.0604, 0.2132, 0.1680], [ 0.1733, -0.2407, -0.1721, 0.1484, 0.0358, -0.0633, -0.0721, -0.0090, 0.2707, -0.2509], [-0.1173, 0.1561, 0.2945, 0.0595, -0.1996, 0.2988, -0.0802, 0.0407, 0.1829, -0.1568], [-0.1164, -0.2228, -0.0403, 0.0428, 0.1339, 0.0047, 0.1967, 0.2923, 0.0333, -0.0536], [-0.1492, -0.1616, 0.1057, 0.1950, -0.2807, -0.2710, -0.1586, 0.0739, 0.2220, 0.2358]]). ``` In the conversion script, the random weights should be replaced with the exact weights from the corresponding layer in the original checkpoint. ```py # retrieve matching layer weights with recursive algorithm layer_name = "dense" pretrained_weight = array_of_dense_layer model_pointer = getattr(model, "dense") model_pointer.weight.data = torch.from_numpy(pretrained_weight) ``` Verify the randomly initialized weights and their corresponding pretrained checkpoint weights have the identical **shape** and **name**. Add assert statements for the shape and print out the checkpoint weight names. ```py assert ( model_pointer.weight.shape == pretrained_weight.shape ), f"Pointer shape of random weight {model_pointer.shape} and array shape of checkpoint weight {pretrained_weight.shape} mismatched" logger.info(f"Initialize PyTorch weight {layer_name} from {pretrained_weight.name}") ``` When the shape or name don't match, you may have assigned the incorrect checkpoint weight to a randomly initialized layer. An incorrect shape may be because the `BrandNewLlama` parameters don't exactly match the original models parameters. But it could also be that the PyTorch layer implementation requires the weights to be transposed first. ### Implement the forward pass The forward pass should be implemented next if the model loads correctly. It takes some inputs and returns the model output. ```py model = BrandNewLlamaModel.from_pretrained("/path/to/converted/checkpoint/folder") input_ids = [0, 4, 4, 3, 2, 4, 1, 7, 19] output = model.generate(input_ids).last_hidden_states ``` Don't be discouraged if your forward pass isn't identical with the output from the original model or if it returns an error. Check that the forward pass doesn't throw any errors. This is often because the dimensions are wrong or because the wrong data type is used ([torch.long](https://pytorch.org/docs/stable/generated/torch.Tensor.long.html) instead of [torch.float32](https://pytorch.org/docs/stable/tensors.html)). Your output should have a precision of *1e-3*. Ensure the output shapes and output values are identical. Common reasons for why the outputs aren't identical include: - Some layers were not added (activation layer or a residual connection). - The word embedding matrix is not tied. - The wrong positional embeddings are used because the original implementation includes an offset. - Dropout is applied during the forward pass. Fix this error by making sure `model.training` is `False` and passing `self.training` to [torch.nn.functional.dropout](https://pytorch.org/docs/stable/nn.functional.html?highlight=dropout#torch.nn.functional.dropout). Compare the forward pass of the original model and your implementation to check if there are any differences. Ideally, debug and print out the intermediate outputs of both implementations of the forward pass to pinpoint where the original implementation differs from yours. 1. Make sure the hardcoded `input_ids` in both implementations are identical. 2. Verify the outputs of the first transformation of `input_ids` (usually the word embeddings) are identical, and work your way through to the last layer. Any difference between the two implementations should point to the bug in your implementation. One of the best strategies is to add many print statements to the same positions in both implementations, and then successively remove them when they output identical values for the intermediate outputs. When both implementations produce the same output, verify the outputs are within a precision of *1e-3*. ```py torch.allclose(original_output, output, atol=1e-3) ``` This is typically the most difficult part of the process. Congratulations if you've made it this far! And if you're stuck or struggling with this step, don't hesitate to ask for help on your pull request. ### Add model tests While the model works, you still need to add tests to ensure it is compatible with Transformers. Tests are important because they help users understand your work by looking at specific tests, and because they prevent your model from breaking in the future if any changes are made. [Cookiecutter](https://cookiecutter.readthedocs.io/en/stable/) should have added a test file for your model. Run the test file below to make sure all common tests pass. ```bash pytest tests/models/brand_new_llama/test_modeling_brand_new_llama.py ``` The integration tests should be added first because they serve the same purpose as the debugging scripts you used earlier to implement the new model in Transformers. A template of those model tests, `BrandNewLlamaModelIntegrationTests`, was added by Cookiecutter and should be filled out. To ensure it passes, run the following command. <hfoptions id="integration-test"> <hfoption id="macOS"> ```bash RUN_SLOW=1 pytest -sv tests/models/brand_new_llama/test_modeling_brand_new_llama.py::BrandNewLlamaModelIntegrationTests ``` </hfoption> <hfoption id="Windows"> ```bash SET RUN_SLOW=1 pytest -sv tests/models/brand_new_llama/test_modeling_brand_new_llama.py::BrandNewLlamaModelIntegrationTests ``` </hfoption> </hfoptions> All features unique to BrandNewLlama should be tested in a separate test under `BrandNewLlamaModelTester/BrandNewLlamaModelTest`. This test is often overlooked, but it is extremely important because: - it helps transfer knowledge you acquired during the process to the community by showing how the models novel features work - future contributors can quickly test changes to the model by running these special tests ## Implement tokenizer > [!TIP] > We recommend adding a fast tokenizer ([`PreTrainedTokenizerFast`]) to give users the best performance. Feel free to tag [@ArthurZucker](https://github.com/ArthurZucker) or [@itazap](https://github.com/itazap) in your PR for help on how to add [`PreTrainedTokenizerFast`]. With the model out of the way, time to focus on the tokenizer. The tokenizer should be identical or very similar to an existing tokenizer in Transformers. Find and load the original tokenizer file into your implementation. Create a script in the original repository that inputs a string and returns the `input_ids`. The pseudocode should look similar to the code below. ```py input_str = "This is a long example input string containing special characters .$?-, numbers 2872 234 12 and words." model = BrandNewLlamaModel.load_pretrained_checkpoint("/path/to/checkpoint/") input_ids = model.tokenize(input_str) ``` You may need to search the original repository to find the correct tokenizer function or modify the existing tokenizer in your clone of the original repository to only return the `input_ids`. The script for your tokenizer should look similar to the following. ```py from transformers import BrandNewLlamaTokenizer input_str = "This is a long example input string containing special characters .$?-, numbers 2872 234 12 and words." tokenizer = BrandNewLlamaTokenizer.from_pretrained("/path/to/tokenizer/folder/") input_ids = tokenizer(input_str).input_ids ``` When both implementations have the same `input_ids`, add a tokenizer test file. This file is analogous to the modeling test files. The tokenizer test files should contain a couple of hardcoded integration tests. ## Implement image processor > [!TIP] > Fast image processors use the [torchvision](https://pytorch.org/vision/stable/index.html) library and can perform image processing on the GPU, significantly improving processing speed. > We recommend adding a fast image processor ([`BaseImageProcessorFast`]) in addition to the "slow" image processor ([`BaseImageProcessor`]) to provide users with the best performance. Feel free to tag [@yonigozlan](https://github.com/yonigozlan) for help adding a [`BaseImageProcessorFast`]. While this example doesn't include an image processor, you may need to implement one if your model requires image inputs. The image processor is responsible for converting images into a format suitable for your model. Before implementing a new one, check whether an existing image processor in the Transformers library can be reused, as many models share similar image processing techniques. Note that you can also use [modular](./modular_transformers) for image processors to reuse existing components. If you do need to implement a new image processor, refer to an existing image processor to understand the expected structure. Slow image processors ([`BaseImageProcessor`]) and fast image processors ([`BaseImageProcessorFast`]) are designed differently, so make sure you follow the correct structure based on the processor type you're implementing. Run the following command (only if you haven't already created the fast image processor with the `transformers add-new-model-like` command) to generate the necessary imports and to create a prefilled template for the fast image processor. Modify the template to fit your model. ```bash transformers add-fast-image-processor --model-name your_model_name ``` This command will generate the necessary imports and provide a pre-filled template for the fast image processor. You can then modify it to fit your model's needs. Add tests for the image processor in `tests/models/your_model_name/test_image_processing_your_model_name.py`. These tests should be similar to those for other image processors and should verify that the image processor correctly handles image inputs. If your image processor includes unique features or processing methods, ensure you add specific tests for those as well. ## Implement processor If your model accepts multiple modalities, like text and images, you need to add a processor. The processor centralizes the preprocessing of different modalities before passing them to the model. The processor should call the appropriate modality-specific processors within its `__call__` function to handle each type of input correctly. Be sure to check existing processors in the library to understand their expected structure. Transformers uses the following convention in the `__call__` function signature. ```python def __call__( self, images: ImageInput = None, text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None, audio=None, videos=None, **kwargs: Unpack[YourModelProcessorKwargs], ) -> BatchFeature: ... ``` `YourModelProcessorKwargs` is a `TypedDict` that includes all the typical processing arguments and any extra arguments a specific processor may require. Add tests for the processor in `tests/models/your_model_name/test_processor_your_model_name.py`. These tests should be similar to those for other processors and should verify that the processor correctly handles the different modalities. ## Integration tests Now that you have a model and tokenizer, add end-to-end integration tests for the model and tokenizer to `tests/models/brand_new_llama/test_modeling_brand_new_llama.py`. The test should provide a meaningful text-to-text example to show the model works as expected. For example, you can include a source-to-target translation pair, an article-to-summary pair, or a question-to-answer pair. If the checkpoint hasn't been fine-tuned on a downstream task, then the model tests are sufficient. Finally, try to make sure your tests can run on a GPU by adding `.to(self.device)` statements to the models internal tensors. If you don't have access to a GPU, we can take care of that for you. ## Add documentation Your model is only useful if users know how to use it. This is why it's important to add documentation and docstrings. Cookiecutter added a template file, `docs/source/model_doc/brand_new_llama.md`, that you can fill out with information about your model. This is generally a user's first interaction with a model, so the documentation should be clear and concise. It is often very useful to add examples of how the model should be used. Make sure docstrings are added to `src/transformers/models/brand_new_llama/modeling_brand_new_llama.py` and includes all necessary inputs and outputs. Review our [guide](https://github.com/huggingface/transformers/tree/main/docs#writing-documentation---specification) for writing documentation and docstrings. ## Refactor Time to tidy things up and make sure the code style is consistent with the rest of the library. Run the following command to automatically fix incorrect styles. ```bash make style ``` To verify the code style passes quality checks, run the command below. ```bash make quality ``` There may be other failing tests or checks (missing docstring or incorrect naming) on your pull request due to Transformers strict design tests. We can help you with these issues if you're stuck. After ensuring the code runs correctly, you may want to refactor it to make it more readable or cleaner. ## Upload to the Hub Convert and upload all checkpoints to the [Hub](https://hf.co/models). Add a model card to provide more transparency and context about the model. The model card should highlight specific characteristics of a checkpoint, how the model was trained, and code examples of how to use it. > [!TIP] > In many cases, adding an interactive notebook users can run is a great way to showcase how to use the model for inference or fine-tune it on a downstream task. While not required, including a notebook can drive greater adoption of your model. You should also consult with the Transformers team to decide on an appropriate name for the model, and getting the required access rights to upload the model. Use the [`~PreTrainedModel.push_to_hub`] method to upload the model. ```py brand_new_bert.push_to_hub("brand_new_llama") ``` Refer to the [Sharing](./model_sharing) guide for more information about uploading models to the Hub. ## Merge your model You're finally ready to merge your pull request and officially add the model to Transformers! Make sure all the tests are passing and all comments and feedback have been addressed. Congratulations on adding a new model to Transformers! 🥳 This is a very significant contribution. Your work makes Transformers more accessible to developers and researchers around the world. You should be proud of your contribution and share your accomplishment with the community! ## Model addition timeline There are four timelines for model additions depending on the model contributor and community demand for an architecture. - **day-0 integration**: If you plan on having a Transformers-first release, this is a great option because we can ensure the documentation is clear and optimize your model as much as possible (quantization, FlashAttention, KV-cache, etc.). We can also help you add the model, provide early reviews and make sure it works as expected. Reach out to transformers@huggingface.co a few days (preferably weeks) in advance, especially if an architecture is particularly novel, to ensure model integration. We'll work together on a private fork of Transformers until your checkpoint and release is ready. - **same week integration**: Models with significant requests/demand are usually added the same week if the model author doesn't reach out. Use the [issue tracker](https://github.com/huggingface/transformers/issues/new?assignees=&labels=New+model&projects=&template=new-model-addition.yml) to request a specific model to add. The more activity on the issue, the faster and more likely we'll integrate it. - **post-release integration**: Models without popular requests/demand or if we don't have the bandwidth to integrate it are added post-release. This is a good opportunity if you're interested in contributing a model to Transformers. Take a look at open issues tagged with ["New model"](https://github.com/huggingface/transformers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+model%22). Feel free to give the most requested models a try first to multiply the impact of your contribution. We'll be there to help you each step of the way! - **Hub-first release**: Transformers [remote-code](./models#custom-models) feature allows Transformers-based projects to be shared directly on the Hub. This is a good option if you don't have the bandwidth to add a model directly to Transformers. If a model ends up being very popular, then it's very likely that we'll integrate it in Transformers ourselves to enable better support (documentation, maintenance, optimization, etc.) for it. A Hub-first release is the most frictionless way to add a model.
transformers/docs/source/en/add_new_model.md/0
{ "file_path": "transformers/docs/source/en/add_new_model.md", "repo_id": "transformers", "token_count": 10966 }
381
<!--Copyright 2024 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. --> # Multi-GPU debugging Distributed training can be tricky because you have to ensure you're using the correct CUDA version across your system. You may encounter inter-communication issues between GPUs, and there may be underflow or overflow problems in your model. This guide covers how to debug these issues, especially as it relates to DeepSpeed and PyTorch. ## DeepSpeed CUDA DeepSpeed compiles CUDA C++ which can be a potential source of errors when building PyTorch extensions that require CUDA. These errors depend on how CUDA is installed on your system. This section focuses on PyTorch built with *CUDA 10.2* ```bash pip install deepspeed ``` > [!TIP] > For any other installation issues, please [open an issue](https://github.com/microsoft/DeepSpeed/issues) with the DeepSpeed team. ### Non-identical toolkits PyTorch comes with its own CUDA toolkit, but to use DeepSpeed with PyTorch, you need to have an identical version of CUDA installed system-wide. For example, if you installed PyTorch with `cudatoolkit==10.2` in your Python environment, then you'll also need to have CUDA 10.2 installed everywhere. The exact location can vary from system to system, but `usr/local/cuda-10.2` is the most common location on many Unix systems. When CUDA is correctly set up and added to your `PATH` environment variable, you can find the installation location with the following command. ```bash which nvcc ``` ### Multiple toolkits You may also have more than one CUDA toolkit installed on your system. ```bash /usr/local/cuda-10.2 /usr/local/cuda-11.0 ``` Typically, package installers set the paths to whatever the last version was installed. If the package build fails because it can't find the right CUDA version (despite it being installed already), then you need to configure the `PATH` and `LD_LIBRARY_PATH` environment variables to point to the correct path. Take a look at the contents of the following environment variables first. ```bash echo $PATH echo $LD_LIBRARY_PATH ``` `PATH` lists the locations of the executables and `LD_LIBRARY_PATH` lists where to look for shared libraries. Earlier entries are prioritized over later ones, and `:` is used to separate multiple entries. To find a specific CUDA toolkit, insert the correct path to list first. This command prepends rather than overwrites the existing values. ```bash # adjust the version and full path if needed export PATH=/usr/local/cuda-10.2/bin:$PATH export LD_LIBRARY_PATH=/usr/local/cuda-10.2/lib64:$LD_LIBRARY_PATH ``` In addition, you should also check that the assigned directories actually exist. The `lib64` sub-directory contains various CUDA `.so` objects (like `libcudart.so`), and while it is unlikely your system names them differently, you should check the actual names and change them accordingly. ### Older versions Sometimes, older CUDA versions may refuse to build with newer compilers. For example, if you have `gcc-9` but CUDA wants `gcc-7`. Usually, installing the latest CUDA toolkit enables support for the newer compiler. You could also install an older version of the compiler in addition to the one you're currently using (or it may already be installed but it's not used by default and the build system can't see it). To resolve this, create a symlink to give the build system visibility to the older compiler. ```bash # adjust the path to your system sudo ln -s /usr/bin/gcc-7 /usr/local/cuda-10.2/bin/gcc sudo ln -s /usr/bin/g++-7 /usr/local/cuda-10.2/bin/g++ ``` ### Prebuild If you're still having issues with installing DeepSpeed or if you're building DeepSpeed at run time, try to prebuild the DeepSpeed modules before installing them. Run the commands below to make a local build for DeepSpeed. ```bash git clone https://github.com/deepspeedai/DeepSpeed/ cd DeepSpeed rm -rf build TORCH_CUDA_ARCH_LIST="8.6" DS_BUILD_CPU_ADAM=1 DS_BUILD_UTILS=1 pip install . \ --global-option="build_ext" --global-option="-j8" --no-cache -v \ --disable-pip-version-check 2>&1 | tee build.log ``` > [!TIP] > Add the `DS_BUILD_AIO=1` parameter to the build command to use NVMe offload. Make sure you install the libaio-dev package across your system. Next, specify your GPUs architecture by editing the `TORCH_CUDA_ARCH_LIST` variable (find a complete list of NVIDIA GPUs and their corresponding architectures on this [page](https://developer.nvidia.com/cuda-gpus)). To check the PyTorch version that corresponds to your architecture, run the following command. ```bash python -c "import torch; print(torch.cuda.get_arch_list())" ``` Find the architecture for a GPU with the following command. <hfoptions id="arch"> <hfoption id="same GPUs"> ```bash CUDA_VISIBLE_DEVICES=0 python -c "import torch; print(torch.cuda.get_device_capability())" ``` </hfoption> <hfoption id="specific GPU"> Run the following command to find the architecture for GPU `0`. The results will show a value for `major` and `minor`, which is your GPU architecture. The GPU architecture below is `8.6`. ```bash CUDA_VISIBLE_DEVICES=0 python -c "import torch; \ print(torch.cuda.get_device_properties(torch.device('cuda'))) "_CudaDeviceProperties(name='GeForce RTX 3090', major=8, minor=6, total_memory=24268MB, multi_processor_count=82)" ``` </hfoption> </hfoptions> If you get `8, 6`, then you can set `TORCH_CUDA_ARCH_LIST="8.6"`. For multiple GPUs with different architectures, list them like `TORCH_CUDA_ARCH_LIST="6.1;8.6"`. It is also possible to not specify `TORCH_CUDA_ARCH_LIST` and the build program automatically queries the GPU architecture of the build. However, it may or may not match the actual GPU on the target machine which is why it is better to explicitly specify the correct architecture. For training on multiple machines with the same setup, you'll need to make a binary wheel as shown below. ```bash git clone https://github.com/deepspeedai/DeepSpeed/ cd DeepSpeed rm -rf build TORCH_CUDA_ARCH_LIST="8.6" DS_BUILD_CPU_ADAM=1 DS_BUILD_UTILS=1 \ python setup.py build_ext -j8 bdist_wheel ``` This command generates a binary wheel that'll look something like `dist/deepspeed-0.3.13+8cd046f-cp38-cp38-linux_x86_64.whl`. Install this wheel locally or on another machine. ```bash pip install deepspeed-0.3.13+8cd046f-cp38-cp38-linux_x86_64.whl ``` ## Communication Distributed training involves communication between processes and or nodes and this can be a potential source of errors. Download the script below to diagnose network issues, and then run it to test GPU communication. The example command below tests how two GPUs communicate. Adjust the `--nproc_per_node` and `--nnodes` parameters to adapt it to your system. ```bash wget https://raw.githubusercontent.com/huggingface/transformers/main/scripts/distributed/torch-distributed-gpu-test.py python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py ``` The script prints an `OK` status if both GPUs are able to communicate and allocate memory. Take a closer look at the diagnostic script for more details and a recipe for running it in a SLURM environment. Add the `NCCL_DEBUG=INFO` environment variable to report more NCCL-related debugging information. ```bash NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py ``` ## Underflow and overflow detection Underflow and overflow can occur when activations or weights are `inf`, `nan`, and when `loss=NaN`. This may indicate an underflow or overflow issue. To detect these issues, activate the `DebugUnderflowOverflow` module in [`TrainingArguments.debug`] or import and add the module to your own training loop or another trainer class. <hfoptions id="overflow"> <hfoption id="Trainer"> ```py from transformers import TrainingArguments args = TrainingArguments( debug="underflow_overflow", ... ) ``` </hfoption> <hfoption id="PyTorch training loop"> ```py from transformers.debug_utils import DebugUnderflowOverflow debug_overflow = DebugUnderflowOverflow(model) ``` </hfoption> </hfoptions> The [`~debug_utils.DebugUnderflowOverflow`] module inserts hooks into the model to test the input and output variables and the corresponding model weights after each forward call. If `inf` or `nan` is detected in at least one element of the activations or weights, the module prints a report like the one shown below. The example below is for fp16 mixed precision training with [google/mt5-small](https://huggingface.co/google/mt5-small). ```shell Detected inf/nan during batch_number=0 Last 21 forward frames: abs min abs max metadata encoder.block.1.layer.1.DenseReluDense.dropout Dropout 0.00e+00 2.57e+02 input[0] 0.00e+00 2.85e+02 output [...] encoder.block.2.layer.0 T5LayerSelfAttention 6.78e-04 3.15e+03 input[0] 2.65e-04 3.42e+03 output[0] None output[1] 2.25e-01 1.00e+04 output[2] encoder.block.2.layer.1.layer_norm T5LayerNorm 8.69e-02 4.18e-01 weight 2.65e-04 3.42e+03 input[0] 1.79e-06 4.65e+00 output encoder.block.2.layer.1.DenseReluDense.wi_0 Linear 2.17e-07 4.50e+00 weight 1.79e-06 4.65e+00 input[0] 2.68e-06 3.70e+01 output encoder.block.2.layer.1.DenseReluDense.wi_1 Linear 8.08e-07 2.66e+01 weight 1.79e-06 4.65e+00 input[0] 1.27e-04 2.37e+02 output encoder.block.2.layer.1.DenseReluDense.dropout Dropout 0.00e+00 8.76e+03 input[0] 0.00e+00 9.74e+03 output encoder.block.2.layer.1.DenseReluDense.wo Linear 1.01e-06 6.44e+00 weight 0.00e+00 9.74e+03 input[0] 3.18e-04 6.27e+04 output encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense 1.79e-06 4.65e+00 input[0] 3.18e-04 6.27e+04 output encoder.block.2.layer.1.dropout Dropout 3.18e-04 6.27e+04 input[0] 0.00e+00 inf output ``` At the start of the report, you can see which batch number the error occurred. In this case, it occurred on the first batch. Each frame describes the module it is reporting on. For example, the frame below inspected `encoder.block.2.layer.1.layer_norm`. This indicates the layer norm in the first layer of the second block of the encoder. The forward calls are to `T5LayerNorm`. ```shell encoder.block.2.layer.1.layer_norm T5LayerNorm 8.69e-02 4.18e-01 weight 2.65e-04 3.42e+03 input[0] 1.79e-06 4.65e+00 output ``` The last frame reports on the `Dropout.forward` function. It called the `dropout` attribute from inside the `DenseReluDense` class. You can observe that the overflow (`inf`) occurred in the first layer of the encoders second block in the first batch. The absolute largest input element was 6.27e+04. ```shell encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense 1.79e-06 4.65e+00 input[0] 3.18e-04 6.27e+04 output encoder.block.2.layer.1.dropout Dropout 3.18e-04 6.27e+04 input[0] 0.00e+00 inf output ``` The `T5DenseGatedGeluDense.forward` function output activations had an absolute maximum value of 6.27e+04 which is close to fp16s maximum limit of 6.4e+04. In the next step, `Dropout` renormalizes the weights, after zeroing some elements, which pushes the absolute maximum value to greater than 6.4e+04 resulting in an overflow. Now that you know where the error is happening, you can investigate the modeling code in [modeling_t5.py](https://github.com/huggingface/transformers/blob/main/src/transformers/models/t5/modeling_t5.py). ```py class T5DenseGatedGeluDense(nn.Module): def __init__(self, config): super().__init__() self.wi_0 = nn.Linear(config.d_model, config.d_ff, bias=False) self.wi_1 = nn.Linear(config.d_model, config.d_ff, bias=False) self.wo = nn.Linear(config.d_ff, config.d_model, bias=False) self.dropout = nn.Dropout(config.dropout_rate) self.gelu_act = ACT2FN["gelu_new"] def forward(self, hidden_states): hidden_gelu = self.gelu_act(self.wi_0(hidden_states)) hidden_linear = self.wi_1(hidden_states) hidden_states = hidden_gelu * hidden_linear hidden_states = self.dropout(hidden_states) hidden_states = self.wo(hidden_states) return hidden_states ``` One solution is to go back a few steps before the values started growing too large and switch to fp32 so the numbers don't overflow when multiplied or summed. Another potential solution is to temporarily disable mixed precision training (`amp`). ```py import torch def forward(self, hidden_states): if torch.is_autocast_enabled(): with torch.cuda.amp.autocast(enabled=False): return self._forward(hidden_states) else: return self._forward(hidden_states) ``` The report only returns inputs and outputs of full frames, so you may also want to analyze the intermediate values of any `forward` function as well. Add the `detect_overflow` function after the forward calls to track `inf` or `nan` values in the intermediate `forwarded_states`. ```py from debug_utils import detect_overflow class T5LayerFF(nn.Module): [...] def forward(self, hidden_states): forwarded_states = self.layer_norm(hidden_states) detect_overflow(forwarded_states, "after layer_norm") forwarded_states = self.DenseReluDense(forwarded_states) detect_overflow(forwarded_states, "after DenseReluDense") return hidden_states + self.dropout(forwarded_states) ``` Finally, you can configure the number of frames printed by [`~debug_utils.DebugUnderflowOverflow`]. ```py from transformers.debug_utils import DebugUnderflowOverflow debug_overflow = DebugUnderflowOverflow(model, max_frames_to_save=100) ``` ### Batch tracing [`~debug_utils.DebugUnderflowOverflow`] is able to trace the absolute minimum and maximum values in each batch with the underflow and overflow feature disabled. This is useful for identifying where errors are occurring in the model. The example below shows how to trace the minimum and maximum values in batches 1 and 3 (batches are zero-indexd). ```py debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3]) ``` ```shell *** Starting batch number=1 *** abs min abs max metadata shared Embedding 1.01e-06 7.92e+02 weight 0.00e+00 2.47e+04 input[0] 5.36e-05 7.92e+02 output [...] decoder.dropout Dropout 1.60e-07 2.27e+01 input[0] 0.00e+00 2.52e+01 output decoder T5Stack not a tensor output lm_head Linear 1.01e-06 7.92e+02 weight 0.00e+00 1.11e+00 input[0] 6.06e-02 8.39e+01 output T5ForConditionalGeneration not a tensor output *** Starting batch number=3 *** abs min abs max metadata shared Embedding 1.01e-06 7.92e+02 weight 0.00e+00 2.78e+04 input[0] 5.36e-05 7.92e+02 output [...] ``` [`~debug_utils.DebugUnderflowOverflow`] reports on a large number of frames which is easier for debugging. Once you know where a problem is occurring, say batch 150, then you can focus the trace for batches 149 and 150 and compare where the numbers are diverging. It is also possible to abort the trace after a certain batch number, for example, batch 3. ```py debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3], abort_after_batch_num=3) ```
transformers/docs/source/en/debugging.md/0
{ "file_path": "transformers/docs/source/en/debugging.md", "repo_id": "transformers", "token_count": 5418 }
382
<!--Copyright 2021 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. --> # General Utilities This page lists all of Transformers general utility functions that are found in the file `utils.py`. Most of those are only useful if you are studying the general code in the library. ## Enums and namedtuples [[autodoc]] utils.ExplicitEnum [[autodoc]] utils.PaddingStrategy [[autodoc]] utils.TensorType ## Special Decorators [[autodoc]] utils.add_start_docstrings [[autodoc]] utils.add_start_docstrings_to_model_forward [[autodoc]] utils.add_end_docstrings [[autodoc]] utils.add_code_sample_docstrings [[autodoc]] utils.replace_return_docstrings ## Special Properties [[autodoc]] utils.cached_property ## Other Utilities [[autodoc]] utils._LazyModule [[autodoc]] pytorch_utils.infer_device
transformers/docs/source/en/internal/file_utils.md/0
{ "file_path": "transformers/docs/source/en/internal/file_utils.md", "repo_id": "transformers", "token_count": 428 }
383
<!--Copyright 2020 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. --> # Callbacks Callbacks are objects that can customize the behavior of the training loop in the PyTorch [`Trainer`] (this feature is not yet implemented in TensorFlow) that can inspect the training loop state (for progress reporting, logging on TensorBoard or other ML platforms...) and take decisions (like early stopping). Callbacks are "read only" pieces of code, apart from the [`TrainerControl`] object they return, they cannot change anything in the training loop. For customizations that require changes in the training loop, you should subclass [`Trainer`] and override the methods you need (see [trainer](trainer) for examples). By default, `TrainingArguments.report_to` is set to `"all"`, so a [`Trainer`] will use the following callbacks. - [`DefaultFlowCallback`] which handles the default behavior for logging, saving and evaluation. - [`PrinterCallback`] or [`ProgressCallback`] to display progress and print the logs (the first one is used if you deactivate tqdm through the [`TrainingArguments`], otherwise it's the second one). - [`~integrations.TensorBoardCallback`] if tensorboard is accessible (either through PyTorch >= 1.4 or tensorboardX). - [`~integrations.TrackioCallback`] if [trackio](https://github.com/gradio-app/trackio) is installed. - [`~integrations.WandbCallback`] if [wandb](https://www.wandb.com/) is installed. - [`~integrations.CometCallback`] if [comet_ml](https://www.comet.com/site/) is installed. - [`~integrations.MLflowCallback`] if [mlflow](https://www.mlflow.org/) is installed. - [`~integrations.NeptuneCallback`] if [neptune](https://neptune.ai/) is installed. - [`~integrations.AzureMLCallback`] if [azureml-sdk](https://pypi.org/project/azureml-sdk/) is installed. - [`~integrations.CodeCarbonCallback`] if [codecarbon](https://pypi.org/project/codecarbon/) is installed. - [`~integrations.ClearMLCallback`] if [clearml](https://github.com/allegroai/clearml) is installed. - [`~integrations.DagsHubCallback`] if [dagshub](https://dagshub.com/) is installed. - [`~integrations.FlyteCallback`] if [flyte](https://flyte.org/) is installed. - [`~integrations.DVCLiveCallback`] if [dvclive](https://dvc.org/doc/dvclive) is installed. - [`~integrations.SwanLabCallback`] if [swanlab](http://swanlab.cn/) is installed. If a package is installed but you don't wish to use the accompanying integration, you can change `TrainingArguments.report_to` to a list of just those integrations you want to use (e.g. `["azure_ml", "wandb"]`). The main class that implements callbacks is [`TrainerCallback`]. It gets the [`TrainingArguments`] used to instantiate the [`Trainer`], can access that Trainer's internal state via [`TrainerState`], and can take some actions on the training loop via [`TrainerControl`]. ## Available Callbacks Here is the list of the available [`TrainerCallback`] in the library: [[autodoc]] integrations.CometCallback - setup [[autodoc]] DefaultFlowCallback [[autodoc]] PrinterCallback [[autodoc]] ProgressCallback [[autodoc]] EarlyStoppingCallback [[autodoc]] integrations.TensorBoardCallback [[autodoc]] integrations.TrackioCallback - setup [[autodoc]] integrations.WandbCallback - setup [[autodoc]] integrations.MLflowCallback - setup [[autodoc]] integrations.AzureMLCallback [[autodoc]] integrations.CodeCarbonCallback [[autodoc]] integrations.NeptuneCallback [[autodoc]] integrations.ClearMLCallback [[autodoc]] integrations.DagsHubCallback [[autodoc]] integrations.FlyteCallback [[autodoc]] integrations.DVCLiveCallback - setup [[autodoc]] integrations.SwanLabCallback - setup ## TrainerCallback [[autodoc]] TrainerCallback Here is an example of how to register a custom callback with the PyTorch [`Trainer`]: ```python class MyCallback(TrainerCallback): "A callback that prints a message at the beginning of training" def on_train_begin(self, args, state, control, **kwargs): print("Starting training") trainer = Trainer( model, args, train_dataset=train_dataset, eval_dataset=eval_dataset, callbacks=[MyCallback], # We can either pass the callback class this way or an instance of it (MyCallback()) ) ``` Another way to register a callback is to call `trainer.add_callback()` as follows: ```python trainer = Trainer(...) trainer.add_callback(MyCallback) # Alternatively, we can pass an instance of the callback class trainer.add_callback(MyCallback()) ``` ## TrainerState [[autodoc]] TrainerState ## TrainerControl [[autodoc]] TrainerControl
transformers/docs/source/en/main_classes/callback.md/0
{ "file_path": "transformers/docs/source/en/main_classes/callback.md", "repo_id": "transformers", "token_count": 1625 }
384
<!--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. ⚠️ 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. --> # Quantization Quantization techniques reduce memory and computational costs by representing weights and activations with lower-precision data types like 8-bit integers (int8). This enables loading larger models you normally wouldn't be able to fit into memory, and speeding up inference. Transformers supports the AWQ and GPTQ quantization algorithms and it supports 8-bit and 4-bit quantization with bitsandbytes. Quantization techniques that aren't supported in Transformers can be added with the [`HfQuantizer`] class. <Tip> Learn how to quantize models in the [Quantization](../quantization) guide. </Tip> ## QuantoConfig [[autodoc]] QuantoConfig ## AqlmConfig [[autodoc]] AqlmConfig ## VptqConfig [[autodoc]] VptqConfig ## AwqConfig [[autodoc]] AwqConfig ## EetqConfig [[autodoc]] EetqConfig ## GPTQConfig [[autodoc]] GPTQConfig ## BitsAndBytesConfig [[autodoc]] BitsAndBytesConfig ## HfQuantizer [[autodoc]] quantizers.base.HfQuantizer ## HiggsConfig [[autodoc]] HiggsConfig ## HqqConfig [[autodoc]] HqqConfig ## Mxfp4Config [[autodoc]] Mxfp4Config ## FbgemmFp8Config [[autodoc]] FbgemmFp8Config ## CompressedTensorsConfig [[autodoc]] CompressedTensorsConfig ## TorchAoConfig [[autodoc]] TorchAoConfig ## BitNetQuantConfig [[autodoc]] BitNetQuantConfig ## SpQRConfig [[autodoc]] SpQRConfig ## FineGrainedFP8Config [[autodoc]] FineGrainedFP8Config ## QuarkConfig [[autodoc]] QuarkConfig ## FPQuantConfig [[autodoc]] FPQuantConfig ## AutoRoundConfig [[autodoc]] AutoRoundConfig
transformers/docs/source/en/main_classes/quantization.md/0
{ "file_path": "transformers/docs/source/en/main_classes/quantization.md", "repo_id": "transformers", "token_count": 696 }
385
<!--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. --> *This model was released on 2023-04-09 and added to Hugging Face Transformers on 2023-07-17.* # Bark <div class="flex flex-wrap space-x-1"> <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white"> <img alt="FlashAttention" src="https://img.shields.io/badge/%E2%9A%A1%EF%B8%8E%20FlashAttention-eae0c8?style=flat"> </div> ## Overview [Bark](https://huggingface.co/suno/bark) is a transformer-based text-to-speech model proposed by Suno AI in [suno-ai/bark](https://github.com/suno-ai/bark). Bark is made of 4 main models: - [`BarkSemanticModel`] (also referred to as the 'text' model): a causal auto-regressive transformer model that takes as input tokenized text, and predicts semantic text tokens that capture the meaning of the text. - [`BarkCoarseModel`] (also referred to as the 'coarse acoustics' model): a causal autoregressive transformer, that takes as input the results of the [`BarkSemanticModel`] model. It aims at predicting the first two audio codebooks necessary for EnCodec. - [`BarkFineModel`] (the 'fine acoustics' model), this time a non-causal autoencoder transformer, which iteratively predicts the last codebooks based on the sum of the previous codebooks embeddings. - having predicted all the codebook channels from the [`EncodecModel`], Bark uses it to decode the output audio array. It should be noted that each of the first three modules can support conditional speaker embeddings to condition the output sound according to specific predefined voice. This model was contributed by [Yoach Lacombe (ylacombe)](https://huggingface.co/ylacombe) and [Sanchit Gandhi (sanchit-gandhi)](https://github.com/sanchit-gandhi). The original code can be found [here](https://github.com/suno-ai/bark). ### Optimizing Bark Bark can be optimized with just a few extra lines of code, which **significantly reduces its memory footprint** and **accelerates inference**. #### Using half-precision You can speed up inference and reduce memory footprint by 50% simply by loading the model in half-precision. ```python from transformers import BarkModel, infer_device import torch device = infer_device() model = BarkModel.from_pretrained("suno/bark-small", dtype=torch.float16).to(device) ``` #### Using CPU offload As mentioned above, Bark is made up of 4 sub-models, which are called up sequentially during audio generation. In other words, while one sub-model is in use, the other sub-models are idle. If you're using a CUDA GPU or Intel XPU, a simple solution to benefit from an 80% reduction in memory footprint is to offload the submodels from device to CPU when they're idle. This operation is called *CPU offloading*. You can use it with one line of code as follows: ```python model.enable_cpu_offload() ``` Note that 🤗 Accelerate must be installed before using this feature. [Here's how to install it.](https://huggingface.co/docs/accelerate/basic_tutorials/install) #### Using Better Transformer Better Transformer is an 🤗 Optimum feature that performs kernel fusion under the hood. You can gain 20% to 30% in speed with zero performance degradation. It only requires one line of code to export the model to 🤗 Better Transformer: ```python model = model.to_bettertransformer() ``` Note that 🤗 Optimum must be installed before using this feature. [Here's how to install it.](https://huggingface.co/docs/optimum/installation) #### Using Flash Attention 2 Flash Attention 2 is an even faster, optimized version of the previous optimization. ##### Installation First, check whether your hardware is compatible with Flash Attention 2. The latest list of compatible hardware can be found in the [official documentation](https://github.com/Dao-AILab/flash-attention#installation-and-features). If your hardware is not compatible with Flash Attention 2, you can still benefit from attention kernel optimisations through Better Transformer support covered [above](https://huggingface.co/docs/transformers/main/en/model_doc/bark#using-better-transformer). Next, [install](https://github.com/Dao-AILab/flash-attention#installation-and-features) the latest version of Flash Attention 2: ```bash pip install -U flash-attn --no-build-isolation ``` ##### Usage To load a model using Flash Attention 2, we can pass the `attn_implementation="flash_attention_2"` flag to [`.from_pretrained`](https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel.from_pretrained). We'll also load the model in half-precision (e.g. `torch.float16`), since it results in almost no degradation to audio quality but significantly lower memory usage and faster inference: ```python model = BarkModel.from_pretrained("suno/bark-small", dtype=torch.float16, attn_implementation="flash_attention_2").to(device) ``` ##### Performance comparison The following diagram shows the latency for the native attention implementation (no optimisation) against Better Transformer and Flash Attention 2. In all cases, we generate 400 semantic tokens on a 40GB A100 GPU with PyTorch 2.1. Flash Attention 2 is also consistently faster than Better Transformer, and its performance improves even more as batch sizes increase: <div style="text-align: center"> <img src="https://huggingface.co/datasets/ylacombe/benchmark-comparison/resolve/main/Bark%20Optimization%20Benchmark.png"> </div> To put this into perspective, on an NVIDIA A100 and when generating 400 semantic tokens with a batch size of 16, you can get 17 times the [throughput](https://huggingface.co/blog/optimizing-bark#throughput) and still be 2 seconds faster than generating sentences one by one with the native model implementation. In other words, all the samples will be generated 17 times faster. At batch size 8, on an NVIDIA A100, Flash Attention 2 is also 10% faster than Better Transformer, and at batch size 16, 25%. #### Combining optimization techniques You can combine optimization techniques, and use CPU offload, half-precision and Flash Attention 2 (or 🤗 Better Transformer) all at once. ```python from transformers import BarkModel, infer_device import torch device = infer_device() # load in fp16 and use Flash Attention 2 model = BarkModel.from_pretrained("suno/bark-small", dtype=torch.float16, attn_implementation="flash_attention_2").to(device) # enable CPU offload model.enable_cpu_offload() ``` Find out more on inference optimization techniques [here](https://huggingface.co/docs/transformers/perf_infer_gpu_one). ### Usage tips Suno offers a library of voice presets in a number of languages [here](https://suno-ai.notion.site/8b8e8749ed514b0cbf3f699013548683?v=bc67cff786b04b50b3ceb756fd05f68c). These presets are also uploaded in the hub [here](https://huggingface.co/suno/bark-small/tree/main/speaker_embeddings) or [here](https://huggingface.co/suno/bark/tree/main/speaker_embeddings). ```python >>> from transformers import AutoProcessor, BarkModel >>> processor = AutoProcessor.from_pretrained("suno/bark") >>> model = BarkModel.from_pretrained("suno/bark") >>> voice_preset = "v2/en_speaker_6" >>> inputs = processor("Hello, my dog is cute", voice_preset=voice_preset) >>> audio_array = model.generate(**inputs) >>> audio_array = audio_array.cpu().numpy().squeeze() ``` Bark can generate highly realistic, **multilingual** speech as well as other audio - including music, background noise and simple sound effects. ```python >>> # Multilingual speech - simplified Chinese >>> inputs = processor("惊人的!我会说中文") >>> # Multilingual speech - French - let's use a voice_preset as well >>> inputs = processor("Incroyable! Je peux générer du son.", voice_preset="fr_speaker_5") >>> # Bark can also generate music. You can help it out by adding music notes around your lyrics. >>> inputs = processor("♪ Hello, my dog is cute ♪") >>> audio_array = model.generate(**inputs) >>> audio_array = audio_array.cpu().numpy().squeeze() ``` The model can also produce **nonverbal communications** like laughing, sighing and crying. ```python >>> # Adding non-speech cues to the input text >>> inputs = processor("Hello uh ... [clears throat], my dog is cute [laughter]") >>> audio_array = model.generate(**inputs) >>> audio_array = audio_array.cpu().numpy().squeeze() ``` To save the audio, simply take the sample rate from the model config and some scipy utility: ```python >>> from scipy.io.wavfile import write as write_wav >>> # save audio to disk, but first take the sample rate from the model config >>> sample_rate = model.generation_config.sample_rate >>> write_wav("bark_generation.wav", sample_rate, audio_array) ``` ## BarkConfig [[autodoc]] BarkConfig - all ## BarkProcessor [[autodoc]] BarkProcessor - all - __call__ ## BarkModel [[autodoc]] BarkModel - generate - enable_cpu_offload ## BarkSemanticModel [[autodoc]] BarkSemanticModel - forward ## BarkCoarseModel [[autodoc]] BarkCoarseModel - forward ## BarkFineModel [[autodoc]] BarkFineModel - forward ## BarkCausalModel [[autodoc]] BarkCausalModel - forward ## BarkCoarseConfig [[autodoc]] BarkCoarseConfig - all ## BarkFineConfig [[autodoc]] BarkFineConfig - all ## BarkSemanticConfig [[autodoc]] BarkSemanticConfig - all
transformers/docs/source/en/model_doc/bark.md/0
{ "file_path": "transformers/docs/source/en/model_doc/bark.md", "repo_id": "transformers", "token_count": 2907 }
386
<!--Copyright 2024 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. --> *This model was released on 2022-01-28 and added to Hugging Face Transformers on 2025-02-04.* # DAB-DETR <div class="flex flex-wrap space-x-1"> <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white"> </div> ## Overview The DAB-DETR model was proposed in [DAB-DETR: Dynamic Anchor Boxes are Better Queries for DETR](https://huggingface.co/papers/2201.12329) by Shilong Liu, Feng Li, Hao Zhang, Xiao Yang, Xianbiao Qi, Hang Su, Jun Zhu, Lei Zhang. DAB-DETR is an enhanced variant of Conditional DETR. It utilizes dynamically updated anchor boxes to provide both a reference query point (x, y) and a reference anchor size (w, h), improving cross-attention computation. This new approach achieves 45.7% AP when trained for 50 epochs with a single ResNet-50 model as the backbone. <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/dab_detr_convergence_plot.png" alt="drawing" width="600"/> The abstract from the paper is the following: *We present in this paper a novel query formulation using dynamic anchor boxes for DETR (DEtection TRansformer) and offer a deeper understanding of the role of queries in DETR. This new formulation directly uses box coordinates as queries in Transformer decoders and dynamically updates them layer-by-layer. Using box coordinates not only helps using explicit positional priors to improve the query-to-feature similarity and eliminate the slow training convergence issue in DETR, but also allows us to modulate the positional attention map using the box width and height information. Such a design makes it clear that queries in DETR can be implemented as performing soft ROI pooling layer-by-layer in a cascade manner. As a result, it leads to the best performance on MS-COCO benchmark among the DETR-like detection models under the same setting, e.g., AP 45.7% using ResNet50-DC5 as backbone trained in 50 epochs. We also conducted extensive experiments to confirm our analysis and verify the effectiveness of our methods.* This model was contributed by [davidhajdu](https://huggingface.co/davidhajdu). The original code can be found [here](https://github.com/IDEA-Research/DAB-DETR). ## How to Get Started with the Model Use the code below to get started with the model. ```python import torch import requests from PIL import Image from transformers import AutoModelForObjectDetection, AutoImageProcessor url = 'http://images.cocodataset.org/val2017/000000039769.jpg' image = Image.open(requests.get(url, stream=True).raw) image_processor = AutoImageProcessor.from_pretrained("IDEA-Research/dab-detr-resnet-50") model = AutoModelForObjectDetection.from_pretrained("IDEA-Research/dab-detr-resnet-50") inputs = image_processor(images=image, return_tensors="pt") with torch.no_grad(): outputs = model(**inputs) results = image_processor.post_process_object_detection(outputs, target_sizes=torch.tensor([image.size[::-1]]), threshold=0.3) for result in results: for score, label_id, box in zip(result["scores"], result["labels"], result["boxes"]): score, label = score.item(), label_id.item() box = [round(i, 2) for i in box.tolist()] print(f"{model.config.id2label[label]}: {score:.2f} {box}") ``` This should output ``` cat: 0.87 [14.7, 49.39, 320.52, 469.28] remote: 0.86 [41.08, 72.37, 173.39, 117.2] cat: 0.86 [344.45, 19.43, 639.85, 367.86] remote: 0.61 [334.27, 75.93, 367.92, 188.81] couch: 0.59 [-0.04, 1.34, 639.9, 477.09] ``` There are three other ways to instantiate a DAB-DETR model (depending on what you prefer): Option 1: Instantiate DAB-DETR with pre-trained weights for entire model ```py >>> from transformers import DabDetrForObjectDetection >>> model = DabDetrForObjectDetection.from_pretrained("IDEA-Research/dab-detr-resnet-50") ``` Option 2: Instantiate DAB-DETR with randomly initialized weights for Transformer, but pre-trained weights for backbone ```py >>> from transformers import DabDetrConfig, DabDetrForObjectDetection >>> config = DabDetrConfig() >>> model = DabDetrForObjectDetection(config) ``` Option 3: Instantiate DAB-DETR with randomly initialized weights for backbone + Transformer ```py >>> config = DabDetrConfig(use_pretrained_backbone=False) >>> model = DabDetrForObjectDetection(config) ``` ## DabDetrConfig [[autodoc]] DabDetrConfig ## DabDetrModel [[autodoc]] DabDetrModel - forward ## DabDetrForObjectDetection [[autodoc]] DabDetrForObjectDetection - forward
transformers/docs/source/en/model_doc/dab-detr.md/0
{ "file_path": "transformers/docs/source/en/model_doc/dab-detr.md", "repo_id": "transformers", "token_count": 1652 }
387
<!--Copyright 2024 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. --> *This model was released on 2024-10-02 and added to Hugging Face Transformers on 2025-02-10.* # DepthPro <div class="flex flex-wrap space-x-1"> <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white"> </div> ## Overview The DepthPro model was proposed in [Depth Pro: Sharp Monocular Metric Depth in Less Than a Second](https://huggingface.co/papers/2410.02073) by Aleksei Bochkovskii, Amaël Delaunoy, Hugo Germain, Marcel Santos, Yichao Zhou, Stephan R. Richter, Vladlen Koltun. DepthPro is a foundation model for zero-shot metric monocular depth estimation, designed to generate high-resolution depth maps with remarkable sharpness and fine-grained details. It employs a multi-scale Vision Transformer (ViT)-based architecture, where images are downsampled, divided into patches, and processed using a shared Dinov2 encoder. The extracted patch-level features are merged, upsampled, and refined using a DPT-like fusion stage, enabling precise depth estimation. The abstract from the paper is the following: *We present a foundation model for zero-shot metric monocular depth estimation. Our model, Depth Pro, synthesizes high-resolution depth maps with unparalleled sharpness and high-frequency details. The predictions are metric, with absolute scale, without relying on the availability of metadata such as camera intrinsics. And the model is fast, producing a 2.25-megapixel depth map in 0.3 seconds on a standard GPU. These characteristics are enabled by a number of technical contributions, including an efficient multi-scale vision transformer for dense prediction, a training protocol that combines real and synthetic datasets to achieve high metric accuracy alongside fine boundary tracing, dedicated evaluation metrics for boundary accuracy in estimated depth maps, and state-of-the-art focal length estimation from a single image. Extensive experiments analyze specific design choices and demonstrate that Depth Pro outperforms prior work along multiple dimensions.* <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/depth_pro_teaser.png" alt="drawing" width="600"/> <small> DepthPro Outputs. Taken from the <a href="https://github.com/apple/ml-depth-pro" target="_blank">official code</a>. </small> This model was contributed by [geetu040](https://github.com/geetu040). The original code can be found [here](https://github.com/apple/ml-depth-pro). ## Usage Tips The DepthPro model processes an input image by first downsampling it at multiple scales and splitting each scaled version into patches. These patches are then encoded using a shared Vision Transformer (ViT)-based Dinov2 patch encoder, while the full image is processed by a separate image encoder. The extracted patch features are merged into feature maps, upsampled, and fused using a DPT-like decoder to generate the final depth estimation. If enabled, an additional Field of View (FOV) encoder processes the image for estimating the camera's field of view, aiding in depth accuracy. ```py >>> import requests >>> from PIL import Image >>> import torch >>> from transformers import DepthProImageProcessorFast, DepthProForDepthEstimation, infer_device >>> device = infer_device() >>> url = 'http://images.cocodataset.org/val2017/000000039769.jpg' >>> image = Image.open(requests.get(url, stream=True).raw) >>> image_processor = DepthProImageProcessorFast.from_pretrained("apple/DepthPro-hf") >>> model = DepthProForDepthEstimation.from_pretrained("apple/DepthPro-hf").to(device) >>> inputs = image_processor(images=image, return_tensors="pt").to(model.device) >>> with torch.no_grad(): ... outputs = model(**inputs) >>> post_processed_output = image_processor.post_process_depth_estimation( ... outputs, target_sizes=[(image.height, image.width)], ... ) >>> field_of_view = post_processed_output[0]["field_of_view"] >>> focal_length = post_processed_output[0]["focal_length"] >>> depth = post_processed_output[0]["predicted_depth"] >>> depth = (depth - depth.min()) / depth.max() >>> depth = depth * 255. >>> depth = depth.detach().cpu().numpy() >>> depth = Image.fromarray(depth.astype("uint8")) ``` ### Architecture and Configuration <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/depth_pro_architecture.png" alt="drawing" width="600"/> <small> DepthPro architecture. Taken from the <a href="https://huggingface.co/papers/2410.02073" target="_blank">original paper</a>. </small> The `DepthProForDepthEstimation` model uses a `DepthProEncoder`, for encoding the input image and a `FeatureFusionStage` for fusing the output features from encoder. The `DepthProEncoder` further uses two encoders: - `patch_encoder` - Input image is scaled with multiple ratios, as specified in the `scaled_images_ratios` configuration. - Each scaled image is split into smaller **patches** of size `patch_size` with overlapping areas determined by `scaled_images_overlap_ratios`. - These patches are processed by the **`patch_encoder`** - `image_encoder` - Input image is also rescaled to `patch_size` and processed by the **`image_encoder`** Both these encoders can be configured via `patch_model_config` and `image_model_config` respectively, both of which are separate `Dinov2Model` by default. Outputs from both encoders (`last_hidden_state`) and selected intermediate states (`hidden_states`) from **`patch_encoder`** are fused by a `DPT`-based `FeatureFusionStage` for depth estimation. ### Field-of-View (FOV) Prediction The network is supplemented with a focal length estimation head. A small convolutional head ingests frozen features from the depth estimation network and task-specific features from a separate ViT image encoder to predict the horizontal angular field-of-view. The `use_fov_model` parameter in `DepthProConfig` controls whether **FOV prediction** is enabled. By default, it is set to `False` to conserve memory and computation. When enabled, the **FOV encoder** is instantiated based on the `fov_model_config` parameter, which defaults to a `Dinov2Model`. The `use_fov_model` parameter can also be passed when initializing the `DepthProForDepthEstimation` model. The pretrained model at checkpoint `apple/DepthPro-hf` uses the FOV encoder. To use the pretrained-model without FOV encoder, set `use_fov_model=False` when loading the model, which saves computation. ```py >>> from transformers import DepthProForDepthEstimation >>> model = DepthProForDepthEstimation.from_pretrained("apple/DepthPro-hf", use_fov_model=False) ``` To instantiate a new model with FOV encoder, set `use_fov_model=True` in the config. ```py >>> from transformers import DepthProConfig, DepthProForDepthEstimation >>> config = DepthProConfig(use_fov_model=True) >>> model = DepthProForDepthEstimation(config) ``` Or set `use_fov_model=True` when initializing the model, which overrides the value in config. ```py >>> from transformers import DepthProConfig, DepthProForDepthEstimation >>> config = DepthProConfig() >>> model = DepthProForDepthEstimation(config, use_fov_model=True) ``` ### Using Scaled Dot Product Attention (SDPA) PyTorch includes a native scaled dot-product attention (SDPA) operator as part of `torch.nn.functional`. This function encompasses several implementations that can be applied depending on the inputs and the hardware in use. See the [official documentation](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) or the [GPU Inference](https://huggingface.co/docs/transformers/main/en/perf_infer_gpu_one#pytorch-scaled-dot-product-attention) page for more information. SDPA is used by default for `torch>=2.1.1` when an implementation is available, but you may also set `attn_implementation="sdpa"` in `from_pretrained()` to explicitly request SDPA to be used. ```py from transformers import DepthProForDepthEstimation model = DepthProForDepthEstimation.from_pretrained("apple/DepthPro-hf", attn_implementation="sdpa", dtype=torch.float16) ``` For the best speedups, we recommend loading the model in half-precision (e.g. `torch.float16` or `torch.bfloat16`). On a local benchmark (A100-40GB, PyTorch 2.3.0, OS Ubuntu 22.04) with `float32` and `google/vit-base-patch16-224` model, we saw the following speedups during inference. | Batch size | Average inference time (ms), eager mode | Average inference time (ms), sdpa model | Speed up, Sdpa / Eager (x) | |--------------|-------------------------------------------|-------------------------------------------|------------------------------| | 1 | 7 | 6 | 1.17 | | 2 | 8 | 6 | 1.33 | | 4 | 8 | 6 | 1.33 | | 8 | 8 | 6 | 1.33 | ## Resources A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with DepthPro: - Research Paper: [Depth Pro: Sharp Monocular Metric Depth in Less Than a Second](https://huggingface.co/papers/2410.02073) - Official Implementation: [apple/ml-depth-pro](https://github.com/apple/ml-depth-pro) - DepthPro Inference Notebook: [DepthPro Inference](https://github.com/qubvel/transformers-notebooks/blob/main/notebooks/DepthPro_inference.ipynb) - DepthPro for Super Resolution and Image Segmentation - Read blog on Medium: [Depth Pro: Beyond Depth](https://medium.com/@raoarmaghanshakir040/depth-pro-beyond-depth-9d822fc557ba) - Code on Github: [geetu040/depthpro-beyond-depth](https://github.com/geetu040/depthpro-beyond-depth) If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. ## DepthProConfig [[autodoc]] DepthProConfig ## DepthProImageProcessor [[autodoc]] DepthProImageProcessor - preprocess - post_process_depth_estimation ## DepthProImageProcessorFast [[autodoc]] DepthProImageProcessorFast - preprocess - post_process_depth_estimation ## DepthProModel [[autodoc]] DepthProModel - forward ## DepthProForDepthEstimation [[autodoc]] DepthProForDepthEstimation - forward
transformers/docs/source/en/model_doc/depth_pro.md/0
{ "file_path": "transformers/docs/source/en/model_doc/depth_pro.md", "repo_id": "transformers", "token_count": 3554 }
388
<!--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. ⚠️ 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. --> *This model was released on 2023-11-28 and added to Hugging Face Transformers on 2023-07-11.* <div style="float: right;"> <div class="flex flex-wrap space-x-1"> <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white"> <img alt="FlashAttention" src="https://img.shields.io/badge/%E2%9A%A1%EF%B8%8E%20FlashAttention-eae0c8?style=flat"> <img alt="SDPA" src="https://img.shields.io/badge/SDPA-DE3412?style=flat&logo=pytorch&logoColor=white"> </div> </div> # Falcon [Falcon](https://huggingface.co/papers/2311.16867) is a family of large language models, available in 7B, 40B, and 180B parameters, as pretrained and instruction tuned variants. This model focuses on scaling pretraining over three categories, performance, data, and hardware. Falcon uses multigroup attention to significantly reduce inference memory requirements and rotary positional embeddings (RoPE). These models are pretrained on [RefinedWeb](https://huggingface.co/datasets/tiiuae/falcon-refinedweb), a high-quality and deduplicated 5T token dataset. You can find all the original Falcon checkpoints under the [Falcon](https://huggingface.co/collections/tiiuae/falcon-64fb432660017eeec9837b5a) collection. > [!TIP] > Click on the Falcon models in the right sidebar for more examples of how to apply Falcon to different language tasks. The example below demonstrates how to generate text with [`Pipeline`], [`AutoModel`], and from the command line. <hfoptions id="usage"> <hfoption id="Pipeline"> ```py import torch from transformers import pipeline pipeline = pipeline( task="text-generation", model="tiiuae/falcon-7b-instruct", dtype=torch.bfloat16, device=0 ) pipeline( "Write a short poem about coding", max_length=100, do_sample=True, temperature=0.7 ) ``` </hfoption> <hfoption id="AutoModel"> ```py import torch from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("tiiuae/falcon-7b-instruct") model = AutoModelForCausalLM.from_pretrained( "tiiuae/falcon-7b-instruct", dtype=torch.bfloat16, device_map="auto", attn_implementation="sdpa", ) input_ids = tokenizer("Write a short poem about coding", return_tensors="pt").to(model.device) output = model.generate(**input_ids) print(tokenizer.decode(output[0], skip_special_tokens=True)) ``` </hfoption> <hfoption id="transformers CLI"> ```bash # pip install -U flash-attn --no-build-isolation transformers chat tiiuae/falcon-7b-instruct --dtype auto --attn_implementation flash_attention_2 --device 0 ``` </hfoption> </hfoptions> Quantization reduces the memory burden of large models by representing the weights in a lower precision. Refer to the [Quantization](../quantization/overview) overview for more available quantization backends. The example below uses [bitsandbytes](../quantization/bitsandbytes) to only quantize the weights to 4-bits. ```python import torch from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig quantization_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, ) tokenizer = AutoTokenizer.from_pretrained("tiiuae/falcon-7b") model = AutoModelForCausalLM.from_pretrained( "tiiuae/falcon-7b", dtype=torch.bfloat16, device_map="auto", quantization_config=quantization_config, ) inputs = tokenizer("In quantum physics, entanglement means", return_tensors="pt").to(model.device) outputs = model.generate(**inputs, max_new_tokens=100) print(tokenizer.decode(outputs[0], skip_special_tokens=True)) ``` ## Notes - If you're upgrading from an older custom code checkpoint, remember to convert it to the official Transformers format for better stability and performance using the conversion script located in the [Falcon model directory](https://github.com/huggingface/transformers/tree/main/src/transformers/models/falcon). ```bash python convert_custom_code_checkpoint.py --checkpoint_dir my_model ``` ## FalconConfig [[autodoc]] FalconConfig - all ## FalconModel [[autodoc]] FalconModel - forward ## FalconForCausalLM [[autodoc]] FalconForCausalLM - forward ## FalconForSequenceClassification [[autodoc]] FalconForSequenceClassification - forward ## FalconForTokenClassification [[autodoc]] FalconForTokenClassification - forward ## FalconForQuestionAnswering [[autodoc]] FalconForQuestionAnswering - forward
transformers/docs/source/en/model_doc/falcon.md/0
{ "file_path": "transformers/docs/source/en/model_doc/falcon.md", "repo_id": "transformers", "token_count": 1752 }
389
<!--Copyright 2024 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. --> *This model was released on 2024-07-31 and added to Hugging Face Transformers on 2024-06-27.* <div style="float: right;"> <div class="flex flex-wrap space-x-1"> <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white"> <img alt="FlashAttention" src="https://img.shields.io/badge/%E2%9A%A1%EF%B8%8E%20FlashAttention-eae0c8?style=flat"> <img alt="SDPA" src="https://img.shields.io/badge/SDPA-DE3412?style=flat&logo=pytorch&logoColor=white"> <img alt="Tensor parallelism" src="https://img.shields.io/badge/Tensor%20parallelism-06b6d4?style=flat&logoColor=white"> </div> </div> # Gemma2 [Gemma 2](https://huggingface.co/papers/2408.00118) is a family of language models with pretrained and instruction-tuned variants, available in 2B, 9B, 27B parameters. The architecture is similar to the previous Gemma, except it features interleaved local attention (4096 tokens) and global attention (8192 tokens) and grouped-query attention (GQA) to increase inference performance. The 2B and 9B models are trained with knowledge distillation, and the instruction-tuned variant was post-trained with supervised fine-tuning and reinforcement learning. You can find all the original Gemma 2 checkpoints under the [Gemma 2](https://huggingface.co/collections/google/gemma-2-release-667d6600fd5220e7b967f315) collection. > [!TIP] > Click on the Gemma 2 models in the right sidebar for more examples of how to apply Gemma to different language tasks. The example below demonstrates how to chat with the model with [`Pipeline`] or the [`AutoModel`] class, and from the command line. <hfoptions id="usage"> <hfoption id="Pipeline"> ```python import torch from transformers import pipeline pipe = pipeline( task="text-generation", model="google/gemma-2-9b", dtype=torch.bfloat16, device_map="auto", ) pipe("Explain quantum computing simply. ", max_new_tokens=50) ``` </hfoption> <hfoption id="AutoModel"> ```python import torch from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-9b") model = AutoModelForCausalLM.from_pretrained( "google/gemma-2-9b", dtype=torch.bfloat16, device_map="auto", attn_implementation="sdpa" ) input_text = "Explain quantum computing simply." input_ids = tokenizer(input_text, return_tensors="pt").to(model.device) outputs = model.generate(**input_ids, max_new_tokens=32, cache_implementation="static") print(tokenizer.decode(outputs[0], skip_special_tokens=True)) ``` </hfoption> <hfoption id="transformers CLI"> ``` echo -e "Explain quantum computing simply." | transformers run --task text-generation --model google/gemma-2-2b --device 0 ``` </hfoption> </hfoptions> Quantization reduces the memory burden of large models by representing the weights in a lower precision. Refer to the [Quantization](../quantization/overview) overview for more available quantization backends. The example below uses [bitsandbytes](../quantization/bitsandbytes) to only quantize the weights to int4. ```python import torch from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig quantization_config = BitsAndBytesConfig(load_in_4bit=True) tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-27b") model = AutoModelForCausalLM.from_pretrained( "google/gemma-2-27b", dtype=torch.bfloat16, device_map="auto", attn_implementation="sdpa" ) input_text = "Explain quantum computing simply." input_ids = tokenizer(input_text, return_tensors="pt").to(model.device) outputs = model.generate(**input_ids, max_new_tokens=32, cache_implementation="static") print(tokenizer.decode(outputs[0], skip_special_tokens=True)) ``` Use the [AttentionMaskVisualizer](https://github.com/huggingface/transformers/blob/beb9b5b02246b9b7ee81ddf938f93f44cfeaad19/src/transformers/utils/attention_visualizer.py#L139) to better understand what tokens the model can and cannot attend to. ```python from transformers.utils.attention_visualizer import AttentionMaskVisualizer visualizer = AttentionMaskVisualizer("google/gemma-2b") visualizer("You are an assistant. Make sure you print me") ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/gemma-2-attn-mask.png"/> </div> ## Gemma2Config [[autodoc]] Gemma2Config ## Gemma2Model [[autodoc]] Gemma2Model - forward ## Gemma2ForCausalLM [[autodoc]] Gemma2ForCausalLM - forward ## Gemma2ForSequenceClassification [[autodoc]] Gemma2ForSequenceClassification - forward ## Gemma2ForTokenClassification [[autodoc]] Gemma2ForTokenClassification - forward
transformers/docs/source/en/model_doc/gemma2.md/0
{ "file_path": "transformers/docs/source/en/model_doc/gemma2.md", "repo_id": "transformers", "token_count": 1826 }
390
<!--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. --> <div style="float: right;"> <div class="flex flex-wrap space-x-1"> <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColorF=white"> </div> </div> *This model was released on 2022-07-27 and added to Hugging Face Transformers on 2022-09-14.* # GPT-NeoX-Japanese GPT-NeoX-Japanese, a Japanese language model based on [GPT-NeoX](./gpt_neox). Japanese uses three types of characters (hiragana, katakana, kanji) and has a huge vocabulary. This model uses [BPEEncoder V2](https://github.com/tanreinama/Japanese-BPEEncoder_V2), a sub-word tokenizer to handle the different characters. The model also removes some bias parameters for better performance. You can find all the original GPT-NeoX-Japanese checkpoints under the [ABEJA](https://huggingface.co/abeja/models?search=gpt-neo-x) organization. > [!TIP] > This model was contributed by [Shinya Otani](https://github.com/SO0529), [Takayoshi Makabe](https://github.com/spider-man-tm), [Anuj Arora](https://github.com/Anuj040), and [Kyo Hattori](https://github.com/go5paopao) from [ABEJA, Inc.](https://www.abejainc.com/). > > Click on the GPT-NeoX-Japanese models in the right sidebar for more examples of how to apply GPT-NeoX-Japanese to different language tasks. The example below demonstrates how to generate text with [`Pipeline`] or the [`AutoModel`], and from the command line. <hfoptions id="usage"> <hfoption id="Pipeline"> ```py import torch from transformers import pipeline pipeline = pipeline(task="text-generation", model="abeja/gpt-neox-japanese-2.7b", dtype=torch.float16, device=0) pipeline("人とAIが協調するためには、") ``` </hfoption> <hfoption id="AutoModel"> ```py import torch from transformers import AutoModelForCausalLM, AutoTokenizer model = AutoModelForCausalLM.from_pretrained("abeja/gpt-neox-japanese-2.7b", dtype=torch.float16, device_map="auto") tokenizer = AutoTokenizer.from_pretrained("abeja/gpt-neox-japanese-2.7b") input_ids = tokenizer("人とAIが協調するためには、", return_tensors="pt").input_ids.to(model.device) outputs = model.generate(input_ids) print(tokenizer.decode(outputs[0], skip_special_tokens=True)) ``` </hfoption> <hfoption id="transformers CLI"> ```bash echo -e "人とAIが協調するためには、" | transformers run --task text-generation --model abeja/gpt-neox-japanese-2.7b --device 0 ``` </hfoption> </hfoptions> Quantization reduces the memory burden of large models by representing the weights in a lower precision. Refer to the [Quantization](../quantization/overview) overview for more available quantization backends. The example below uses [bitsandbytes](../quantization/bitsandbytes) to only quantize the weights to 4-bits. ```py import torch from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig quantization_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_use_double_quant=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype="float16" ) model = AutoModelForCausalLM.from_pretrained( "abeja/gpt-neox-japanese-2.7b", quantization_config=quantization_config, device_map="auto" ) tokenizer = AutoTokenizer.from_pretrained("abeja/gpt-neox-japanese-2.7b") input_ids = tokenizer.encode("人とAIが協調するためには、", return_tensors="pt").to(model.device) output = model.generate(input_ids) print(tokenizer.decode(output[0], skip_special_tokens=True)) ``` Use the [AttentionMaskVisualizer](https://github.com/huggingface/transformers/blob/beb9b5b02246b9b7ee81ddf938f93f44cfeaad19/src/transformers/utils/attention_visualizer.py#L139) to better understand what tokens the model can and cannot attend to. ```py from transformers.utils.attention_visualizer import AttentionMaskVisualizer visualizer = AttentionMaskVisualizer("abeja/gpt-neox-japanese-2.7b") visualizer("<img>What is shown in this image?") ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/gpt_neox_japanese-attn-mask.png"/> </div> ## Resources Refer to the [Training a better GPT model: Learnings from PaLM](https://medium.com/ml-abeja/training-a-better-gpt-2-93b157662ae4) blog post for more details about how ABEJA trained GPT-NeoX-Japanese. ## GPTNeoXJapaneseConfig [[autodoc]] GPTNeoXJapaneseConfig ## GPTNeoXJapaneseTokenizer [[autodoc]] GPTNeoXJapaneseTokenizer ## GPTNeoXJapaneseModel [[autodoc]] GPTNeoXJapaneseModel - forward ## GPTNeoXJapaneseForCausalLM [[autodoc]] GPTNeoXJapaneseForCausalLM - forward
transformers/docs/source/en/model_doc/gpt_neox_japanese.md/0
{ "file_path": "transformers/docs/source/en/model_doc/gpt_neox_japanese.md", "repo_id": "transformers", "token_count": 1865 }
391
<!--Copyright 2024 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. --> *This model was released on 2023-06-01 and added to Hugging Face Transformers on 2024-07-12.* # Hiera <div class="flex flex-wrap space-x-1"> <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white"> </div> ## Overview Hiera was proposed in [Hiera: A Hierarchical Vision Transformer without the Bells-and-Whistles](https://huggingface.co/papers/2306.00989) by Chaitanya Ryali, Yuan-Ting Hu, Daniel Bolya, Chen Wei, Haoqi Fan, Po-Yao Huang, Vaibhav Aggarwal, Arkabandhu Chowdhury, Omid Poursaeed, Judy Hoffman, Jitendra Malik, Yanghao Li, Christoph Feichtenhofer The paper introduces "Hiera," a hierarchical Vision Transformer that simplifies the architecture of modern hierarchical vision transformers by removing unnecessary components without compromising on accuracy or efficiency. Unlike traditional transformers that add complex vision-specific components to improve supervised classification performance, Hiera demonstrates that such additions, often termed "bells-and-whistles," are not essential for high accuracy. By leveraging a strong visual pretext task (MAE) for pretraining, Hiera retains simplicity and achieves superior accuracy and speed both in inference and training across various image and video recognition tasks. The approach suggests that spatial biases required for vision tasks can be effectively learned through proper pretraining, eliminating the need for added architectural complexity. The abstract from the paper is the following: *Modern hierarchical vision transformers have added several vision-specific components in the pursuit of supervised classification performance. While these components lead to effective accuracies and attractive FLOP counts, the added complexity actually makes these transformers slower than their vanilla ViT counterparts. In this paper, we argue that this additional bulk is unnecessary. By pretraining with a strong visual pretext task (MAE), we can strip out all the bells-and-whistles from a state-of-the-art multi-stage vision transformer without losing accuracy. In the process, we create Hiera, an extremely simple hierarchical vision transformer that is more accurate than previous models while being significantly faster both at inference and during training. We evaluate Hiera on a variety of tasks for image and video recognition. Our code and models are available at https://github.com/facebookresearch/hiera.* <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/hiera_overview.png" alt="drawing" width="600"/> <small> Hiera architecture. Taken from the <a href="https://huggingface.co/papers/2306.00989">original paper.</a> </small> This model was a joint contribution by [EduardoPacheco](https://huggingface.co/EduardoPacheco) and [namangarg110](https://huggingface.co/namangarg110). The original code can be found [here] (https://github.com/facebookresearch/hiera). ## Resources A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with Hiera. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource. <PipelineTag pipeline="image-classification"/> - [`HieraForImageClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb). - See also: [Image classification task guide](../tasks/image_classification) ## HieraConfig [[autodoc]] HieraConfig ## HieraModel [[autodoc]] HieraModel - forward ## HieraForPreTraining [[autodoc]] HieraForPreTraining - forward ## HieraForImageClassification [[autodoc]] HieraForImageClassification - forward
transformers/docs/source/en/model_doc/hiera.md/0
{ "file_path": "transformers/docs/source/en/model_doc/hiera.md", "repo_id": "transformers", "token_count": 1214 }
392
<!--Copyright 2024 JetMoe team and 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. --> *This model was released on 2023-06-07 and added to Hugging Face Transformers on 2024-05-14.* # JetMoe <div class="flex flex-wrap space-x-1"> <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white"> <img alt="FlashAttention" src="https://img.shields.io/badge/%E2%9A%A1%EF%B8%8E%20FlashAttention-eae0c8?style=flat"> <img alt="SDPA" src="https://img.shields.io/badge/SDPA-DE3412?style=flat&logo=pytorch&logoColor=white"> </div> ## Overview **JetMoe-8B** is an 8B Mixture-of-Experts (MoE) language model developed by [Yikang Shen](https://scholar.google.com.hk/citations?user=qff5rRYAAAAJ) and [MyShell](https://myshell.ai/). JetMoe project aims to provide a LLaMA2-level performance and efficient language model with a limited budget. To achieve this goal, JetMoe uses a sparsely activated architecture inspired by the [ModuleFormer](https://huggingface.co/papers/2306.04640). Each JetMoe block consists of two MoE layers: Mixture of Attention Heads and Mixture of MLP Experts. Given the input tokens, it activates a subset of its experts to process them. This sparse activation schema enables JetMoe to achieve much better training throughput than similar size dense models. The training throughput of JetMoe-8B is around 100B tokens per day on a cluster of 96 H100 GPUs with a straightforward 3-way pipeline parallelism strategy. This model was contributed by [Yikang Shen](https://huggingface.co/YikangS). ## JetMoeConfig [[autodoc]] JetMoeConfig ## JetMoeModel [[autodoc]] JetMoeModel - forward ## JetMoeForCausalLM [[autodoc]] JetMoeForCausalLM - forward ## JetMoeForSequenceClassification [[autodoc]] JetMoeForSequenceClassification - forward
transformers/docs/source/en/model_doc/jetmoe.md/0
{ "file_path": "transformers/docs/source/en/model_doc/jetmoe.md", "repo_id": "transformers", "token_count": 766 }
393
<!--Copyright 2024 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. --> *This model was released on 2024-04-18 and added to Hugging Face Transformers on 2024-04-24.* # Llama3 <div class="flex flex-wrap space-x-1"> <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white"> <img alt="Tensor parallelism" src="https://img.shields.io/badge/Tensor%20parallelism-06b6d4?style=flat&logoColor=white"> </div> ```py3 import transformers import torch model_id = "meta-llama/Meta-Llama-3-8B" pipeline = transformers.pipeline("text-generation", model=model_id, model_kwargs={"dtype": torch.bfloat16}, device_map="auto") pipeline("Hey how are you doing today?") ``` ## Overview The [Llama3](https://huggingface.co/papers/2407.21783) model was proposed in [Introducing Meta Llama 3: The most capable openly available LLM to date](https://ai.meta.com/blog/meta-llama-3/) by the meta AI team. The abstract from the blogpost is the following: *Today, we’re excited to share the first two models of the next generation of Llama, Meta Llama 3, available for broad use. This release features pretrained and instruction-fine-tuned language models with 8B and 70B parameters that can support a broad range of use cases. This next generation of Llama demonstrates state-of-the-art performance on a wide range of industry benchmarks and offers new capabilities, including improved reasoning. We believe these are the best open source models of their class, period. In support of our longstanding open approach, we’re putting Llama 3 in the hands of the community. We want to kickstart the next wave of innovation in AI across the stack—from applications to developer tools to evals to inference optimizations and more. We can’t wait to see what you build and look forward to your feedback.* Checkout all Llama3 model checkpoints [here](https://huggingface.co/models?search=llama3). The original code of the authors can be found [here](https://github.com/meta-llama/llama3). ## Usage tips <Tip warning={true}> The `Llama3` models were trained using `bfloat16`, but the original inference uses `float16`. The checkpoints uploaded on the Hub use `dtype = 'float16'`, which will be used by the `AutoModel` API to cast the checkpoints from `torch.float32` to `torch.float16`. The `dtype` of the online weights is mostly irrelevant unless you are using `dtype="auto"` when initializing a model using `model = AutoModelForCausalLM.from_pretrained("path", dtype = "auto")`. The reason is that the model will first be downloaded ( using the `dtype` of the checkpoints online), then it will be casted to the default `dtype` of `torch` (becomes `torch.float32`), and finally, if there is a `dtype` or `torch_dtype` provided in the config, it will be used. Training the model in `float16` is not recommended and is known to produce `nan`; as such, the model should be trained in `bfloat16`. </Tip> Tips: - Weights for the Llama3 models can be obtained by filling out [this form](https://ai.meta.com/resources/models-and-libraries/llama-downloads/) - The architecture is exactly the same as Llama2. - The tokenizer is a BPE model based on [tiktoken](https://github.com/openai/tiktoken) (vs the one based on sentencepiece implementation for Llama2). The main difference that it ignores BPE merge rules when an input token is part of the vocab. This means that if no merge exist to produce `"hugging"`, instead of having the smallest units, like `["hug","ging"] form 2 tokens, if `"hugging"` is part of the vocab, it will be automatically returned as a token. - The original model uses `pad_id = -1` which means that there is no padding token. We can't have the same logic, make sure to add a padding token using `tokenizer.add_special_tokens({"pad_token":"<pad>"})` and resize the token embedding accordingly. You should also set the `model.config.pad_token_id`. The `embed_tokens` layer of the model is initialized with `self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.config.padding_idx)`, which makes sure that encoding the padding token will output zeros, so passing it when initializing is recommended. - The original checkpoint can be converted using the [conversion script](https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/convert_llama_weights_to_hf.py). The script can be called with the following (example) command: ```bash python src/transformers/models/llama/convert_llama_weights_to_hf.py \ --input_dir /path/to/downloaded/llama/weights --model_size 7B --output_dir /output/path --llama_version 3 ``` - After conversion, the model and tokenizer can be loaded via: ```python from transformers import AutoModelForCausalLM, AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("/output/path") model = AutoModelForCausalLM.from_pretrained("/output/path") ``` Note that executing the script requires enough CPU RAM to host the whole model in float16 precision (even if the biggest versions come in several checkpoints they each contain a part of each weight of the model, so we need to load them all in RAM). For the 75B model, it's thus 145GB of RAM needed. - When using Flash Attention 2 via `attn_implementation="flash_attention_2"`, don't pass `dtype` to the `from_pretrained` class method and use Automatic Mixed-Precision training. When using `Trainer`, it is simply specifying either `fp16` or `bf16` to `True`. Otherwise, make sure you are using `torch.autocast`. This is required because the Flash Attention only support `fp16` and `bf16` data type. ## Resources A ton of cool resources are already available on the documentation page of [Llama2](./llama2), inviting contributors to add new resources curated for Llama3 here! 🤗
transformers/docs/source/en/model_doc/llama3.md/0
{ "file_path": "transformers/docs/source/en/model_doc/llama3.md", "repo_id": "transformers", "token_count": 1846 }
394
<!--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. --> *This model was released on 2021-12-02 and added to Hugging Face Transformers on 2023-01-16.* # Mask2Former <div class="flex flex-wrap space-x-1"> <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white"> </div> ## Overview The Mask2Former model was proposed in [Masked-attention Mask Transformer for Universal Image Segmentation](https://huggingface.co/papers/2112.01527) by Bowen Cheng, Ishan Misra, Alexander G. Schwing, Alexander Kirillov, Rohit Girdhar. Mask2Former is a unified framework for panoptic, instance and semantic segmentation and features significant performance and efficiency improvements over [MaskFormer](maskformer). The abstract from the paper is the following: *Image segmentation groups pixels with different semantics, e.g., category or instance membership. Each choice of semantics defines a task. While only the semantics of each task differ, current research focuses on designing specialized architectures for each task. We present Masked-attention Mask Transformer (Mask2Former), a new architecture capable of addressing any image segmentation task (panoptic, instance or semantic). Its key components include masked attention, which extracts localized features by constraining cross-attention within predicted mask regions. In addition to reducing the research effort by at least three times, it outperforms the best specialized architectures by a significant margin on four popular datasets. Most notably, Mask2Former sets a new state-of-the-art for panoptic segmentation (57.8 PQ on COCO), instance segmentation (50.1 AP on COCO) and semantic segmentation (57.7 mIoU on ADE20K).* <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/mask2former_architecture.jpg" alt="drawing" width="600"/> <small> Mask2Former architecture. Taken from the <a href="https://huggingface.co/papers/2112.01527">original paper.</a> </small> This model was contributed by [Shivalika Singh](https://huggingface.co/shivi) and [Alara Dirik](https://huggingface.co/adirik). The original code can be found [here](https://github.com/facebookresearch/Mask2Former). ## Usage tips - Mask2Former uses the same preprocessing and postprocessing steps as [MaskFormer](maskformer). Use [`Mask2FormerImageProcessor`] or [`AutoImageProcessor`] to prepare images and optional targets for the model. - To get the final segmentation, depending on the task, you can call [`~Mask2FormerImageProcessor.post_process_semantic_segmentation`] or [`~Mask2FormerImageProcessor.post_process_instance_segmentation`] or [`~Mask2FormerImageProcessor.post_process_panoptic_segmentation`]. All three tasks can be solved using [`Mask2FormerForUniversalSegmentation`] output, panoptic segmentation accepts an optional `label_ids_to_fuse` argument to fuse instances of the target object/s (e.g. sky) together. ## Resources A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with Mask2Former. - Demo notebooks regarding inference + fine-tuning Mask2Former on custom data can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/Mask2Former). - Scripts for finetuning [`Mask2Former`] with [`Trainer`] or [Accelerate](https://huggingface.co/docs/accelerate/index) can be found [here](https://github.com/huggingface/transformers/tree/main/examples/pytorch/instance-segmentation). If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we will review it. The resource should ideally demonstrate something new instead of duplicating an existing resource. ## Mask2FormerConfig [[autodoc]] Mask2FormerConfig ## MaskFormer specific outputs [[autodoc]] models.mask2former.modeling_mask2former.Mask2FormerModelOutput [[autodoc]] models.mask2former.modeling_mask2former.Mask2FormerForUniversalSegmentationOutput ## Mask2FormerModel [[autodoc]] Mask2FormerModel - forward ## Mask2FormerForUniversalSegmentation [[autodoc]] Mask2FormerForUniversalSegmentation - forward ## Mask2FormerImageProcessor [[autodoc]] Mask2FormerImageProcessor - preprocess - encode_inputs - post_process_semantic_segmentation - post_process_instance_segmentation - post_process_panoptic_segmentation ## Mask2FormerImageProcessorFast [[autodoc]] Mask2FormerImageProcessorFast - preprocess - post_process_semantic_segmentation - post_process_instance_segmentation - post_process_panoptic_segmentation
transformers/docs/source/en/model_doc/mask2former.md/0
{ "file_path": "transformers/docs/source/en/model_doc/mask2former.md", "repo_id": "transformers", "token_count": 1474 }
395
<!--Copyright 2024 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. --> *This model was released on 2024-09-25 and added to Hugging Face Transformers on 2024-09-25.* # Mllama <div class="flex flex-wrap space-x-1"> <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white"> </div> ## Overview The [Llama 3.2-Vision](https://ai.meta.com/blog/llama-3-2-connect-2024-vision-edge-mobile-devices/) collection of multimodal large language models (LLMs) is a collection of pretrained and instruction-tuned image reasoning generative models in 11B and 90B sizes (text \+ images in / text out). The Llama 3.2-Vision instruction-tuned models are optimized for visual recognition, image reasoning, captioning, and answering general questions about an image. **Model Architecture:** Llama 3.2-Vision is built on top of Llama 3.1 text-only model, which is an auto-regressive language model that uses an optimized transformer architecture. The tuned versions use supervised fine-tuning (SFT) and reinforcement learning with human feedback (RLHF) to align with human preferences for helpfulness and safety. To support image recognition tasks, the Llama 3.2-Vision model uses a separately trained vision adapter that integrates with the pre-trained Llama 3.1 language model. The adapter consists of a series of cross-attention layers that feed image encoder representations into the core LLM. ## Usage Tips - For image+text and text inputs use `MllamaForConditionalGeneration`. - For text-only inputs use `MllamaForCausalLM` for generation to avoid loading vision tower. - Each sample can contain multiple images, and the number of images can vary between samples. The processor will pad the inputs to the maximum number of images across samples and to a maximum number of tiles within each image. - The text passed to the processor should have the `"<|image|>"` tokens where the images should be inserted. - The processor has its own `apply_chat_template` method to convert chat messages to text that can then be passed as text to the processor. If you're using `transformers>=4.49.0`, you can also get a vectorized output from `apply_chat_template`. See the **Usage Examples** below for more details on how to use it. <Tip warning={true}> Mllama has an extra token used as a placeholder for image positions in the text. It means that input ids and an input embedding layer will have an extra token. But since the weights for input and output embeddings are not tied, the `lm_head` layer has one less token and will fail if you want to calculate loss on image tokens or apply some logit processors. In case you are training, make sure to mask out special `"<|image|>"` tokens in the `labels` as the model should not be trained on predicting them. Otherwise if you see CUDA-side index errors when generating, use the below code to expand the `lm_head` by one more token. ```python old_embeddings = model.get_output_embeddings() num_tokens = model.vocab_size + 1 resized_embeddings = model._get_resized_lm_head(old_embeddings, new_num_tokens=num_tokens, mean_resizing=True) resized_embeddings.requires_grad_(old_embeddings.weight.requires_grad) model.set_output_embeddings(resized_embeddings) ``` </Tip> ## Usage Example #### Instruct model ```python import torch from transformers import MllamaForConditionalGeneration, AutoProcessor model_id = "meta-llama/Llama-3.2-11B-Vision-Instruct" model = MllamaForConditionalGeneration.from_pretrained(model_id, device_map="auto", dtype=torch.bfloat16) processor = AutoProcessor.from_pretrained(model_id) messages = [ [ { "role": "user", "content": [ {"type": "image", "url": "https://llava-vl.github.io/static/images/view.jpg"}, {"type": "text", "text": "What does the image show?"} ] } ], ] inputs = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(model.device) output = model.generate(**inputs, max_new_tokens=25) print(processor.decode(output[0])) ``` #### Base model ```python import requests import torch from PIL import Image from transformers import MllamaForConditionalGeneration, AutoProcessor model_id = "meta-llama/Llama-3.2-11B-Vision" model = MllamaForConditionalGeneration.from_pretrained(model_id, device_map="auto", dtype=torch.bfloat16) processor = AutoProcessor.from_pretrained(model_id) prompt = "<|image|>If I had to write a haiku for this one" url = "https://llava-vl.github.io/static/images/view.jpg" raw_image = Image.open(requests.get(url, stream=True).raw) inputs = processor(text=prompt, images=raw_image, return_tensors="pt").to(model.device) output = model.generate(**inputs, do_sample=False, max_new_tokens=25) print(processor.decode(output[0], skip_special_tokens=True)) ``` ## MllamaConfig [[autodoc]] MllamaConfig ## MllamaProcessor [[autodoc]] MllamaProcessor ## MllamaImageProcessor [[autodoc]] MllamaImageProcessor ## MllamaForConditionalGeneration [[autodoc]] MllamaForConditionalGeneration - forward ## MllamaForCausalLM [[autodoc]] MllamaForCausalLM - forward ## MllamaTextModel [[autodoc]] MllamaTextModel - forward ## MllamaModel [[autodoc]] MllamaModel ## MllamaForCausalLM [[autodoc]] MllamaForCausalLM - forward ## MllamaVisionModel [[autodoc]] MllamaVisionModel - forward
transformers/docs/source/en/model_doc/mllama.md/0
{ "file_path": "transformers/docs/source/en/model_doc/mllama.md", "repo_id": "transformers", "token_count": 1901 }
396
<!--Copyright 2020 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. --> *This model was released on 2020-10-22 and added to Hugging Face Transformers on 2020-11-17.* <div style="float: right;"> <div class="flex flex-wrap space-x-1"> <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white"> </div> </div> # mT5 [mT5](https://huggingface.co/papers/2010.11934) is a multilingual variant of [T5](./t5), training on 101 languages. It also incorporates a new "accidental translation" technique to prevent the model from incorrectly translating predictions into the wrong language. You can find all the original [mT5] checkpoints under the [mT5](https://huggingface.co/collections/google/mt5-release-65005f1a520f8d7b4d039509) collection. > [!TIP] > This model was contributed by [patrickvonplaten](https://huggingface.co/patrickvonplaten). > > Click on the mT5 models in the right sidebar for more examples of how to apply mT5 to different language tasks. The example below demonstrates how to summarize text with [`Pipeline`], [`AutoModel`], and from the command line. <hfoptions id="usage"> <hfoption id="Pipeline"> ```python import torch from transformers import pipeline pipeline = pipeline( task="text2text-generation", model="csebuetnlp/mT5_multilingual_XLSum", dtype=torch.float16, device=0 ) pipeline("""Plants are remarkable organisms that produce their own food using a method called photosynthesis. This process involves converting sunlight, carbon dioxide, and water into glucose, which provides energy for growth. Plants play a crucial role in sustaining life on Earth by generating oxygen and serving as the foundation of most ecosystems.""") ``` </hfoption> <hfoption id="AutoModel"> ```python import torch from transformers import AutoModelForSeq2SeqLM, AutoTokenizer tokenizer = AutoTokenizer.from_pretrained( "csebuetnlp/mT5_multilingual_XLSum" ) model = AutoModelForSeq2SeqLM.from_pretrained( "csebuetnlp/mT5_multilingual_XLSum", dtype=torch.float16, device_map="auto", ) input_text = """Plants are remarkable organisms that produce their own food using a method called photosynthesis. This process involves converting sunlight, carbon dioxide, and water into glucose, which provides energy for growth. Plants play a crucial role in sustaining life on Earth by generating oxygen and serving as the foundation of most ecosystems.""" input_ids = tokenizer(input_text, return_tensors="pt").to(model.device) output = model.generate(**input_ids, cache_implementation="static") print(tokenizer.decode(output[0], skip_special_tokens=True)) ``` </hfoption> <hfoption id="transformers CLI"> ```bash echo -e "Plants are remarkable organisms that produce their own food using a method called photosynthesis." | transformers run --task text2text-generation --model csebuetnlp/mT5_multilingual_XLSum --device 0 ``` </hfoption> </hfoptions> Quantization reduces the memory burden of large models by representing the weights in a lower precision. Refer to the [Quantization](../quantization/overview) overview for more available quantization backends. The example below uses [bitsandbytes](../quantization/bitsandbytes) to only quantize the weights to int4. ```python import torch from transformers import BitsAndBytesConfig, AutoModelForSeq2SeqLM, AutoTokenizer quantization_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_quant_type="nf4" ) model = AutoModelForSeq2SeqLM.from_pretrained( "csebuetnlp/mT5_multilingual_XLSum", dtype=torch.bfloat16, device_map="auto", quantization_config=quantization_config ) tokenizer = AutoTokenizer.from_pretrained( "csebuetnlp/mT5_multilingual_XLSum" ) input_text = """Plants are remarkable organisms that produce their own food using a method called photosynthesis. This process involves converting sunlight, carbon dioxide, and water into glucose, which provides energy for growth. Plants play a crucial role in sustaining life on Earth by generating oxygen and serving as the foundation of most ecosystems.""" input_ids = tokenizer(input_text, return_tensors="pt").to(model.device) output = model.generate(**input_ids, cache_implementation="static") print(tokenizer.decode(output[0], skip_special_tokens=True)) ``` ## Notes - mT5 must be fine-tuned for downstream tasks because it was only pretrained on the [mc4](https://huggingface.co/datasets/mc4) dataset. ## MT5Config [[autodoc]] MT5Config ## MT5Tokenizer [[autodoc]] MT5Tokenizer See [`T5Tokenizer`] for all details. ## MT5TokenizerFast [[autodoc]] MT5TokenizerFast See [`T5TokenizerFast`] for all details. ## MT5Model [[autodoc]] MT5Model ## MT5ForConditionalGeneration [[autodoc]] MT5ForConditionalGeneration ## MT5EncoderModel [[autodoc]] MT5EncoderModel ## MT5ForSequenceClassification [[autodoc]] MT5ForSequenceClassification ## MT5ForTokenClassification [[autodoc]] MT5ForTokenClassification ## MT5ForQuestionAnswering [[autodoc]] MT5ForQuestionAnswering
transformers/docs/source/en/model_doc/mt5.md/0
{ "file_path": "transformers/docs/source/en/model_doc/mt5.md", "repo_id": "transformers", "token_count": 1785 }
397
<!--Copyright 2024 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 contains specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> *This model was released on 2024-04-22 and added to Hugging Face Transformers on 2024-04-24.* # Phi-3 <div class="flex flex-wrap space-x-1"> <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white"> <img alt="FlashAttention" src="https://img.shields.io/badge/%E2%9A%A1%EF%B8%8E%20FlashAttention-eae0c8?style=flat"> <img alt="SDPA" src="https://img.shields.io/badge/SDPA-DE3412?style=flat&logo=pytorch&logoColor=white"> <img alt="Tensor parallelism" src="https://img.shields.io/badge/Tensor%20parallelism-06b6d4?style=flat&logoColor=white"> </div> ## Overview The Phi-3 model was proposed in [Phi-3 Technical Report: A Highly Capable Language Model Locally on Your Phone](https://huggingface.co/papers/2404.14219) by Microsoft. ### Summary The abstract from the Phi-3 paper is the following: We introduce phi-3-mini, a 3.8 billion parameter language model trained on 3.3 trillion tokens, whose overall performance, as measured by both academic benchmarks and internal testing, rivals that of models such as Mixtral 8x7B and GPT-3.5 (e.g., phi-3-mini achieves 69% on MMLU and 8.38 on MT-bench), despite being small enough to be deployed on a phone. The innovation lies entirely in our dataset for training, a scaled-up version of the one used for phi-2, composed of heavily filtered web data and synthetic data. The model is also further aligned for robustness, safety, and chat format. We also provide some initial parameter-scaling results with a 7B and 14B models trained for 4.8T tokens, called phi-3-small and phi-3-medium, both significantly more capable than phi-3-mini (e.g., respectively 75% and 78% on MMLU, and 8.7 and 8.9 on MT-bench). The original code for Phi-3 can be found [here](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct). ## Usage tips - This model is very similar to `Llama` with the main difference of [`Phi3SuScaledRotaryEmbedding`] and [`Phi3YarnScaledRotaryEmbedding`], where they are used to extend the context of the rotary embeddings. The query, key and values are fused, and the MLP's up and gate projection layers are also fused. - The tokenizer used for this model is identical to the [`LlamaTokenizer`], with the exception of additional tokens. ## How to use Phi-3 <Tip warning={true}> Phi-3 has been integrated in the development version (4.40.0.dev) of `transformers`. Until the official version is released through `pip`, ensure that you are doing one of the following: * When loading the model, ensure that `trust_remote_code=True` is passed as an argument of the `from_pretrained()` function. * Update your local `transformers` to the development version: `pip uninstall -y transformers && pip install git+https://github.com/huggingface/transformers`. The previous command is an alternative to cloning and installing from the source. </Tip> ```python >>> from transformers import AutoModelForCausalLM, AutoTokenizer >>> model = AutoModelForCausalLM.from_pretrained("microsoft/Phi-3-mini-4k-instruct") >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-4k-instruct") >>> messages = [{"role": "user", "content": "Can you provide ways to eat combinations of bananas and dragonfruits?"}] >>> inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt") >>> outputs = model.generate(inputs, max_new_tokens=32) >>> text = tokenizer.batch_decode(outputs)[0] >>> print(text) <|user|> Can you provide ways to eat combinations of bananas and dragonfruits?<|end|><|assistant|> Certainly! Bananas and dragonfruits can be combined in various delicious ways. Here are some creative ideas for incorporating both fruits ``` ## Phi3Config [[autodoc]] Phi3Config <frameworkcontent> <pt> ## Phi3Model [[autodoc]] Phi3Model - forward ## Phi3ForCausalLM [[autodoc]] Phi3ForCausalLM - forward - generate ## Phi3ForSequenceClassification [[autodoc]] Phi3ForSequenceClassification - forward ## Phi3ForTokenClassification [[autodoc]] Phi3ForTokenClassification - forward </pt> </frameworkcontent>
transformers/docs/source/en/model_doc/phi3.md/0
{ "file_path": "transformers/docs/source/en/model_doc/phi3.md", "repo_id": "transformers", "token_count": 1463 }
398
<!--Copyright 2025 The Qwen Team and The HuggingFace Inc. 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. --> *This model was released on 2025-02-19 and added to Hugging Face Transformers on 2025-01-23.* <div style="float: right;"> <div class="flex flex-wrap space-x-1"> <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white"> <img alt="FlashAttention" src="https://img.shields.io/badge/%E2%9A%A1%EF%B8%8E%20FlashAttention-eae0c8?style=flat"> <img alt="SDPA" src="https://img.shields.io/badge/SDPA-DE3412?style=flat&logo=pytorch&logoColor=white"> </div> </div> # Qwen2.5-VL [Qwen2.5-VL](https://huggingface.co/papers/2502.13923) is a multimodal vision-language model, available in 3B, 7B, and 72B parameters, pretrained on 4.1T tokens. The model introduces window attention in the ViT encoder to accelerate training and inference, dynamic FPS sampling on the spatial and temporal dimensions for better video understanding across different sampling rates, and an upgraded MRoPE (multi-resolutional rotary positional encoding) mechanism to better capture and learn temporal dynamics. You can find all the original Qwen2.5-VL checkpoints under the [Qwen2.5-VL](https://huggingface.co/collections/Qwen/qwen25-vl-6795ffac22b334a837c0f9a5) collection. > [!TIP] > Click on the Qwen2.5-VL models in the right sidebar for more examples of how to apply Qwen2.5-VL to different vision and language tasks. The example below demonstrates how to generate text based on an image with [`Pipeline`] or the [`AutoModel`] class. <hfoptions id="usage"> <hfoption id="Pipeline"> ```py import torch from transformers import pipeline pipe = pipeline( task="image-text-to-text", model="Qwen/Qwen2.5-VL-7B-Instruct", device=0, dtype=torch.bfloat16 ) messages = [ { "role": "user", "content": [ { "type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg", }, { "type": "text", "text": "Describe this image."}, ] } ] pipe(text=messages,max_new_tokens=20, return_full_text=False) ``` </hfoption> <hfoption id="AutoModel"> ```py import torch from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor model = Qwen2_5_VLForConditionalGeneration.from_pretrained( "Qwen/Qwen2.5-VL-7B-Instruct", dtype=torch.float16, device_map="auto", attn_implementation="sdpa" ) processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct") messages = [ { "role":"user", "content":[ { "type":"image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" }, { "type":"text", "text":"Describe this image." } ] } ] inputs = processor.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt" ).to(model.device) generated_ids = model.generate(**inputs, max_new_tokens=128) generated_ids_trimmed = [ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids) ] output_text = processor.batch_decode( generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False ) print(output_text) ``` </hfoption> </hfoptions> Quantization reduces the memory burden of large models by representing the weights in a lower precision. Refer to the [Quantization](../quantization/overview) overview for more available quantization backends. The example below uses [torchao](../quantization/torchao) to only quantize the weights to int4. ```python import torch from transformers import TorchAoConfig, Qwen2_5_VLForConditionalGeneration, AutoProcessor quantization_config = TorchAoConfig("int4_weight_only", group_size=128) model = Qwen2_5_VLForConditionalGeneration.from_pretrained( "Qwen/Qwen2.5-VL-7B-Instruct", dtype=torch.bfloat16, device_map="auto", quantization_config=quantization_config ) ``` ### Notes - Use Qwen2.5-VL for video inputs by setting `"type": "video"` as shown below. ```python conversation = [ { "role": "user", "content": [ {"type": "video", "path": "/path/to/video.mp4"}, {"type": "text", "text": "What happened in the video?"}, ], } ] inputs = processor.apply_chat_template( conversation, video_fps=1, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt" ).to(model.device) # Inference: Generation of the output output_ids = model.generate(**inputs, max_new_tokens=128) generated_ids = [output_ids[len(input_ids):] for input_ids, output_ids in zip(inputs.input_ids, output_ids)] output_text = processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True) print(output_text) ``` - Use Qwen2.5-VL for a mixed batch of inputs (images, videos, text). Add labels when handling multiple images or videos for better reference as show below. ```python import torch from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor model = Qwen2_5_VLForConditionalGeneration.from_pretrained( "Qwen/Qwen2.5-VL-7B-Instruct", dtype=torch.float16, device_map="auto", attn_implementation="sdpa" ) processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct") conversation = [ { "role": "user", "content": [ {"type": "image"}, {"type": "text", "text": "Hello, how are you?"} ] }, { "role": "assistant", "content": "I'm doing well, thank you for asking. How can I assist you today?" }, { "role": "user", "content": [ {"type": "text", "text": "Can you describe these images and video?"}, {"type": "image"}, {"type": "image"}, {"type": "video"}, {"type": "text", "text": "These are from my vacation."} ] }, { "role": "assistant", "content": "I'd be happy to describe the images and video for you. Could you please provide more context about your vacation?" }, { "role": "user", "content": "It was a trip to the mountains. Can you see the details in the images and video?" } ] # default: prompt_without_id = processor.apply_chat_template(conversation, add_generation_prompt=True) # Excepted output: '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Hello, how are you?<|im_end|>\n<|im_start|>assistant\nI'm doing well, thank you for asking. How can I assist you today?<|im_end|>\n<|im_start|>user\nCan you describe these images and video?<|vision_start|><|image_pad|><|vision_end|><|vision_start|><|image_pad|><|vision_end|><|vision_start|><|video_pad|><|vision_end|>These are from my vacation.<|im_end|>\n<|im_start|>assistant\nI'd be happy to describe the images and video for you. Could you please provide more context about your vacation?<|im_end|>\n<|im_start|>user\nIt was a trip to the mountains. Can you see the details in the images and video?<|im_end|>\n<|im_start|>assistant\n' # add ids prompt_with_id = processor.apply_chat_template(conversation, add_generation_prompt=True, add_vision_id=True) # Excepted output: '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\nPicture 1: <|vision_start|><|image_pad|><|vision_end|>Hello, how are you?<|im_end|>\n<|im_start|>assistant\nI'm doing well, thank you for asking. How can I assist you today?<|im_end|>\n<|im_start|>user\nCan you describe these images and video?Picture 2: <|vision_start|><|image_pad|><|vision_end|>Picture 3: <|vision_start|><|image_pad|><|vision_end|>Video 1: <|vision_start|><|video_pad|><|vision_end|>These are from my vacation.<|im_end|>\n<|im_start|>assistant\nI'd be happy to describe the images and video for you. Could you please provide more context about your vacation?<|im_end|>\n<|im_start|>user\nIt was a trip to the mountains. Can you see the details in the images and video?<|im_end|>\n<|im_start|>assistant\n' ``` - Use the `min_pixels` and `max_pixels` parameters in [`AutoProcessor`] to set the resolution. ```python min_pixels = 224*224 max_pixels = 2048*2048 processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels) ``` Higher resolution can require more compute whereas reducing the resolution can save memory as follows: ```python min_pixels = 256*28*28 max_pixels = 1024*28*28 processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels) ``` ## Qwen2_5_VLConfig [[autodoc]] Qwen2_5_VLConfig ## Qwen2_5_VLTextConfig [[autodoc]] Qwen2_5_VLTextConfig ## Qwen2_5_VLProcessor [[autodoc]] Qwen2_5_VLProcessor ## Qwen2_5_VLTextModel [[autodoc]] Qwen2_5_VLTextModel - forward ## Qwen2_5_VLModel [[autodoc]] Qwen2_5_VLModel - forward ## Qwen2_5_VLForConditionalGeneration [[autodoc]] Qwen2_5_VLForConditionalGeneration - forward
transformers/docs/source/en/model_doc/qwen2_5_vl.md/0
{ "file_path": "transformers/docs/source/en/model_doc/qwen2_5_vl.md", "repo_id": "transformers", "token_count": 4175 }
399